This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('censored','censored','censored','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db");
$sql="SELECT message FROM messages WHERE code = '".$q."'";
$result = mysqli_query($con,$sql);
$resultstring = (string)$result;
echo $resultstring;
mysqli_close($con);
?>
I am attempting to echo the result of the query to the user but when this PHP runs through ajax I get this error:
Recoverable fatal error: Object of class mysqli_result could not be
converted to string in D:\xampp\htdocs\getmessage.php on line 12
Now I don't understand this because I am already converting $result into a string.. Thanks!
mysqli_query() can not convert to string.
You must use mysqli_fetch for parse to array.
Example:
if ($result=mysqli_query($con,$sql))
{
// Fetch one and one row
while ($row=mysqli_fetch_row($result))
{
printf ("%s (%s)\n",$row[0],$row[1]);
}
}
First of all mysqli_query Performs a query on the database
it does not directly return a value
$query = mysqli_query($con,$sql);
so to do that use mysqli_fetch_assoc it will Fetch a result row as an associative array
$result = mysqli_fetch_assoc($query);
Then you can now get your value
$resultstring = $result['message'];
so your code should be like this
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('censored','censored','censored','db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db");
$sql="SELECT message FROM messages WHERE code = '".$q."'";
$query = mysqli_query($con,$sql);
$result = mysqli_fetch_assoc($query);
$resultstring = $result['message'];
echo $resultstring;
mysqli_close($con);
?>
you need to convert the data(RS) into array !
$result = mysqli_fetch_assoc($result);
print_r($result);
As an result of your query on success You will get mysqli_result object. If You want to get received rows use fetch data function.
$result = mysqli_query($con,$sql);
$resultstring = $result->fetch_row()[0];
See docs: mysqli_query &
mysqli_result
I have resolved similar issue with following approach.
// Assign your sql statement
$sqlMasterSiteIds = "SELECT DISTINCT table_name FROM site WHERE gwid = 39 AND master_site_id NOT LIKE '0'";
// Run the query
$masterSiteIdsQuery = $this->db->query($sqlMasterSiteIds);
// Prepare container
$masterSiteIds = [];
// Fetch first row of query results
$first_row = $masterSiteIdsQuery->fetch_assoc();
// Assign first row to your prepared container
$masterSiteIds= $first_row['master_site_id'];
// Change the results into string comma separated so it can be used in next mysqli query or echoed
while($sub_row = $masterSiteIdsQuery->fetch_assoc()) {
$masterSiteIds = implode(',', array($masterSiteIds, $sub_row['master_site_id']));
}
// Now you can use $masterSiteIds which is a STRING of values comma separated
echo $masterSiteIds; // Output: '1024, 1142, 8492'
I hope it will help you or anybody else in need. I am not sure if it is the best approach but it worked well in my case as I had to change my results into STRING so I could use it in my next mysqli query with FIND_IN_SET command.
Happy coding!
Related
I am trying to set the two outputs from this MySQL stored procedure as PHP variables:
$result = mysql_query("CALL mst2('$q', #eset, #leng)");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = #mysql_fetch_assoc($result))
{
debug($row);
}
$eset = $row->{'#eset'};
$length= $row->{'#leng'};
The last two line are throwing an error Trying to get property of non-object . Does anybody know the proper way to do this?
mysql_fetch_object instead of mysql_fetch_assoc should fix your query up.
Secondly though you should really look at either using mysqli_ or pdo statements.
Links here:
http://php.net/manual/en/pdo.query.php
http://php.net/manual/en/mysqli.query.php
Here's how I got it to work with mysql_query:
$result = mysql_query("CALL mst2('$q', #eset, #leng)");
$result = mysql_query("SELECT #eset, #leng");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
while($row = #mysql_fetch_object($result))
{
$eset = $row->{'#eset'};
}
right after the procedure I called a SELECT statement, then in the while loop, the $eset variable gets set properly.
Back again, thanks for all the help last time. I'm running this query:
$query = "SELECT * FROM event where evLoc = ".$loc." AND evChar = ".$char;
var_dump($query);
$result = mysql_query($query, $con) or die('Error 1:'.mysql_error());
if ($result) {
$row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());
var_dump(mysql_num_rows($result));
exit();
I get a message Error 2: but no mysql_error printed out. The var_dump($query) printed out a query that ran without errors in phpMyAdmin. The var_dump(mysql_num_rows($result)) did not print.
This is a case of being too cautious and applying error checking where it doesn't belong.
Don't call die() in partnership with a fetch call. The fetch intentionally returns FALSE when there are no rows available, so you don't have an error, just no rows.
// No rows were returned, wich is FALSE
$row = mysql_fetch_array($result) or die('Error 2:'.mysql_error());
Instead, don't call die() here:
$row = mysql_fetch_array($result);
if ($row) {
// you got something
}
Or this way:
if ($row = mysql_fetch_array($result)) {
// you got something.
}
If multiple rows are expected to be returned, fetch in a while loop.
while ($row = mysql_fetch_array($result)) {
// loops until you're out of rows
// or not at all if you have no rows
}
Obviously, your request returns 0 rows and mysql_fetch_array returns FALSE
Apply Single Quotes in the fields of your query
$query = "SELECT * FROM event where evLoc = '".$loc."' AND evChar = '".$char."'";
You can write these in short form too. Like
$query = "SELECT * FROM event where evLoc = '$loc' AND evChar = '$char'";
Next, you might want to change your fetch portion.
while($row = mysql_fetch_assoc($result)) {
....
}
When you use this, you will avoid the error you would receive when no rows are returned.
I'm looking to label a string based on database results. I have the following code:
$loc1 = "A";
$query = "SELECT loc FROM User where nick='".$users[$j]."'";
$loc = mysql_query($query);
if($loc == 1)
$loc1 = "A";
if($loc== 2)
$loc1 = "B";
The loc1 location is always "A". I've confirmed that the query works in MySQL and I'm having a difficult time understanding why this simple case is not working. I would appreciate your help!
The function mysql_query does not return the value of the column fetched, instead it returns a MySQL resource which you use to extract the column value returned by the query.
Change:
$loc = mysql_query($query);
to:
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if ($row = mysql_fetch_assoc($result)) {
$loc = $row["loc"];
}
You are storing mysql_query() return value in $loc which is a resource.
For SELECT, SHOW, DESCRIBE, EXPLAIN and other statements returning resultset, mysql_query() returns a resource on success, or FALSE on error.
So, $loc is not 1 or neither equals to 2.
You need to use mysql_fetch_array / mysql_fetch_object, etc to manipulate the resource.
You must fetch the recordset with, in example mysql_fetch_row
Example #1 Fetching one row with mysql_fetch_row()
<?php
$result = mysql_query("SELECT id,email FROM people WHERE id = '42'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
echo $row[0]; // 42
echo $row[1]; // the email value
?>
But, be careful with SQL injection attacks!
http://es.php.net/manual/en/security.database.sql-injection.php
Here is the code in question:
From index.php:
require_once('includes/DbConnector.php');
// Create an object (instance) of the DbConnector
$connector = new DbConnector();
// Execute the query to retrieve articles
$query1 = "SELECT id, title FROM articles ORDER BY id DESC LIMIT 0,5";
$result = $connector->query($query1);
echo "vardump1:";
var_dump($result);
echo "\n";
/*(!line 17!)*/ echo "Number of rows in the result of the query:".mysql_num_rows($result)."\n";
// Get an array containing the results.
// Loop for each item in that array
while ($row = $connector->fetchArray($result)){
echo '<p> <a href="viewArticle.php?id='.$row['id'].'">';
echo $row['title'];
echo '</a> </p>';
From dbconnector.php:
$settings = SystemComponent::getSettings();
// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];
// Connect to the database
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));
} //end constructor
//*** Function: query, Purpose: Execute a database query ***
function query($query) {
echo "Query Statement: ".$query."\n";
$this->theQuery = $query;
return mysql_query($query, $this->link) or die(mysql_error());
}
//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {
echo "<|";
var_dump($result);
echo "|> \n";
/*(!line 50!)*/$res= mysql_fetch_array($result) or die(mysql_error());
echo $res['id']."-".$res['title']."-".$res['imagelink']."-".$res['text'];
return $res;
}
Output:
Query Statement: SELECT id, title FROM articles ORDER BY id DESC LIMIT 0,5 vardump1:bool(true)
PHP Error Message
Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /*path to*/index.php on line 17
Number of rows in the result of the query: <|bool(true) |>
PHP Error Message
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /*path to*/DbConnector.php on line 50
Your problem is in fallowing line:
return mysql_query($query, $this->link) or die(mysql_error())
it should have been written like this:
$result = mysql_query($query, $this->link);
if(!$result) die(mysql_error());
return $result;
It is common in dynamic languages that or returns first object which evaluates to true, but in PHP the result of X or Y is always true or false.
As you can learn from the manual, mysql_query return value type is not boolean but resource.
Something in your code converting it
Agree with above, you have an issue with your mysql_query. It should never return True. Either false or a resource.
Refactor : mysql_query($query, $this->link) or die(mysql_error())
echo mysqlerror() after your query and see what the error message is. You probably do not have a valid connection.
I am trying to access some information from mysql, but am getting the warning: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource for the second line of code below, any help would be much appreciated.
$musicfiles=getmusicfiles($records['m_id']);
$mus=mysql_fetch_assoc($musicfiles);
for($j=0;$j<2;$j++)
{
if(file_exists($mus['musicpath']))
{
echo ''.$mus['musicname'].'';
}
else
{
echo 'Hello world';
}
}
function getmusicfiles($m_id)
{
$music="select * from music WHERE itemid=".$s_id;
$result=getQuery($music,$l);
return $result;
}
Generally, the mysql_* functions are used as follows:
$id = 1234;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
// $query is a string with the MySQL query
$resource = mysql_query($query);
// $resource is a *MySQL result resource* - a mere link to the result set
while ($row = mysql_fetch_assoc($resource)) {
// $row is an associative array from the result set
print_r($row);
// do something with $row
}
If you pass something to mysql_fetch_assoc that is not a MySQL result resource (whether it's a string, an object, or a boolean), the function will complain that it doesn't know what to do with the parameter; which is exactly what you are seeing.
A common gotcha: you get this warning if you pass something (other than a valid query string) to mysql_query:
$id = null;
$query = 'SELECT name, genre FROM sometable WHERE id=' . $id;
$res = mysql_query($query);
// $res === FALSE because the query was invalid
// ( "SELECT name, genre FROM sometable WHERE id=" is not a valid query )
mysql_fetch_assoc($res);
// Warning: don't know what to do with FALSE, as it's not a MySQL result resource
Without seeing the code of getmusicfiles there's not a lot we can really help you with. You should be returning a valid mysql resource in that function.
As others have noted, you need to return a valid mysql resource into the mysql_fetch_assoc function to retrieve the next row. For example:
$sql = "select * from table";
$resultSet = mysql_query($sql) or die("Couldn't query the database.");
echo "Num Rows: " . mysql_num_rows($resultSet);
while ($resultRowArr = mysql_fetch_assoc($resultSet)) {
...
}
I think you need to specify what the function getQuery()
$result=getQuery($music,$l);
does
It depends on what exactly getmusicfiles() does. It must return a result of mysql_query() function call, then it will be a "valid MySQL result".
And you most probably wanted to put the line $mus=mysql_fetch_assoc($musicfiles) inside of the for cycle to fetch several rows one after another.
function getmusicfiles($m_id) {
$music="select * from music WHERE itemid=".$s_id;
$m_id != $s_id ?