Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

php - Warning: mysql_result(): supplied argument is not a valid MySQL result resource in (...) on line 4

Here is my snippet.

I've checked some other questions similar to my error, but so far I can't get it solved.

<?php 
function user_exists ($username) {
$username = sanitize($username);
return (mysql_result(mysql_query("SELECT COUNT(user_id) FROM users WHERE username =  $username"), 0) == 1) ? true : false;
}
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You should split your code in some more lines to handle those errors or special cases. mysql_query will return zero to n rows or an error if it occurs. The returned resource will therefore only be true on non-error queries. This can be used to handle such situations like follows.

At first build and execute query, next process the resource.

$query="SELECT COUNT(user_id) FROM users WHERE username = ".$username;
$result = mysql_query($query);  

u may use the following to determine what is going on in case of an error:

if(!$result) die("SELECT failed: ".mysql_error());

or these idea to handle the problem

if (!$result=mysql_query($query)) {
        return false; // or similar operation
    }

    if (mysql_num_rows($result)!=1){
        return false;
    }else{
        return true;
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...