Roysyboysy
Roysyboysy

Reputation: 13

MySQL/PHP - displays only the first row twice

I'm trying to get my PHP to display all the product names in a dropdown menu. However it only displays the first row twice.

$prodNameSQL="select prodName from product";

//execute SQL query or return an error
$exeProdNameSQL=mysql_query($prodNameSQL) or die(mysql_error());

//create array of records & populate it with result of the execution of the SQL query
$array=mysql_fetch_array($exeProdNameSQL);

echo "<select name='productCombo'>";
foreach($array as $value) {

echo "<option value=".$value.">".$value;
echo "</option>";

}
echo "</select>";

I know that I should be using mysqli and mysql is depreciated but its beyond my control.

Thanks.

Upvotes: 1

Views: 276

Answers (3)

Jim Rubenstein
Jim Rubenstein

Reputation: 6920

When you call mysql_fetch_array the mysql driver returns a single row from your result set. By executing a foreach over that result ($array) you are effectively looping over the columns in a single row.

You need to execute:

while ($array = mysql_fetch_array($exeProdNameSQL)) {
    // output your dropdown options here
}

This will allow you to iterate over every single result that your query returns.


Also, the mysql extension was deprecated a very long time ago (php5.5), and php5.6 has reach end of life and is basically deprecated as well. The mysql extension is not available php7.0+, so if you ever try to run this code on an up-to-date system, it will fail.

You should strongly consider upgrading to the MySQL PDO driver (http://php.net/manual/en/ref.pdo-mysql.php).

Upvotes: 1

dashred
dashred

Reputation: 141

Check first the $array if it does contain results

<?php 

if ($array) {

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

} else {
  echo "<p>". mysqli_error($connection) ."</p>";
}

Upvotes: 0

clearshot66
clearshot66

Reputation: 2302

Try using result set instead using a fetch_assoc() and then using a while loop like this

while($row = mysql_fetch_assoc($result)){
    echo "<option value=".$row['prodName '].">".$row['prodName ']."</option";

}

http://php.net/manual/en/function.mysql-fetch-assoc.php

Upvotes: 0

Related Questions