What's wrong with this sql query and mysql_fetch_array? - php

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

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.

maybe you have to json_encode the result?
//return json
return json_encode(array('result'=>$rows));

Related

I cannot populate an array with sql query data to export it as json object in php

I am new with php, I try to call the following function in order to populate an array of previously inserted data in mysql, but I get null.
function GetBusiness($con, $email)
{
$query = "SELECT * from Business WHERE B_EMAIL ='".$email."'";
$res = mysqli_query($con,$query);
$result_arr = array();
while($row = mysqli_fetch_array($res))
{
$result_arr[] = $row;
}
return $result_arr;
}
and then I try to construct my json object as..
$result_business = array();
$result_business = GetBusiness($con, $email);
$json['result'] = "Success";
$json['message'] = "Successfully registered the Business";
$json["uid"] = $result_business["id"];
$json["business"]["name"] = $result_business["name"];
$json["business"]["email"] = $result_business["email"];
but for even if the data are inserted successfully the part of $result_business is null, why I get null? I my $query typed wrong?
thank you
The problem is, your function GetBusiness returns a multi-dimensionnal array, you can use this one instead :
function GetBusiness($con, $email)
{
$query = "SELECT * from Business WHERE B_EMAIL ='".$email."'";
$res = mysqli_query($con,$query);
return mysqli_fetch_array($res);
}
Also, you must use the MySQL columns that you selected to access the data of the rowset. Something like
$json["uid"] = $result_business["B_ID"];
$json["business"]["name"] = $result_business["B_NAME"];

PHP issue using a method's return value as a parameter for query function

I have a function query:
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');
}
}
The function works just fine when I use it like this:
$g = "05%";
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $g);
print json_encode($result);
However I am getting no result when $g is a value retrieved from a method. For example lets say I have a method getMonth() from a class Date that returns the current month of May as 05% when echoed. I try the code below and get nothing from the database:
$time = new Date();
//$g = "05%"; this would definitely get results from the db
$h = $time->getMonth();
echo $h; //this displays 05% on the screen
$result = query("SELECT * FROM table_name WHERE table_column LIKE '%s'", $h);
print json_encode($result);
I am pretty sure that I am making a simple mistake, but I can't seem to figure it out. How can I fix this? Any help would be greatly appreciated.
Do something that your method return only 05 part from 05%. and append % after that for example
$h = $time->getMonth();
$h = "$h%";
and then it should work

Get the id of a newly inserted row php

I am trying to get the insert id from a newly inserted row. I use the following method to query. However I am unable to get the inserted id.
function query($sql) {
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);
$id = $result->insert_id; //no result, what do I put here?
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, 'id'=>$id);
} else {
//error
return array('error'=>'Database error');
}
}
How can I modify this method to get the insert id?
$id = mysqli_insert_id($link);
This value would be called the "identity", keep that in mind when searching for information pertaining to this.
check the below links
mysql_insert_id()
http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html
http://dev.mysql.com/doc/refman/5.0/en/mysql-insert-id.html

mysql_fetch_assoc into mysqli in a function

So I have a function to gather user_data in PHP & MYSQL, and the thing is that I want to upgrade MYSQL in MYSQLi.
The MYSQL code is following:
$data = mysql_fetch_assoc(mysql_query("SELECT $fields FROM members where id = $id"));
The MYSQLi code I tried but with no use:
$data = $db_connect->query("SELECT $fields FROM ´members´ where id = $id");
and
$result = $db_connect->query("SELECT $fields FROM ´members´ where id = $id");
$data = $result->fetch_assoc();
I don't know what could be wrong, in the 1:st example I have no errors but the data isn't displaying, and in the 2:nd code I noticed I need the fetch_assoc function to make it work, but here I get the errors saying
Call to a member function fetch_assoc() on a non-object
Seems like you have an error in your query. MySQli->query() will return FALSE on failure.
[UPDATE 2] Try this code:
$result = $db_connect->query("SELECT $fields FROM members where id = $id");
if (!$result) {
printf("Errormessage: %s\n", $db_connect->error);
}
else {
while ($data = $result->fetch_assoc()) {
print_r ($data);
}
}

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');
}
}
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'.
If that's a copy/paste of your code, you're missing a closing quote after % in your SQL statement.

Categories