Jump to content

[SOLVED] simple question: check to see if row exists


jbrill

Recommended Posts

$id can be $_GET['id']; I am just using number 1 as an example.

 

<?php

$id = 1; // This can be $_GET['id'] FROM the URL Values

$search = mysql_query("SELECT * FROM orders WHERE id = '$id'"); // Here we select the rows with the id of 1

while($row = mysql_fetch_array($search)){ // We loop through the data

if($id == $row['id']){ // Check if the id exists in the table

echo " IT DOES!!!"; // yes it does

}
else
{

echo " The id $id doesnt exist"; //else no

}
}
?>

Based on phpSensei code, here's a shorter way. It sets a boolean variable ($blnFound) to true if the ID exists.

 

<?php

$id = 1; // Set $id

$objResult = mysql_query("SELECT id FROM `orders` WHERE id = '$id'");

$blnFound = (boolean) ($objResult) ? mysql_num_rows($objResult) : FALSE;

?>

Based on phpSensei code, here's a shorter way. It sets a boolean variable ($blnFound) to true if the ID exists.

 

<?php

$id = 1; // Set $id

$objResult = mysql_query("SELECT id FROM `orders` WHERE id = '$id'");

$blnFound = (boolean) ($objResult) ? mysql_num_rows($objResult) : FALSE;

?>

does it really important to set that var as bool when your var is returning bool i  mean  mysql_query returns t/f

does it really important to set that var as bool when your var is returning bool i  mean  mysql_query returns t/f

 

The mysql_query() function does not return false when you do a successful "SELECT" query. See manual for details:

http://us2.php.net/manual/en/function.mysql-query.php

 

FYI:

 

Executing a successful select query does not necessarily mean there are rows (data) returned. The search criteria (in the "where" clause) might not match any data. You have to follow the select query with a fetch to see if there really is data, or in this case, we don't need the data per say but just need to know if it's there (a match was made); so I used the mysql_num_rows() to tell if there is data (without having to actually fetch the data).

 

hth.

 

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.