Forum Moderators: coopster

Message Too Old, No Replies

PHP function but any output

         

toplisek

4:38 pm on Nov 3, 2015 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



I'm testing simple HTML listbox and PHP function.
Is this correct one as it is any output.

function ShowCity1($id) {
$sql = 'SELECT city1 FROM tablepostal';
mysql_query($sql) or mysql_error_show($sql,__FILE__,__LINE__);
echo '<select name="citynames">';
while($row = mysql_fetch_array($sql,MYSQLI_ASSOC)){
echo '<option value="'.$row{city1}.'">'.$row{city1}.'</option>';
}
echo '</select>';
}

whitespace

9:42 pm on Nov 3, 2015 (gmt 0)

10+ Year Member Top Contributors Of The Month



mysql_query($sql) or mysql_error_show($sql,__FILE__,__LINE__);


You need the resource that is returned from mysql_query() in order to pass this to mysql_fetch_array()...


$result = mysql_query($sql) or mysql_error_show($sql,__FILE__,__LINE__);


while($row = mysql_fetch_array($sql,MYSQLI_ASSOC)){


And then pass $result to mysql_fetch_array(), not $sql. Note also, that it should be MYSQL_ASSOC (no "I") - although the two constants do have the same value.


while($row = mysql_fetch_array($result,MYSQL_ASSOC)){


echo '<option value="'.$row{city1}.'">'.$row{city1}.'</option>';


This syntax is also not strictly correct, although it still works. This will result in an E_NOTICE. The array index should be quoted, otherwise it will be seen as an "undefined constant". And square brackets are more common that curly brackets - although curly brackets are OK.


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


You should enable full error_reporting whilst developing. That would have caught these errors.

Consider using the MySQLi extension instead. The MySQL extension is deprecated and will be removed entirely in future versions of PHP.

Your choice, but it is bad practice to echo directly within a function (restrictive, less portable). It would be better to save the HTML in a string within the function and return the HTML (string) from the function. The calling environment then outputs the HTML.