Problem loading array from SELECT

Hi,

This should be simple, but can’t get it to work.

Want to check whether any classes are valid for today, and if so load them into an array, to be put into a Form SELECT list.

Code is below - commented where the problems are.

if (!$loaded) {
$loaded = TRUE;
$noclasses = TRUE;
$today = getdate();
$weekday = $today[“wday”];
echo date(“Y-m-d”) . ’ - ’ . $weekday . ‘
’; //ok gives todays date and correct day number

require_once 'conn.php';

$sql = "SELECT 'class_id', 'class_name', 'TermDates' FROM `classdetails` WHERE `DayOfWeek` =" . $weekday . " ORDER BY  `StartTime`";
$c_query = $conn->query($sql);
echo $c_query->num_rows . '<br />';  //ok returns no. of rows expected
if ($c_query->num_rows > 0) {
    $classids = array();
    while ($row = mysqli_fetch_array($c_query, MYSQLI_ASSOC)) {
        $classids[$row['class_id']] = $row['class_name'];
        $termdates = $row['TermDates'];
    }

    foreach ($classids as $key => $item) {
        echo "$key => $item <br>";          // get single  "class_id => class_name" would expect "3 => Mon 1pm", "4 => Mon 2pm", "7 => Mon 3pm"
    }
    echo $termdates . "<br/>";              // echos "TermDates" would expect "2019-09-09,2919-09-16,2019-09-23,2019-09-30"
    $classdates = explode(",", $termdates);
    $NoWeeks = count($classdates);       

Basically is $noclasses = TRUE will go on and give “No Classes” message. If $noclasses = FALSE then display form with a listbox displaying classes to choose from.

As can be seen the query isn’t filling the array (I am really having problems with PHP arrays!)

you’re just overwriting $termdates again and again. And in your steatement you are selecting a string, not an actual column, don’t use quotes there.

Hi,

The Stermdates shouldn’t really be a problem as each class for a given day has the same termdates.

I have tried using

        $classids[$row[class_id]] = $row[class_name];
        $termdates = $row[TermDates];

but keep getting PHP errors e.g.

Use of undefined constant class_id - assumed ‘class_id’

If I don’t use quotes.

You should use quotes for array keys to prevent the “undefined constant” errors.

But you should not use quotes for coulmn names within the SQL statement - obviously the database returns "TermDates" as a string, instead of the actual column value, as you’ve seen in the echo.

Thanks - I misunderstood your original reply.

It now works as I would expect - many thanks for your help

Sponsor our Newsletter | Privacy Policy | Terms of Service