NSViking
NSViking

Reputation: 53

Search user using part of the name

I have this PHP code:

function getusers($user) {
    $result = query("SELECT IdUser, username FROM login WHERE username='%s'",$user);

    if (count($result['result'])>0) {
        //authorized

        print json_encode($result);
    } else {
        errorJson('Actualization failed');
    }
}

But this only returns the user that matches the name exactly. I'd like to return all users containing that name string, for example:

dani -> daniel, dani_56, dani563, elnenedani, ...

It is usually done by putting in PHP: %dani% but as I have put the %s to grab the variable $user, I do not know how to put it.

Any idea?

Upvotes: 0

Views: 81

Answers (4)

NSViking
NSViking

Reputation: 53

I do not get fixed. This code is for an ios app that uses AFNetworking, might please that helps you know what happens because I do not get it

Upvotes: 0

DonOfDen
DonOfDen

Reputation: 4108

It is not a great Question. If you have searched well in Stackoverflow you would have go it the answer.. As you asked the Question the answer is.. Instead of Equal use LIKE:

function getusers($user) {
$result = query("SELECT IdUser, username FROM login WHERE username LIKE %'%s'%",$user);

if (count($result['result'])>0) {
    //authorized

    print json_encode($result);
} else {
    errorJson('Actualization failed');
}
}

It seems the PHP code and DB is working well. Checkout the below links for the error:

iOS 5 JSON Parsing Results in Cocoa Error 3840

Cocoa error 3840 using JSON (iOS)

The Operation couldn't be completed. (Cocoa error: 3840.)

Cocoa Error 3840 - NSJSONSerialization

Upvotes: 1

NSViking
NSViking

Reputation: 53

My query() function is

function query() {
global $link;
$debug = false;

//get the sql query
$args = func_get_args();
$sql = array_shift($args);

//secure the input
for ($i=0;$i<count($args);$i++) {
    $args[$i] = urldecode($args[$i]);
    $args[$i] = mysqli_real_escape_string($link, $args[$i]);
}

//build the final query
$sql = vsprintf($sql, $args);

if ($debug) print $sql;

//execute and fetch the results
$result = mysqli_query($link, $sql);
if (mysqli_errno($link)==0 && $result) {

    $rows = array();

    if ($result!==true)
    while ($d = mysqli_fetch_assoc($result)) {
        array_push($rows,$d);
    }

    //return json
    return array('result'=>$rows);

} else {

    //error
    return array('error'=>'Database error');
}

}

Upvotes: 0

Mundi
Mundi

Reputation: 80271

You should use the LIKE syntax. Make sure to include % to indicate wildcards:

query('SELECT IdUser, username FROM login 
       WHERE username LIKE "%' . $user . '%"')

Upvotes: 0

Related Questions