当前位置: 动力学知识库 > 问答 > 编程问答 >

html.dropdownlistfor - Drop-down list using mysql when query not found

问题描述:

I built a simple input drop-down list, using <select> which populates from a mysql database.

It works fine, but if the result from the query is not found then the drop-down list just shrinks and doesn't say anything.

I want it to say something like: "Name not found". I've searched everywhere but I can't seem to find the way.

This is my code:

<?php

if ( $myquery = $mysqli->prepare("SELECT name, idname FROM db WHERE

name LIKE '%".$name."%'") ) {

$myquery->execute();

$myquery->store_result();

$myquery->bind_result( $nompac, $idpac ) ;

}

<form name="form1" method="post" action="example.php">

<table >

<tr>

<td>Name: </td>

<td>

<select name="chosen_name">

<?php

while ( $myquery->fetch() ) {

echo "<strong><option value=".$idpac.">".$nompac."</option></strong>";

}

?>

</select>

</td>

<td><input type="submit" name="Submit" value="Go" class="button"/></td>

</tr>

</table>

</form>

I would like to add an IF statement, saying something like "if $myquery didn't find any results, then $nompac ="name not found". So I wrote this right after the WHILE statement:

 if ( $nompac = "" ) {

$nompac = "Name not found";

$idpac = "0";

}

But it just ignores the code as if I didn't write anything :(

Ok I added the code as suggested by Mister Melancholy. Now looks like this:

<form name="form1" method="post" action="example.php">

<table >

<tr>

<td>Name: </td>

<td>

<select name="chosen_name">

<?php

if ( empty( $myquery ) ) {

echo "<strong><option value=''>Name not found</option></strong>";

} else {

while ( $myquery->fetch() ) {

echo "<strong><option value=".$idpac.">".$nompac."</option></strong>";

}

}

?>

</select>

</td>

<td><input type="submit" name="Submit" value="Go" class="button"/></td>

</tr>

</table>

</form>

But still doesn't work if the query doesn't find the name. What am I doing wrong? :-s

I added !empty instead of empty, and I was very happy it seemed to work but it turned out to be that even though the query founded the right name, it echoed "Name not found" every time, so back to square one :(

网友答案:

You need a way to tell if $myquery is empty before you begin your while loop. Something like this should do the trick:

if ( empty( $myquery ) ) {
    echo "<strong><option value=''>Name not found</option></strong>";
} else {
    while ( $myquery->fetch() ) {
        echo "<strong><option value='".$idpac."'>".$nompac."</option></strong>";       
    } 
}
网友答案:

Since I had no further answers in here, I had to ask on another forum and they came up with the solution!

Just to let you know, I used:

if ( $myquery->num_rows==0 ) {

and this works like a charm!

分享给朋友:
您可能感兴趣的文章:
随机阅读: