Asked  7 Months ago    Answers:  5   Viewed   32 times

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;
}
?>

 Answers

61

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;
    }
Wednesday, March 31, 2021
 
Jauco
answered 7 Months ago
73

The problem is with PHP variable scoping. Add this line inside of allServers() function before you refer to the $link variable for the first time:

global $link;

See more here: http://php.net/manual/en/language.variables.scope.php

Wednesday, March 31, 2021
 
SheppardDigital
answered 7 Months ago
40

Looks like a malformed MySQL query:

$query = "select * from tabled where field like "%$trimmed%"  
  order by field";

You basically forgot the "from" in the query string.

As a side note, you should read into properly escaping MySQL query strings:

http://php.net/manual/en/function.mysql-real-escape-string.php

http://kunststube.net/escapism/

Wednesday, March 31, 2021
 
MoarCodePlz
answered 7 Months ago
90

That's because your query is wrong.

$sql = "GET * FROM matt";

must probably become

$sql = "SELECT * FROM matt";

the basic measure to get warned about this is

if (!$result)
 die("mySQL error: ". mysql_error());  

after issuing a query.

Friday, May 28, 2021
 
Yrtymd
answered 5 Months ago
26

You probably need to use the global keyword, otherwise $db is considered a var in local scope.

function sanitize ($data){
    global $db;
    $db->mysqli_real_escape_string($data);
}

function user_exists($usermail){
    global $db;
    $usermail = sanitize($usermail);
    $query = $db->query("SELECT COUNT(userId) FROM users WHERE userEmail= '$usermail' ");
    $check = $query->num_rows;
    return ($check == 1) ? true : false;
}
Monday, August 2, 2021
 
ajreal
answered 3 Months ago
Only authorized users can answer the question. Please sign in first, or register a free account.
Not the answer you're looking for? Browse other questions tagged :
 
Share