ielyamani
ielyamani

Reputation: 18591

What's wrong with this sql query and mysql_fetch_array?

These lines are from a php function on a web server, the client is an ios app, I get an error on the result2 query

$result = query("SELECT field1 FROM table1 WHERE field2='%s' limit 1", $value);
$row = mysql_fetch_array($result);
$result2 = query("SELECT field2 FROM table1 WHERE field3='%s' limit 1", $row['field1']);

on Xcode I get the error (in json):

{
    error = "The operation couldn't be completed. (Cocoa error 3840.)";
}

here is the definition of the function query

//executes a given sql query with the params and returns an array as result
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');
}
}

what's wrong with that query?

thanks

Upvotes: 0

Views: 94

Answers (2)

Pitchinnate
Pitchinnate

Reputation: 7556

You are using mysqli_ functions in your query() function yet you are trying to use mysql_fetch_array() to get the results. You need to use: mysqli_fetch_array()

http://www.php.net/manual/en/mysqli-result.fetch-array.php

Actually it looks like your query() function does it for you. You shouldn't need to use a function at all. Look at this section of your query() function:

$rows = array();

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

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

However not sure why it says it is json cause it is just a normal array not a json array. So you should just use this in your code:

$row = $result['result'][0];

This will get the first row.

Upvotes: 1

Zakari
Zakari

Reputation: 743

maybe you have to json_encode the result?

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

Upvotes: 0

Related Questions