Skovie
Skovie

Reputation: 197

Search in mysql php webservice

im trying to make a Search function in my app, using AFNetworking but whenit dosent find anything unless i type in the hole name ...

my function in my web service;

function streamSearch($name) {

    $result = query("SELECT name, email, IdPhoto  FROM users WHERE name LIKE '%", $name);


if (!$result['error']) {
    print json_encode($result);
} else {
    errorJson('search is broken');
}
}

and in my ios i do this:

[[API sharedInstance] commandWithParams:[NSMutableDictionary dictionaryWithObjectsAndKeys:@"streamSearch", @"command",theSearchBar.text, @"name", nil] onCompletion:^(NSDictionary *json) {
            //got stream
            NSDictionary *user = [json objectForKey:@"result"];

can you help me, i need it to find all users that have the letter i type....

query behind the scene :

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

Views: 105

Answers (2)

Ja͢ck
Ja͢ck

Reputation: 173582

The code should probably read like:

$result = query("SELECT name, email, IdPhoto  FROM users WHERE name LIKE '%s%%'", $name);

Which acts as "LIKE 'test%'" if $name is 'test'.

The query() function acts like printf() so a '%' should be encoded as '%%' and a string argument is passed using '%s'.

Upvotes: 1

Simon Germain
Simon Germain

Reputation: 6844

If that's a copy/paste of your code, you're missing a closing quote after % in your SQL statement.

Upvotes: 0

Related Questions