mysql_fetch_assoc into mysqli in a function - php

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

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"];

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
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));

mysql COUNT(*) always returns 8

The title says it all. I have the below code:
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) FROM `".$table."`");
if (! $result) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno() . ".Table = ".$table);
}
return $result;
}
Seems like it should be the easiest function ever, but the result always returns 8.
Any ideas?
Thanks,
Josh
Your function returns a mysql_query() function result, which is NOT the results of your SQL query.
You have to do something like mysql_fetch_assoc() with the mysql_* old PHP functions.
PS: You should use PDO now, mysql_* are deprecated, it's just a tip ;)
To get number of records in your result
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) AS count FROM `".$table."`");
if (! $result) {
// throw exception
}
$row = mysql_fetch_assoc($result);
return $row['count'];
}
Also. as previous responder pointed out, you need to stop using mysql_* funcitons and start using either mysqli_* or PDO. PHP Docs for PDO
mysql_query returns a resource: http://php.net/manual/en/function.mysql-query.php
Returning that value won't give you the result of the query. You need mysql_fetch_array().
A working example:
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) FROM `".$table."`");
if (! $result) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno() . ".Table = ".$table);
}
if($row = mysql_fetch_row($result)) {
return $row[0];
}
else {
return false;
}
}
try to get result using mysql_fetch_array() mysql_fetch_assoc() or mysql_fetch_object()
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) AS count FROM `".$table."`");
if (! $result) {
// throw exception
}
$row = mysql_fetch_array($result);
return $row['count'];
}
I hope it will help
you need to fetch your query , not return the mysql_query.
try this
public function getRows($table) {
$result = mysql_query("SELECT COUNT(*) as counts FROM `".$table."`");
if (! $result) {
throw new Exception(mysql_error().". Query was:\n\n".$query."\n\nError number: ".mysql_errno() . ".Table = ".$table);
}
$row =mysql_fetch_array($result) ;
return $row['counts'];
}
You would be better using mysql_num_rows as it does not need to fetch any data and is more efficient
public function getRows($table) {
$result = mysql_query("SELECT * FROM `".$table."`");
if (! $result) {
// throw exception
}
$rows = mysql_num_rows($result);
return $rows;
}

My SQL query using exception while getting data

I am using MySQL to get data from table but it shows an exception. Here is the code I am using. I am calling this using URL to test:
$userName=mysql_real_escape_string($_GET['userName']);
$query = mysql_query("SELECT * FROM UserCredentials where UserName='$userName' ");
http://celeritas-solutions.com/pah_brd_v1/productivo/getUserData.php?userName=jamshaid.ali
Here is the exception
Warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource in /home/content/i/h/u/ihus235/html/cs/pah_brd_v1/productivo/getUserData.php on line 74 []
Here is the full code
$userName=mysql_real_escape_string($_GET['userName']);
$query = mysql_query("SELECT * FROM UserCredentials Where UserName='$userName' ");
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);
?>
$query = sprintf("SELECT * FROM UserCredentials where UserName='%s'",mysql_real_escape_string($_GET['userName']));
$result = mysql_query($query);
if(result){
//do you code
}
Some suggestions -
Use isset() , like --
if(isset($_GET['userName'])) {
// Do the processing, most appropriate check whether form is submitted or not
}
Now your code will looks like-
// Sanatize the data, and make sure to safe your code from sql injections(prefer PDO or mysqli_)
if(isset($_GET['userName'])) {
$userName=mysql_real_escape_string($_GET['userName']);
$sql = "SELECT * FROM UserCredentials Where UserName='".$userName."'";
$query = mysql_query($sql, $conn) or die(mysql_error());
$rows = array();
while($row = mysql_fetch_assoc($query)) {
$rows[] = $row;
}
echo json_encode($rows);
}
?>
echo $sql; and run it in phpmyadmin to check your query is forming correctly or not, use var_dump() and read error/warning/notices to track errors.

Unable to process string inside mysql_query() function in php

I am having an array of fields and after using implode function and converting them to string, I am trying to use this string as names of columns in mysql_query() function as follows:
$field_array = array('course','batch','branch');
$fields = implode(", ",$field_array);
$resource = mysql_query("SELECT $fields FROM some_table") or die(mysql_error());
but I am getting the following error. What is that I am doing wrong here ?
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM fix_data' at line 1
Below is the exact code I am using
function fetch_resource_db_nowhere($table_name,$field_array,$return_type,$return_type_name) {
if($field_array[0]=='ALL') {
//echo "asda";
$resource = mysql_query("SELECT * FROM ".$table_name."") or die(mysql_error());
}
else {
$fields = implode(",",$field_array);
$sql = "SELECT ".$fields." FROM ".$table_name."";
echo $sql;
$resource = mysql_query($sql) or die(mysql_error());
}
if($return_type == 'resource') {
return $resource;
}
if($return_type == 'resource_array') {
return mysql_fetch_assoc($resource);
}
if($return_type == 'resource_array_value') {
$resource_array = mysql_fetch_assoc($resource);
return $resource_array[$return_type_name];
}
}
$data = fetch_resource_db_nowhere('fix_data',array('course','branch','name'),'resource','');
You were trying to implode an array called field_array, even though your example shows an array called fields_array:
$fields_array = array('course','batch','branch');
$fields = implode(", ",$fields_array);
$resource = mysql_query("SELECT $fields FROM some_table") or die(mysql_error());
Edit: You changed your code again. Could you please give us the exact code that you're working with?

Categories