Garrett Reardon
Garrett Reardon

Reputation: 3

How to display error when searching MySQL using PHP

New to PHP and MySQL, have heard amazing things about this website from Leo Laporte and others. I am using a extremely basic PHP script to search a MySQL database of peoples names. I was wondering how I can have the search supply an error if there no one by that name in the database.

</p><?php

mysql_connect ("mysql.mydomain.us", "pnq_1","passwordremoved")  or die (mysql_error());
mysql_select_db ("pnq_soldiers");

$term = $_POST['term'];

$sql = mysql_query("select * from test_database where LN like '%$term%'");

while ($row = mysql_fetch_array($sql)){
    echo 'Last Name: '.$row['LN'];
    echo '<br/> First Name: '.$row['FN'];
    echo '<br/> Middle Initial: '.$row['MI'];
    echo '<br/> Rank: '.$row['RNK'];
    echo '<br/> Company: '.$row['CO'];
    echo '<br/> Platoon: '.$row['PL'];
    echo '<br/> Roster Number: '.$row['RN'];
    echo '<br/><br/>';
    }


?>

Upvotes: 0

Views: 86

Answers (4)

user557846
user557846

Reputation:

if (mysql_num_rows($sql)==0){
    //error
}else{
    //process data, while loop
}

and of course don't use mysql_ functions :-)

Upvotes: 0

Steve Robbins
Steve Robbins

Reputation: 13812

Keeping it simple... use mysql_num_rows()

</p><?php

mysql_connect ("mysql.mydomain.us", "pnq_1","passwordremoved")  or die (mysql_error());
mysql_select_db ("pnq_soldiers");

$term = $_POST['term'];

$sql = mysql_query("select * from test_database where LN like '%$term%'");

if(mysql_num_rows($sql) < 1) {

    echo 'Couldn\'t find anything for '.$term.'.';
}
else {

while ($row = mysql_fetch_array($sql)){
    echo 'Last Name: '.$row['LN'];
    echo '<br/> First Name: '.$row['FN'];
    echo '<br/> Middle Initial: '.$row['MI'];
    echo '<br/> Rank: '.$row['RNK'];
    echo '<br/> Company: '.$row['CO'];
    echo '<br/> Platoon: '.$row['PL'];
    echo '<br/> Roster Number: '.$row['RN'];
    echo '<br/><br/>';
    }
}


?>

Upvotes: 0

korko
korko

Reputation: 670

Use mysql_num_rows to test the number of rows in the result. 0 for no results.

Upvotes: 0

Waleed Khan
Waleed Khan

Reputation: 11467

Check to see how many rows were returned. If no rows were returned, you can display an error.

$sql = mysql_query("select * from test_database where LN like '%$term%'");
if (mysql_num_rows($sql)) {
    // continue as normal
} else {
    echo "Error!";
}

Upvotes: 2

Related Questions