Forum Moderators: coopster

Message Too Old, No Replies

Test for MySQL cell exists

         

Readie

8:42 pm on Jan 18, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've spent quite some time googling, but havn't actually been able to find a solution. The MySQL WHERE EXISTS function seems to only be for cross-referencing tables, and I havn't been able to find anything else that comes remotely close.

So, what I want to do is have a function that tests for whether or not a row with a particular ID exists, so, say a user tries to type in newsarchive.php?id=23 - as there would be no row with that id, I'd like to be able to echo an error message with something like:

$n_id = mysql_real_escape_string($_GET['id']);
if(id_valid($n_id)) {
echo 'Blah blah news';
} else {
echo 'Error';
}

But, writing that id_valid function is where I'm stuck. Any help would be greatly appreciated.

Regards,
Readie

TheMadScientist

8:47 pm on Jan 18, 2010 (gmt 0)

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



How about just writing a query and seeing if there is a result?

$n_id = mysql_real_escape_string($_GET['id']);
$s="SELECT whatyouneed FROM table WHERE id=".$n_id;
$query=mysql_query($s);

if($result=mysql_fetch_array($query)) {
echo 'Blah blah news';
} else {
/* If this will have it's own query string it is recommended to server the proper status code to Search Engines and browsers if no results is found. */

header('HTTP/1.1 404 Not Found');
echo 'Error';
}

Readie

8:52 pm on Jan 18, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Works like a charm. Thank you for the very fast and helpful reply :)