Avatar of SeanDoherty49
SeanDoherty49 asked on

Setting default value of Dropdown

I have populated a dropdown box, and I have selected the the default value ($Current) that I want to set it to.  This is working fine.  I just want to set the DropDown to $Current.
 
The code is shown below.
 
Any help would be much appreciated.
 
Thanks
John
 
<?php
mysql_select_db($database_mcr500, $mcr500);
$query_NextRideOut = "SELECT  coursedates.Filename, coursedates.CourseDates, coursedates.Destination FROM coursedates WHERE coursedates.CourseDates >= '$date' ORDER BY coursedates.CourseDates";
$NextRideOut = mysql_query($query_NextRideOut, $mcr500) or die(mysql_error());
$row_NextRideOut = mysql_fetch_assoc($NextRideOut);
$totalRows_NextRideOut = mysql_num_rows($NextRideOut);
 
if ($totalRows_NextRideOut>0)
  { $Current = $row_NextRideOut['Filename'].$row_NextRideOut['Destination']; }
else
  { $Current = $row_Courses['Filename'].$row_NextCourses['Destination'];}
?>
 
<select name="CourseDates"  ID = "21" size="1" Style="float:right" Width = "300"  onchange"javascript:ajax_post()" method = "post";>
 
 
 <?php do {  ?>
 <option value=" <?php echo $row_Courses['Filename'].$row_Courses['CourseDates']?>">
 <?php echo $row_Courses['CourseNo'].".....".$row_Courses['CourseDates'].".....".$row_Courses['Destination']?></option>
 <?php
 
 }
 while ($row_Courses = mysql_fetch_assoc($Courses));
 $rows = mysql_num_rows($Courses);
 if($rows > 0) {
     mysql_data_seek($Courses, 0);
     $row_Courses = mysql_fetch_assoc($Courses);
  } 
?>

Open in new window

DropDown.doc
Scripting LanguagesPHP

Avatar of undefined
Last Comment
Michel Plungjan

8/22/2022 - Mon
SOLUTION
Michel Plungjan

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
SOLUTION
Ray Paseur

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question
ASKER
SeanDoherty49

I do not understand the comment above from Mplungjan,
I have copied the code from your DOC to this question and wrapped in [ code ] tags and added PHP to the zones.  Are the <?PHP and ?> code tags?

This code looks identical to mine, I only attached it as a Doc so that I could show colors used in Dreamweaver.

I have many years experience of programming, lately VBA in MsAccess.  I understand MySQL but am totally new to PHP.


I am getting numerous syntax errors when I enter your code.  I have been putting in <?php ?> around much of my code.  

I left out this code.  The MySQL is selecting the right records from the database.  $Current selects  the next date if there is one or else picks the first one in the recordset.

The variables that  Ray_Paseur thought were missing are shown there.

mysql_select_db($database_mcr500, $mcr500);
$date = Date("y")."/".Date("m")."/".Date("d");
$query_Courses = "SELECT coursedates.CourseDates, coursedates.CourseNo, coursedates.Destination, coursedates.Filename FROM coursedates ORDER BY  coursedates.CourseNo";
$Courses = mysql_query($query_Courses, $mcr500) or die(mysql_error());
$row_Courses = mysql_fetch_assoc($Courses);


mysql_select_db($database_mcr500, $mcr500);
$query_NextRideOut = "SELECT  coursedates.Filename, coursedates.CourseDates, coursedates.Destination FROM coursedates WHERE coursedates.CourseDates >= '$date' ORDER BY coursedates.CourseDates";
$NextRideOut = mysql_query($query_NextRideOut, $mcr500) or die(mysql_error());
$row_NextRideOut = mysql_fetch_assoc($NextRideOut);
$totalRows_NextRideOut = mysql_num_rows($NextRideOut);
if ($totalRows_NextRideOut>0)
      { $Current = $row_NextRideOut['Filename'].$row_NextRideOut['Destination']; }
else
      { $Current = $row_Courses['Filename'].$row_NextCourses['Destination'];}
?>
Ray Paseur

Please read my comments carefully.  There is no data base connection.  This is different from a data base "selection" which was present in the script twice, but not necessary more than once.  We can only see what you post here, and over the years I have found that assuming something exists when it is not posted is usually a failing strategy.

The point of using the code snippet feature here at EE is that the code snippet gives us a unispace font, line numbers, a "select all" so we can copy, etc.  This makes more sense than attaching a Word document.  We do not need the color highlighting of Dreamweaver; Dreamweaver is a stumbling block, not a stepping stone.

Since you're working with DATETIME values in the SQL tables, this article will be helpful.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

Please post the CREATE TABLE statements for the tables in question, and I'll see what I can do to help you get working queries and logic.  Thanks, ~Ray
ASKER
SeanDoherty49

I am using a Local Server for database connection and this is working fine.  I installed Wamp Server and I am using PHPMyAdmin to store/access the data.

The data was converted from existing data into csv and imported.  The SQL below was generated by PHPMyAdmin export routine.

I accept that my date routine is rough and ready and I will explore that further in future, but the SQL query does select the next available date, at the moment, 15th September.  I just want to show this in the dropdown.  I have attached a screen grab.  I thought I had made it clear that the SQL queries were working OK, but I guess I did not.  I have attached a Dialogue box showing my local server.

Thanks

John

-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Sep 04, 2013 at 08:25 AM
-- Server version: 5.5.24-log
-- PHP Version: 5.4.3

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

--
-- Database: `mcr500`
--

-- --------------------------------------------------------

--
-- Table structure for table `coursedates`
--

CREATE TABLE IF NOT EXISTS `coursedates` (
  `CourseDates` varchar(6) NOT NULL DEFAULT '',
  `CourseNo` varchar(3) DEFAULT NULL,
  `Destination` varchar(18) DEFAULT NULL,
  `Filename` varchar(9) DEFAULT NULL,
  PRIMARY KEY (`CourseDates`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

--
-- Dumping data for table `coursedates`
--

INSERT INTO `coursedates` (`CourseDates`, `CourseNo`, `Destination`, `Filename`) VALUES
('01-Sep', '3 1', 'Poplar 2000', '2013Sep01'),
('02-Jun', '2 1', 'Poplar 2000', '2013Jun02'),
('03-Mar', '1 1', 'Poplar 2000', '2013Mar03'),
('03-Nov', '3 5', 'Davenort Marton', '2013Nov03'),
('04-Aug', '2 5', 'Poplar 2000', '2013Aug04'),
('05-May', '1 5', '1-5', '2013May05'),
('06-Oct', '3 3', 'J & S Legends Cafe', '2013Oct06'),
('07-Apr', '1 3', 'Yondermans', '2013Apr07'),
('07-Jul', '2 3', 'Cat & Fiddle', '2013Jul07'),
('15-Sep', '3 2', 'Buxton', '2013Sep15'),
('16-Jun', '2 2', 'Little Chef', '2013Jun16'),
('17-Mar', '1 2', 'Lets Eat', '2013Mar17'),
('17-Nov', '3 6', '3-6', '2013Nov17'),
('18-Aug', '2 6', '2-6', '2013Aug18'),
('19-May', '1 6', '1-6', '2013May19'),
('20-Oct', '3 4', 'Windy Ridge Cafe', '2013Oct20'),
('21-Apr', '1 4', 'Glossop Cafe', '2013Apr21'),
('21-Jul', '2 4', 'Yondermans', '2013Jul21');
Screengrab.jpg
Database.png
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
Michel Plungjan

All that aside... Is my code not correct, Ray?
ASKER
SeanDoherty49

I have attached the code.  I have had far more PHP code tags in my code and I cannot see where to start to satisfy the syntax checker now.



Help please

John
Code-Syntax-error.png
Ray Paseur

Help coming - give me a moment to set up my tests!
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
SeanDoherty49

Thanks

John
Michel Plungjan

I wrote it on my iPhone so with my bad eyesight I put a quote in front of .$val. wrong

<?php do {  
  $val = $row_Courses['Filename'].$row_Courses['CourseDates'];
  echo '<option value="'.$val.'"';
  if ($val==$Current) echo " selected";
  echo ">".$row_Courses['CourseNo'].".....".$row_Courses['CourseDates'].".....".$row_Courses['Destination']."</option>";

Open in new window


You also need a

?>

before the </select>
Ray Paseur

Here is how I might do it.  Some annotation follows.

First and foremost, you must not use the MySQL API extension (that is one of many things that are wrong about the Dreamweaver code).  This article explains why PHP is doing away with MySQL and shows the correct way forward.
https://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_11177-PHP-MySQL-Deprecated-as-of-PHP-5-5-0.html

Line 9-23  Man page references that you would want to become familiar with.

Line 26-48  Connect to the DB server.  This is the sort of thing that you might package into a script initialization subscript, along with other initialization like session_start().  You might require() this subscript at the top of all of your scripts that build your web site.

Line 51-137  This is "housekeeping" for this script.  It creates the data base table and loads it so I can run queries.  Since I am using a temporary table, I can rerun this script over and over for repeated tests (and little tweaks) with variants of the code and data set.  Note line 112, where I took the fragment date and reformatted it into the ISO-8601 date, which is the correct format for all internal representations of date/time values.

Line 140-154  This is the "action=" script.  If you put the action= attribute into the form tag, the submit request will go to the URL in the action= attribute.  If you omit it, the request will go to the current URL.  If you omit the action= attribute, as I did here (line 214) you can keep the action script and the form script in a single script file, which makes it easy to keep all your work in one place.

The action script takes what was submitted, which in this case is the "id" value that points to a row in the data base table.  This id is used to look up the information from the data base table and print it out.

Line 157  This is the beginning of the "form" script that creates the HTML document.

Line 158  I wasn't exactly sure what you wanted here, so I made an arbitrary choice.  The value is used in the WHERE clause of the following query.

Line 160-174  This runs the query to get all of the data we need to create the dropdown-select.  After the query is run, we test for success, and if there is a failure of the query we use trigger_error() to show us the query and the failure information.

Line 177-209  This code uses the results set from the query to generate the dropdown-select.  We use string concatenation (the dot) to put the parts of the results set into HTML tags.

Line 184  If you wanted to pre-select one of the options, you might add some bit of logic to the display.  Without any pre-select, the request will automatically select the first option element in the select tag.

Line 187  Formats the ISO-standard date into a "pretty date" for client display.

Line 189-195  Creates the <option value= part of the control, using the id from the row of the results set.  Note that this is the signal we use in the action script to know what the client selected.

Line 197-205  Creates the visual display part of the option and wraps up the tag.  You can probably guess why I use the string concatenation operators and put fragments on each line -- it makes this easier to read, and makes it easier to modify.  And when I accidentally create the inevitable Parse Error, I will be able to find the error more quickly if there is less complex syntax on the error line.

Line 209  Finishes the select/option variable.

Line 212-220  Creates the HTML document, including the form and the select/optionw we built from the data base query.  This uses the heredoc notation, which I find enormously useful for templates that require variable substitution.  Don't be put off by the big warning on the heredoc man page - just follow its advice.

<?php // RAY_temp_seandoherty49.php
error_reporting(E_ALL);


// SEE http://www.experts-exchange.com/Programming/Languages/Scripting/Q_28229734.html#a39462933
// THIS SCRIPT DEMONSTRATES SOME OF THE BASICS OF MySQLi + PHP


// THE ABSOLUTE MINIMUM YOU MUST UNDERSTAND TO USE PHP AND MYSQLI
// MAN PAGE: http://php.net/manual/en/mysqli.overview.php
// MAN PAGE: http://php.net/manual/en/class.mysqli.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-stmt.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-result.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-warning.php
// MAN PAGE: http://php.net/manual/en/class.mysqli-sql-exception.php <-- DID NOT WORK PHP 5.3+, MySQL 5.1+
// MAN PAGE: http://php.net/manual/en/mysqli.construct.php
// MAN PAGE: http://php.net/manual/en/mysqli.real-escape-string.php
// MAN PAGE: http://php.net/manual/en/mysqli.query.php
// MAN PAGE: http://php.net/manual/en/mysqli.errno.php
// MAN PAGE: http://php.net/manual/en/mysqli.error.php
// MAN PAGE: http://php.net/manual/en/mysqli.insert-id.php
// MAN PAGE: http://php.net/manual/en/mysqli-result.num-rows.php
// MAN PAGE: http://php.net/manual/en/mysqli-result.fetch-object.php


// DATABASE CONNECTION AND SELECTION VARIABLES - GET THESE FROM YOUR HOSTING COMPANY
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";
$db_user = "??";
$db_word = "??";

// OPEN A CONNECTION TO THE DATA BASE SERVER AND SELECT THE DB
$mysqli = new mysqli($db_host, $db_user, $db_word, $db_name);

// DID THE CONNECT/SELECT WORK OR FAIL?
if ($mysqli->connect_errno)
{
    $err
    = "CONNECT FAIL: "
    . $mysqli->connect_errno
    . ' '
    . $mysqli->connect_error
    ;
    trigger_error($err, E_USER_ERROR);
}

// ACTIVATE THIS TO SHOW WHAT THE DB CONNECTION OBJECT LOOKS LIKE
// var_dump($mysqli);


// CREATE THE TABLE FOR THE TEST DATA
$sql =
"
CREATE TEMPORARY TABLE `coursedates`
( id            INT         NOT NULL AUTO_INCREMENT PRIMARY KEY
, `CourseDates` DATETIME    NOT NULL DEFAULT '0000-00-00T00:00:00'
, `CourseNo`    VARCHAR(3)  NOT NULL DEFAULT ''
, `Destination` VARCHAR(18) NOT NULL DEFAULT ''
, `Filename`    VARCHAR(9)  NOT NULL DEFAULT ''
)
ENGINE=InnoDB
DEFAULT CHARSET=utf8
"
;
// RUN THE QUERY TO CREATE THE TABLE
$res = $mysqli->query($sql);

// IF mysqli::query() RETURNS FALSE, LOG AND SHOW THE ERROR
if (!$res)
{
    $err
    = 'QUERY FAILURE:'
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    . ' QUERY: '
    . $sql
    ;
    trigger_error($err, E_USER_ERROR);
}


// THE TEST DATA MUST BE CHANGED TO NORMAL ISO-8601 DATES
$raw = array
(
array('01-Sep', '3 1', 'Poplar 2000', '2013Sep01'),
array('02-Jun', '2 1', 'Poplar 2000', '2013Jun02'),
array('03-Mar', '1 1', 'Poplar 2000', '2013Mar03'),
array('03-Nov', '3 5', 'Davenort Marton', '2013Nov03'),
array('04-Aug', '2 5', 'Poplar 2000', '2013Aug04'),
array('05-May', '1 5', '1-5', '2013May05'),
array('06-Oct', '3 3', 'J & S Legends Cafe', '2013Oct06'),
array('07-Apr', '1 3', 'Yondermans', '2013Apr07'),
array('07-Jul', '2 3', 'Cat & Fiddle', '2013Jul07'),
array('15-Sep', '3 2', 'Buxton', '2013Sep15'),
array('16-Jun', '2 2', 'Little Chef', '2013Jun16'),
array('17-Mar', '1 2', 'Lets Eat', '2013Mar17'),
array('17-Nov', '3 6', '3-6', '2013Nov17'),
array('18-Aug', '2 6', '2-6', '2013Aug18'),
array('19-May', '1 6', '1-6', '2013May19'),
array('20-Oct', '3 4', 'Windy Ridge Cafe', '2013Oct20'),
array('21-Apr', '1 4', 'Glossop Cafe', '2013Apr21'),
array('21-Jul', '2 4', 'Yondermans', '2013Jul21')
)
;

// LOAD THE TEST DATA INTO THE TABLE
foreach ($raw as $row)
{
    // REFORMAT THE DATE IN COLUMN #0
    $row[0] = date('c', strtotime($row[0] . '-2013'));

    // CONSTRUCT THE QUERY STRING
    $sql = 'INSERT INTO coursedates (`CourseDates`, `CourseNo`, `Destination`, `Filename`) VALUES ';
    $sql .= '( ';
    $sql .= "'" . implode("', '", $row) . "'";
    $sql .= ' )';

    // LOAD EACH ROW INTO THE TABLE
    if (!$res = $mysqli->query($sql))
    {
        $err
        = 'QUERY FAILURE:'
        . ' ERRNO: '
        . $mysqli->errno
        . ' ERROR: '
        . $mysqli->error
        . ' QUERY: '
        . $sql
        ;
        trigger_error($err, E_USER_ERROR);
    }

    // FOR A VISUAL CHECK, LOOK AT THE QUERY STRING AS EACH ROW IS LOADED
    // var_dump($sql);
}


// IF THE REQUEST BEEN SUBMITTED, SHOW THE CLIENT CHOICE
if (!empty($_POST['CourseDates']))
{
    // CREATE AND RUN A ONE-ROW QUERY
    $cds = $mysqli->real_escape_string($_POST['CourseDates']);
    $sql = "SELECT * FROM coursedates WHERE id = '$cds' LIMIT 1";
    $res = $mysqli->query($sql);
    $row = $res->fetch_object();

    // SHOW THE ROW WE GOT
    echo '<pre>';
    print_r($row);
    echo '</pre>';
    echo PHP_EOL;
}


// WHAT IS THE DATE WE WANT TO IDENTIFY AS THE LOWER BOUNDARY FOR THE SELECTION?
$date = date('c', strtotime('Today'));

// RUN A QUERY TO GET A RESULTS SET TO CREATE THE SELECT/OPTION INPUT CONTROL TAGS
$sql = "SELECT id, Filename, CourseDates, CourseNo, Destination FROM coursedates WHERE CourseDates >= '$date' ORDER BY CourseDates";
if (!$res= $mysqli->query($sql))
{
    $err
    = 'QUERY FAILURE:'
    . ' ERRNO: '
    . $mysqli->errno
    . ' ERROR: '
    . $mysqli->error
    . ' QUERY: '
    . $sql
    ;
    trigger_error($err, E_USER_ERROR);
}


// CREATE THE SELECT/OPTION TAGS
$sel = '<select name="CourseDates">' . PHP_EOL;

// USE AN ITERATOR TO ACCESS EACH ROW OF THE RESULTS SET
while ($row = $res->fetch_object())
{
    // LOGIC TO CHOOSE A SPECIAL DEFAULT "SELECTED" OPTION HERE, MAYBE?
    $pick = NULL;

    // FORMAT THE DATE FOR USE IN THE FORM
    $dat = date('M j, Y', strtotime($row->CourseDates));

    // CREATE THE OPTION TAG (FORM VALUE IS TABLE id)
    $sel
    .= '<option '
    . $pick
    . 'value="'
    . $row->id
    . '">'

    // FORM DISPLAYS ARE FORMATTED DATE AND DESTINATION
    . $dat
    . ' '
    . htmlentities($row->Destination)

    // END OF THIS OPTION TAG
    . '</option>'
    . PHP_EOL
    ;
}

// CLOSE THE SELECT TAG
$sel .= '</select>' . PHP_EOL;


// CREATE THE HTML FORM WITH THE SELECT/OPTION
$htm = <<<EOD
<form method="post">
$sel
<input type="submit" />
</form>
EOD;

echo $htm;

Open in new window

HTH.  As you can probably see, there is a lot more to the thought processes than just copying some code.  Trying to learn programming by reading code is like trying to learn to bake by looking at an apple pie.  Sure, you can appreciate that something nice has happened, but the pie will not tell you very much about how to bake.  That's what cookbooks are for.  I encourage you to get one or two of the recommended books and spend a little time with some structured learning.  In a month of study you can put yourself a year ahead of the trial-and-error learner.

Please post back with any questions, ~Ray
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
ASKER
SeanDoherty49

Thanks for all your hard work.  I have got the routine working on my computer.  I have got to go out this evening, so will respond tomorrow.  When do you sleep.  I calculate that you are 6 hours behind us so it is now on 10:18 in the morning on the West Coast.

Thank I will get back to you tomorrow.

John
Ray Paseur

I'm on Eastern daylight time in the USA.  It is 1:26pm here, three hours later than West Coast.
ASKER
SeanDoherty49

Hi Ray,

Thank you for all the time you have taken, but you have now just managed to confuse me.  I have spent time reading and watching. I subscribed to Lynda.com and watched everything on PHP.  Most of my PHP code came from their examples. It was for CS5, although we are now in CS6.

I started programming in 1968 and have spent much time since.  I started on Fortran, and then on to BASIC, Pascal, 6502 assembler, 8086 assembler, C, and lately MS Access using VBA and SQL.  I understand relational databases, and programming logic.  I am struggling with PHP and javascript, both logic and syntax.


I also understand your desire to get me to do this right.  I did not know that what I was using was  MySQL API extension.

I have got your code working, and I now understand some of what you werte trying to ask me.

I have a few ‘include’ files and one was the connections file.  I was not even aware of this.

This is now just a hobby and I am trying to re-do the website for Mcr500.org.uk Advanced Motorcycle group.  We have 187 different runs in the year and I was to website to automatically select the next or current ride and display this date in the drop down.  This date also changes the data on a series of button to point to the map of route, or TomTom, Garmin or Google files of the route.  Selecting from the drop down also should do this.  

I have stripped down, and put all the includes, in this code.  The png file is just an image of a map.

I am quite happy to give you the points but feel that I have learnt so much I just want to get this doing what I set out to do.

I am off to buy a new bike tomorrow hopefully and then a wedding on Sturday, so will not be back to my computer until Monday.

Thank you for all your help.


<!doctype html><head></head>
<body>

<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_mcr500 = "localhost";
$database_mcr500 = "mcr500";
$username_mcr500 = "root";
$password_mcr500 = "";
$mcr500 = mysql_pconnect($hostname_mcr500, $username_mcr500, $password_mcr500) or trigger_error(mysql_error(),E_USER_ERROR);
# I haven't a clue what this next bit does.
?>

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
$date = date('c', strtotime('Today'));
# your date does not work with my query
$date = Date("y")."/".Date("m")."/".Date("d");
mysql_select_db($database_mcr500, $mcr500);
#       this is the quey for populating the dropdown
$query_Courses = "SELECT coursedates.CourseDates, coursedates.CourseNo, coursedates.Destination, coursedates.Filename FROM coursedates ORDER BY  coursedates.CourseNo";
$Courses = mysql_query($query_Courses, $mcr500) or die(mysql_error());
$row_Courses = mysql_fetch_assoc($Courses);

#this is the quey for determining the nexct ride.  I know it is not elegant but at the moment it works.
$query_NextRideOut = "SELECT  coursedates.Filename, coursedates.CourseDates, coursedates.Destination FROM coursedates WHERE coursedates.CourseDates >= '$date' ORDER BY coursedates.CourseDates";
$NextRideOut = mysql_query($query_NextRideOut, $mcr500) or die(mysql_error());
$row_NextRideOut = mysql_fetch_assoc($NextRideOut);
$totalRows_NextRideOut = mysql_num_rows($NextRideOut);
# checking the name of current ride out.  if past the last ride select the first.
if ($totalRows_NextRideOut>0)
      { $Current = $row_NextRideOut['Filename'].$row_NextRideOut['Destination']; }
else
      { $Current = $row_Courses['Filename'].$row_NextCourses['Destination'];}
      
?>
  <?php
  # function to change data for route buttons (only one shown)
      function SelectRoute($filename,$destination)
            {error_reporting(E_ALL);
                  $Ride = "Routes/".$filename;
                  $Dest = $filename." to ". $destination;
  if  (!file_exists($Ride.".pdf")      )  
                  {      $Ride = "Other Routes";       
                        $Dest = "";
                         $a = "Routes/otherroutes.pdf";
                        $at = "No route";  }      
            else
                  {      $a = $Ride.".png";
                        $at = $Dest."(Right Click to Download/Print Map)";}
                  return array($at,$a);
            }
?>

<select name="CourseDates"  ID = "21" size="1" Style="float:right" Width = "300"  onchange"javascript:ajax_post()" method = "post";>            
<?php do {  ?>
        <option value="<?php echo $row_Courses['Filename'].$row_Courses['CourseDates']?>">
        <?php echo $row_Courses['CourseNo'].".....".$row_Courses['CourseDates'].".....".$row_Courses['Destination']?></option>
        <?php
        }
              while ($row_Courses = mysql_fetch_assoc($Courses));
              $rows = mysql_num_rows($Courses);
              if($rows > 0) {mysql_data_seek($Courses, 0);
                    $row_Courses = mysql_fetch_assoc($Courses);        }
?>
</select>

<?php  list ($at,$a) =SelectRoute( substr($Current,0,9), substr($Current,9));
# get data from function for buttons
?>
<a href=<?php echo $a;?>><img src="Images/map.png" Title = "<?php echo $at;?>"  height="60" style="float:right"></a>

<?php echo $Current;?>
</body>
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
Michel Plungjan

I do not quite get this

<select name="CourseDates"  ID = "21" size="1" Style="float:right" Width = "300"  onchange"javascript:ajax_post()" method = "post";>            

1) IDs should start with a letter. I suggest you use the same as the name
2) no need to use the javascript: label in from of event handlers so onchange="ajax_post()" would be enough
3) I do not see ajax_post anywhere
4) selects do not have a method attribute, that belongs to the form tag.

If you still need to set the select to a given value, you can do it at load time using javascript too
window.onload=function() {
  var sel=document.getElementsByName("CourseDates")[0];
  sel.onchange=function() {
    ajax_post();
  }
  sel.value="<? echo $CurrentDate; >";
}

Open in new window

ASKER
SeanDoherty49

Thanks, just off to London.

Will contact you on Monday
Thanks
John
ASKER
SeanDoherty49

I adjusted to the code to get it to run without error but it does not set the value of DropDown on the screen.


<script type = "text/javascript">
window.onload=function() {
  var sel=document.getElementsByName("CourseDates")[0];
sel.onchange=function() {
    ajax_post();
   }
  sel.value="<?php echo $Current; ?>";
}
</script>

I have not got as far as writing the code for ajax_post.  I am still reading the book and I am struggling.

I feel totally deskilled, and am not quite sure where to turn.


John
I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck
Michel Plungjan

Can you post the view-source of the select and the   sel.value="<?php echo $Current; ?>"; statement? And do you have a function Ajax.post() available, otherwise you will have an error just before the statement that sets the dropdown. Look in the console (hit F12)
ASKER
SeanDoherty49

I was hoping Ray would respond, as he has spent a lot of time understanding this problem and given me a solution, only I cannot get it to work.

All the code is listed above.  The lit bit I just posted, was the code that Ray had sent, but I made a few changes to resolve syntax issues.

John
Michel Plungjan

If you need help with the javascript, I believe I can help too, I just have no use for the php since the javascript works on the rendered HTML. If you would be kind and post the javascript and the select from view source, I can see if it will work or not.
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.
ASKER
SeanDoherty49

Sorry for not getting back sooner, but I have been away.

The table that I have got stored in Wamp Server is shown on the post above on Posted on 2013-09-04 at 14:01:53 in lines 51 - 133.

Thank you
John

The code is shown below:
<!doctype html><head></head>
<body>

<?php
# FileName="Connection_php_mysql.htm"
# Type="MYSQL"
# HTTP="true"
$hostname_mcr500 = "localhost";
$database_mcr500 = "mcr500";
$username_mcr500 = "root";
$password_mcr500 = "";
$mcr500 = mysql_pconnect($hostname_mcr500, $username_mcr500, $password_mcr500) or trigger_error(mysql_error(),E_USER_ERROR);
# I haven't a clue what this next bit does.
?>

<?php
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
{
  if (PHP_VERSION < 6) { $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}
$Current = "20130915Buxton";
$date = date('c', strtotime('Today'));
# your date does not work with my query
$date = Date("y")."/".Date("m")."/".Date("d");
mysql_select_db($database_mcr500, $mcr500);
#       this is the quey for populating the dropdown
$query_Courses = "SELECT coursedates.CourseDates, coursedates.CourseNo, coursedates.Destination, coursedates.Filename FROM coursedates ORDER BY  coursedates.CourseNo";
$Courses = mysql_query($query_Courses, $mcr500) or die(mysql_error());
$row_Courses = mysql_fetch_assoc($Courses);

#this is the quey for determining the nexct ride.  I know it is not elegant but at the moment it works.
$query_NextRideOut = "SELECT  coursedates.Filename, coursedates.CourseDates, coursedates.Destination FROM coursedates WHERE coursedates.CourseDates >= '$date' ORDER BY coursedates.CourseDates";
$NextRideOut = mysql_query($query_NextRideOut, $mcr500) or die(mysql_error());
$row_NextRideOut = mysql_fetch_assoc($NextRideOut);
$totalRows_NextRideOut = mysql_num_rows($NextRideOut);
# checking the name of current ride out.  if past the last ride select the first.
if ($totalRows_NextRideOut>0)
      { $Current = $row_NextRideOut['Filename'].$row_NextRideOut['Destination']; }
else
      { $Current = $row_Courses['Filename'].$row_NextCourses['Destination'];}
      
?>
  <?php
  # function to change data for route buttons (only one shown)
      function SelectRoute($filename,$destination)
            {error_reporting(E_ALL);
                  $Ride = "Routes/".$filename;
                  $Dest = $filename." to ". $destination;
  if  (!file_exists($Ride.".pdf")      )  
                  {      $Ride = "Other Routes";       
                        $Dest = "";
                         $a = "Routes/otherroutes.pdf";
                        $at = "No route";  }      
            else
                  {      $a = $Ride.".png";
                        $at = $Dest."(Right Click to Download/Print Map)";}
                  return array($at,$a);
            }
?>

<select name="CourseDates"  ID = "21" size="1" Style="float:right" Width = "300"  onchange"javascript:ajax_post()" method = "post";>            
<?php do {  ?>
        <option value="<?php echo $row_Courses['Filename'].$row_Courses['CourseDates']?>">
        <?php echo $row_Courses['CourseNo'].".....".$row_Courses['CourseDates'].".....".$row_Courses['Destination']?></option>
        <?php
        }
              while ($row_Courses = mysql_fetch_assoc($Courses));
              $rows = mysql_num_rows($Courses);
              if($rows > 0) {mysql_data_seek($Courses, 0);
                    $row_Courses = mysql_fetch_assoc($Courses);        }
?>

</select>

<?php  list ($at,$a) =SelectRoute( substr($Current,0,9), substr($Current,9));
# get data from function for buttons
?>
<a href=<?php echo $a;?>><img src="Images/map.png" Title = "<?php echo $at;?>"  height="60" style="float:right"></a>

<script type = "text/javascript">
window.onload=function() {
  var sel=document.getElementsByName("CourseDates")[0];
sel.onchange=function() {
    ajax_post();
   }
   <?php echo sel.value;?>
# this is not doing anything on the screen
  sel.value="<?php echo $Current; ?>";
     <?php echo sel.value;?>
}
</script>
</body>
ASKER CERTIFIED SOLUTION
Log in to continue reading
Log In
Sign up - Free for 7 days
Get an unlimited membership to EE for less than $4 a week.
Unlimited question asking, solutions, articles and more.