$result equals nothing if mysql column not found?
How could i get $result
to开发者_JAVA百科o equal nothing if the column doesn't exist in PHP?
I was thinking something like this:
$result=mysql_query("SELECT * FROM users WHERE username=$key DESC LIMIT 1")or die ($result = '');
But i was told thats wrong.
It's wrong because you're killing the script with die when a DB error occurs, rather than doing stuff when you find no row.
What you presumably need is more like:
$result = mysql_query($query);
if ($result) {
if ($row = mysql_fetch_assoc($result)) {
// do stuff with row
} else {
// do stuff without row
}
} else { // not needed but left here for illustration purposes
// this is the part that would occur, had you called mysql_query(...) or die;
die(mysql_error());
}
$result=mysql_query("SELECT * FROM users WHERE username= '$key' LIMIT 1")or die (mysql_error());
then check the result of mysql_num_rows()
If you mean that the result returns 0 rows, you can check with mysql_num_rows, like this:
$result=mysql_query("SELECT * FROM users WHERE username=$key DESC LIMIT 1");
if (mysql_num_rows($result) == 0)
$result = '';
Your code will set $result
to ''
if there's an error, in which case mysql_query
returns false. It will also halt the code, since you're calling die()
. An empty result set is not an error, however. In that case mysql_query
returns a valid resource identifier with no rows. If I understand your question, this is what you want to do:
$result=mysql_query("SELECT * FROM users WHERE username=$key DESC LIMIT 1");
if (mysql_num_rows($result) == 0){
$result = '';
}
<?php
// Here I assume you're using PHP PDO
$pdo = new PDO("mysql:server=localhost;dbname=mydatabase", "root", "");
$result = $pdo->query("SELECT * FROM users WHERE username=$key DESC LIMIT 1");
$errorcode = $pdo->errorCode();
$errorinfo = $pdo->errorInfo();
// Columns doesn't exist
if($errorcode == "43072") $result = "";
// Other error...
else if($errorcode != "00000") die("MySQL Error: " . $errorinfo[2]);
?>
精彩评论