-1

I have a PHP script that dynamically shows the 'course' options from my database

<?php


    $db_host = 'localhost';
    $db_user = 'root';
    $db_pass = '';
    $db_name = '';

    $con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
    if (!$con) {
    die('Could not connect: ' . mysqli_error($con));
    }   


    $sql = "SELECT courseID, name FROM courses";

    $result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));

    while ($row = mysqli_fetch_array($result))
    {
    echo'<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
    }


    ?>  

I have a dropdown in my HTML (scorecard.php) page.

    <form> <select id="selectCourse" > <option value = "">Select  Course</option></select></form>

I was wondering would anyone know a script or way of getting this data to display in my dropdown.

Thanks for any help

4
  • show us what you tried and how long you researched this. Commented Jul 21, 2015 at 16:05
  • stackoverflow.com/questions/31534927/… Commented Jul 21, 2015 at 16:10
  • I had it using a JSON approach but was having problems displaying the course 'name' and then POST 'courseID' Commented Jul 21, 2015 at 16:11
  • You've answers below; try those out. Commented Jul 21, 2015 at 16:11

2 Answers 2

0

You have to run your while loop inside the select tag

Here is updated code

<?php

$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = '';

$con = mysqli_connect($db_host,$db_user,$db_pass, $db_name);
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}   


$sql = "SELECT courseID, name FROM courses";

$result = mysqli_query($con, $sql) or die("Error: ".mysqli_error($con));

?>  

<form> 
  <select id="selectCourse" >
    <option value = "">Select  Course</option>
     <?php while ($row = mysqli_fetch_array($result))
    {
       echo'<option value="'.$row['courseID'].'">'.$row['name'].'</option>';
    } ?>

 </select>

Sign up to request clarification or add additional context in comments.

Comments

0

echo'<option value="'.$row['courseID'].'">'.$row['name'].'</option>';

change it to

$courses[] = '<option value="'.$row['courseID'].'">'.$row['name'].'</option>';

and where u want it to be displayed

foreach($courses as $c){
    echo $c;
}

1 Comment

What do you mean by 'as $c)' would i place that last section of code in the HTML page?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.