开发者

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

I have this code:

$loc开发者_JAVA百科al_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?


mysql_num_rows

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


$sql = dbquery("select count(*) from videos where id = ".$local_id." LIMIT 0, 1");
$row = mysql_fetch_row($sql);
if($row[0] == 0)
    echo 'error';


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜