Phiter Fernandes Phiter Fernandes - 6 months ago 12
SQL Question

Populate select from database with php

Something is wrong with that code, i mean, it's not doing what i want it to.

<?php
$con = mysql_connect($db_s, $db_u, $db_p);
$db = mysql_select_db("saritur", $con);
$query = "SELECT resumo FROM resumos";
$res = mysql_query($query,$con);

echo "<select name='usuario' id='usuario'>";
while (($row = mysql_fetch_row($res)) != null)
{
echo "<option value = '".$row['resumo']."'>".$row['resumo']."</option>";
}
echo "</select>";
mysql_close($con);
?>


I'm new into PHP so that's already a problem, i got that code from another question in here but still won't work

Edit:

Ok guys i had a stupid problem, the variables $db_s, $db_u etc was on a include file, unfortunately i was not getting the values from it so i had to declare them on the main file and it's looking like this now:

<select name="resumo" id="usuario">
<?php
$db_u = 'phiter';
$db_p = '****';
$db_s = '127.0.0.1';

$con = mysql_connect($db_s, $db_u, $db_p);
$db = mysql_select_db("saritur", $con);
$query = "SELECT * FROM resumos";

$res = mysql_query($query,$con);
while ($row = mysql_fetch_row($res))
{
echo "<option value = '{$row['resumo']}'>{$row['resumo']}</option>";
}

mysql_close($con);
?>
</select>


It is communicating with the database and the number of rows are the same as the number on the database, NICE! But it's all showing white blocks, there is nothing written on the options. I saw the error on page code, it says


Notice: Undefined index: resumo in xxx on line 48


WHYYYYYY

Another update:

Changed
mysql_fetch_row
into
mysql_fetch_array
, now it works

Answer

I'm going to have a gamble here that this is the only thing that is wrong...

while (($row = mysql_fetch_row($res)) != null)

change to

while (($row = mysql_fetch_assoc($res)))

Why? See the reference pages

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

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

mysql_fetch_row() returns a numerical array, whereas mysql_fetch_assoc returns a keyed array... which is how you're using it.

Alternatively you can keep using mysql_fetch_row() but then use $row[0] or reset($row) to access the first value.

Comments