Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

How can i check if a variable is saved or not in the db?

1

44 views

I have this code:

$local_id = $_GET['id'];

$sql = dbquery("SELECT * FROM `videos` WHERE `id` = ".$local_id." LIMIT 0, 1");
while($row = mysql_fetch_array($sql)){
$video_id = $row["youtube_id"]; 
// the rest
}

how can i check if $local_id does not exist in the db and display an error?

asked June 24, 2011 10:40 am CDT
posted via StackOverflow

4 Answers

4
Best answer
 

mysql_num_rows

if(mysql_num_rows($sql) == 0) {
    //Show error 
}

answered June 24, 2011 11:24 am CDT
1
 

You can use the following query:

"SELECT COUNT(*) FROM `videos` WHERE `id` = ".mysql_real_escape_string($local_id)

This query will return one number: how many records have matched your query. If this is zero, you surely know that there are no records with this ID.

This is more optimal than other solutions posted in case you only want to check for the existence of the ID, and don't need the data (if you use SELECT * ..., all the data will be unnecessarily sent from MySQL to you). Otherwise mysql_num_rows() is the best choice, as @Ryan Doherty correctly posted.


Be sure to ALWAYS escape data that came from the outside (this time GET) before you put it into a query (mysql_real_escape_string() for MySQL).

If you fail to do so, you are a possible victim for SQL Injection.

answered June 24, 2011 11:24 am CDT
1
 
$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
    echo 'error';

answered June 24, 2011 11:24 am CDT
0
 

You could have a $count variable and increment it in the while loop. After the loop, check the count, if it is 0, then echo an error message.

answered June 24, 2011 11:24 am CDT

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions