Chris James Champeau
Chris James Champeau

Reputation: 994

return value if mysql query returns no results

Ok so I am trying to make it so that if the input username exists to fetch the details for that username, and if no username exists to tell me so...

So far it will tell me if the username exists, but not if it does not exist...

So basically if the query returns zero results how do I get it to say "hey there were no matches" ?

my code so far...

$user = $_POST['txtUsername'];
$sql = "SELECT * FROM `weaponstreat` WHERE username='$user'";
$rows = $db->query($sql); while ($record = $db->fetch_array($rows)) {

    if ($record['tid'] === NULL) { echo "empty"; } else { echo "full"; }
}

Upvotes: 1

Views: 8697

Answers (4)

sah
sah

Reputation: 137

$user = $_POST['txtUsername'];

$query = mysql_query ("SELECT * FROM weaponstreat WHERE username='$user' ORDER BY tid DESC");

if ( mysql_num_rows( $query ) > 0 )
{
    // Process and display username details
}
else
{
    echo "That username does not exist";
}

Upvotes: 0

Nick
Nick

Reputation: 4212

$user = $_POST['txtUsername'];
$sql = "SELECT * FROM `weaponstreat` WHERE username='$user'";
$rows = $db->query($sql);
// add a counter variable 
$counterRecords = 0;
while ($record = $db->fetch_array($rows)) {

    $counterRecords++;
}

if($counterRecords==0)
 echo "empty";
else echo "full";

Upvotes: 0

John Conde
John Conde

Reputation: 219794

Just check to see if any rows are returned:

if ($db->num_rows() == 0)
{
    // No results
 }
else
{
    while ($record = $db->fetch_array($rows)) {
        if ($record['tid'] === NULL) { echo "empty"; } else { echo "full"; }
    }
}

Upvotes: 1

RolandoMySQLDBA
RolandoMySQLDBA

Reputation: 44333

$user = $_POST['txtUsername'];
$sql = "SELECT COUNT(1) rcount FROM `weaponstreat` WHERE username='$user'";
$rows = $db->query($sql); while ($record = $db->fetch_array($rows)) {

    if ($record['rcount'] == 0) { echo "empty"; } else { echo "full"; }
}

Upvotes: 2

Related Questions