-1

I am trying to populate the dropdown list in my html form using the data fetched from the database using the following php code :

<?php
$user_name = "root";
$password = "";
$database = "student";
$host_name = "localhost";

$con = mysqli_connect($host_name, $user_name, $password, $database) or die("Error not connected! " . mysqli_error($con));

//COURSE selection from database........

$query = "SELECT course_name FROM course_master";
$result = mysql_query($query); // Run your query

if (!mysqli_query($con, $query)) {
  echo "<script type='text/javascript'>alert('Error!!')</script>" . $sql . "<br>" . mysqli_error($con);
} else {
  echo "<script type='text/javascript'>alert('Success!!')</script>";
}

echo '<select name="course">'; // Open your drop down box
// Loop through the query results, outputing the options one by one
while ($row = mysql_fetch_assoc($result)) {
  echo '<option value="' . $row['course_name'] . '">' . $row['course_name'] . '</option>';
}
echo '</select>'; // Close your drop down box

mysqli_close($con);
?>

But its only showing an empty dropdown box at the beginning of my form instead of filling it with the required contents fetched from the database. can anybody please help???

Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
Sweta
  • 1

1 Answers1

0

You mixed mysql & mysqli.

1) Change

$result = mysql_query($query); // Run your query

To

$result = mysqli_query($con, $query); // Run your query

2) Change

if (!mysqli_query($con, $query)) {

To

if (!$result) {

=> $result is already having results set.

Updated Code

<?php
$user_name = "root";
$password = "";
$database = "student";
$host_name = "localhost";

$con = mysqli_connect($host_name, $user_name, $password, $database) or die("Error not connected! " . mysqli_error($con));

//COURSE selection from database........

$query = "SELECT course_name FROM course_master";
$result = mysqli_query($con, $query); // Run your query

if (!$result) {
  echo "<script type='text/javascript'>alert('Error!!')</script>" . $sql . "<br>" . mysqli_error($con);
} else {
  echo "<script type='text/javascript'>alert('Success!!')</script>";
}

// Open your drop down box
echo '<select name="course">'; 
// Loop through the query results, outputing the options one by one
while ($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
  echo '<option value="' . $row['course_name'] . '">' . $row['course_name'] . '</option>';
}
echo '</select>'; 
// Close your drop down box

mysqli_close($con);
?>
Nana Partykar
  • 10,556
  • 10
  • 48
  • 77