PHP and MySQLi Error Converting Query Results into String [duplicate] - php

This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
I'm working on an assignment for school which involves using PHP to generate a table of SQL results. I'm having a problem converting the results of my query. This is my error message:
Catchable fatal error: Object of class mysqli_result could not be converted to string
Here is the relevant part of my code:
$q = "SELECT pages.pageid,pages.pagetitle,pagetype.pagetypename,stylesheets.stylename
FROM pages
INNER JOIN stylesheets
ON pages.styleid=stylesheets.styleid
INNER JOIN pagetype
ON pages.pagetypeid=pagetype.pagetypeid
ORDER by pages.".$sortBy." ".$sortDirection;
print("<p>Query: ".$q."</p>\n");
$r = mysqli_query($db_link,$q);
$n = mysqli_num_rows($r);
print("<p>$r</p>");
My only theory is that maybe since I'm using an inner join with multiple tables there's something additional I need to do? I ran the query the code displayed in the MySQL server and it worked fine and returned the right results.

The problem is that $r is an object, not a string. You want to print the value of $n, not $r. Change your print statement to the following to fix the error:
print("<p>$n</p>");
It's unclear from the question details whether you're asking how to print number of rows, or how to print the actual results of the query.
If you're trying to do the latter: mysqli_query() returns a mysqli_result object. The returned result resource should be passed to mysqli_fetch_array(), mysqli_fetch_assoc() or other functions for dealing with result tables, to access the returned data.
The basic structure would look like:
$r = mysqli_query($db_link,$q) or die(mysqli_error($db_link);
$n = mysqli_num_rows($r);
while ($row = mysqli_fetch_assoc($r)) {
// use $row['key']
}
Also, I suggest you use more descriptive variable names in your code -- it makes your code maintainable and easy to read.
You should also be more careful about constructing your query strings. If $sortBy is coming from user input, it is a vector for an SQL injection attack.

mysqli_query() returns a result set resource, which is not the same as a set of results. You need to retrieve the data with mysql_fetch_array() or similar.
$r = mysqli_query($db_link,$q) or die(mysqli_error($db_link);
$n = mysqli_num_rows($r);
while ($row = mysqli_fetch_array($r)) {
var_dump($row); // replace this with your own code to format the output
}

Part of your confusion is that you are using lots of 1 character strings that—in my honest opinion—simply cause confusion & don’t really benefit coding nowadays. Use real words for strings & make your life—and debugging process—easier. Also your query & results seem to have not been parsed. Here is my take on your code using an object oriented style of handling:
$query = "SELECT pages.pageid,pages.pagetitle,pagetype.pagetypename,stylesheets.stylename
FROM pages
INNER JOIN stylesheets
ON pages.styleid=stylesheets.styleid
INNER JOIN pagetype
ON pages.pagetypeid=pagetype.pagetypeid
ORDER by pages.".$sortBy." ".$sortDirection;
print("<p>Query: ".$query."</p>\n");
$result = $db_link->query($query);
$number_of_rows = $result->num_rows($result);
while($row = $result->fetch_assoc()){
print("<p>$row</p>");
}

Related

Error accessing MySQL database with PHP object (nested queries)

I want to get some data from a Sphinx server and pass it to MySQL to execute some queries. I'm new to PHP so probably I'm missing something here. I've looked for similar questions but can't find anything so maybe you can help me.
The error is in the first while. I'm pretty sure it's due to the $rown variable but don't know the reason. (I've verified that I can retrieve data from the connections so it is passing the data where the error lies - could be the sql syntax of the query but that seems fine).
Edited the code thanks to the comments below, now I get the error: Warning: mysqli_fetch_object() expects parameter 1 to be mysqli_result, boolean given in C:\Apache24\htdocs\test3.php on line 20. This is because the query failed, I still suspect it is because $rown.
$sphinxcon = mysqli_connect...
$mysqlcon = mysqli_connect...
$query = "SELECT names FROM iproducts LIMIT 0,1000";
$raw_results= mysqli_query($sphinxcon, $query);
//Until here works ok, now I want to pass $raw_results to MySQL
while ($row = mysqli_fetch_object($raw_results)) {
$rown = $row->names;
$mquery = "SELECT text FROM claims WHERE EXISTS ($rown) LIMIT 0,1000";
$mysqlresults = mysqli_query($mysqlcon, $mquery);
while ($final = mysqli_fetch_object($mysqlresults)) //this is line 20
{
printf ("%s<br />", $final->text);
}
}
Thanks :)
Well $row contains an object, so would have to use it as such, maybe
$rown = (string)$row->names;
... assuming you want the variable to contain the 'names' attribute you just SELECTed from Sphinx index.
As for the mysql EXISTS(), no idea what you really doing here, seems confused. How you structured it currently suggests that 'names' attribute in sphinx contains a complete SELECT query, that mysql could execute for the exists condition. That seems unlikely.
Guessing you meaning to more normal query something like
$mquery = "SELECT text FROM claims WHERE text LIKE '%$rown%' LIMIT 0,1000";
But that is subject to SQL injection, particully if names might contain single quotes. SO should escape it. Perhaps
$rown = mysqli_real_escape_string($mysqlcon, $row->names);
But might be worth reading up on prepared queries.
btw, the 'Error' you getting, is because you creating an invalid query and not dealing with it. So $mysqlresults is FALSE.
$mysqlresults = mysqli_query($mysqlcon, $mquery) or die("Mysql Error: ".mysqli_error($link)."\n");

multi query select using wrong array?

I have a multi query select which half works. The first query is straight forward.
$sql = "SELECT riskAudDate, riskClientId, RiskNewId FROM tblriskregister ORDER BY riskId DESC LIMIT 1;";
The second one doesn't seem to work even when I do it on its own:
$sql ="SELECT LAST(riskFacility) FROM tbleClients";
If I get rid of the LAST it returns the first entry in that field of the table. I want to use the LAST to get the LAST entry in that field.
When I do the first query on its own I get the data returned and I can echo it to the screen. When I add the second (with out the LAST) I get nothing. Here is what I am using
$result = $conn->query($sql);
if ($result == TRUE){
$r = $result->fetch_array(MYSQLI_ASSOC);
echo $r['riskAudDate'];
echo $r['riskClientId'];
echo $r['RiskNewId'];
echo $r['riskFacility'];
echo "<pre>";
print_r($r);
echo "</pre>";
}
The last bit is just for me to see whats in the array and just for testing.
So I have worked out that its the results array that is not right.
If I change the actual query to multi query I get this:
Call to a member function fetch_array() on boolean
So the array bit seems to be wrong for a multi query. The data returned is one row from each table. It works for the top query but add in the second (which I'm not sure is correct anyway) and the whole things crashes. So I guess it's a two part question. Whats wrong with my inserts and whats wrong with my returned array?
There is no last() function in mysql, it is only supported in ms access, if I'm not much mistaken. In mysql you can do what you do in the 1st query: do an order by and limit the results to 1.
According to the error message, the $conn->query($sql) returns a boolean value (probably true), therefore you cannot call $result->fetch_array(MYSQLI_ASSOC) on it. Since we have no idea what exactly you have in $sql variable, al I can say is that you need to debug your code to detrmine why $conn->query($sql) returns a boolean value.
Although it is not that clear from mysqli_query()'s documentation, but it only supports the execution of 1 query at a time. To execute multiple queries in one go, use mysqli_multi_query() (you can call this one in OO mode as well, see documentation). However, for security reasons I would rather call mysqli_query() twice separately. It is more difficult to execute a successful sql injection attack, if you cannot execute multiple queries.
It seems to me you are trying to do two SQL-queries at once.
That is not possible. Do a separate
$result = $conn->query($sql);
if ($result == TRUE){
while( $r = $result->fetch_array(MYSQLI_ASSOC)) {
...
}
}
for each SQL-query.
concerning :
$sql ="SELECT LAST(riskFacility) FROM tbleClients";
since the last function does not exists in MySQL i would recommend doing a sort like this(because i don't know what you mean with last )
$sql ="SELECT riskFacility FROM tbleClients order by riskFacility desc limit 0,1";

SQL Sanitization Output/Datatype Error

I'm attempting to sanitize the input of some PHP/SQL code, but I keep receiving the following error when checking the number of rows:
mysqli_num_rows() expects parameter 1 to be mysqli_result
It feels like I'm missing a method to convert/handle the query after execution, and there is little in the documentation to bridge this gap. Assuming $conn is a properly connected mysqli database call, here is my code:
$qry = mysqli_prepare($conn,'SELECT * FROM table WHERE attribute=?');
mysqli_stmt_bind_param($qry,'s',$_SESSION['string']);
mysqli_stmt_execute($qry);
/* Should something go here? */
if(mysqli_num_rows($qry) > 0)
{
//foo
}
I avoided object notation because it wasn't working either - this simply appeared a little more explicit, but I'm not opposed to either method.
Looking forward to hearing any thoughts - thank you in advance!
I don't use mysqli very often, but I believe the issue stems from the fact you are trying to call the mysqli_num_rows() method against a sql string. After running the execute command, pull the results of the execution into a variable and pass that into your mysqli_num_rows() call.
// Added this to capture the results of the execution
$result = mysqli_stmt_get_result($qry);
if(mysqli_num_rows($result) > 0)
{
//foo
}
Okay, so I was able to discover a way to count the number of rows and retrieve the db output:
$stmt = mysqli_prepare($conn, 'SELECT blah FROM table WHERE attribute=?');
mysqli_stmt_bind_param($stmt,'s',$string);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
mysqli_stmt_bind_result($stmt,$bindingvar);
mysqli_stmt_fetch($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
//foo
}
And output is now assigned to $bindingvar.
It's cumbersome, but it does everything I want it to, and it's nice and procedural.
It should be noted this method doesn't work well for more than one result from a database, but given the level of problems with "get_result()" this is far better than nothing.
Hope this helps!
- M

Why is this a bad MYSQL query in PHP?

Is this a bad mysql query i used in php?
$tablenamep = $_POST["tablenamep"];
$res = mysqli_query($con, "SELECT * FROM `$tablenamep` WHERE number=9");
So when i try to fetch the result using:
while ($row = mysqli_fetch_assoc($res))
There is an sql injection error :
mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given
I have read several questions and answers regarding this error, but my question is why is the query returning a boolean, when i have even added a value to $tablenamep variable. I added the value to the variable from my android app using this code :
nameValuePairs.add(new BasicNameValuePair("tablenamep", msg));
The codes are working and there aren't any errors, but my android app is crashing when i try to get the result of the php. How can i solve this! (NOTE : there is nothing wrong in my android app, i've thoroughly checked it)
Why is this a bad query? What can i do for the Query to not return a boolean, and return the actual value?
I guess your $res = mysqli_query($con, "SELECT * FROM $tablenamep WHERE number=9");
returns fails.
As what stated here in TECHNICAL DETAILS TABLE
For successful SELECT, SHOW, DESCRIBE, or EXPLAIN queries it will
return a mysqli_result object. For other successful queries it will
return TRUE. FALSE on failure
mysqli_fetch_assoc() function needs mysqli_result but the query fails that why it returns boolean instead of object.
You will find that your query has 'failed'
Insert the bit of code below
if($result === FALSE) {
die(mysql_error());
}
just above this line
while ($row = mysqli_fetch_assoc($res))
and you will find it dies at the script there.
Odds are that your posted value has a problem with it - echo out your posted value and see if it contains any ' or " etc. etc.

mysql_fetch_assoc() expects parameter 1 to be resource, null given [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP Error: mysql_fetch_array() expects parameter 1 to be resource, boolean given
I am trying to build an array from a mysql object after querying.
The number or rows returned in the query is 68, this is why I thought a forloop would be good. However php does not like my code inside the forloop.
Here is the code:
$result = $db->query("SELECT * FROM `networktariff`");
$rows = mysql_num_rows($result);
for ($i= 0; $i<$rows; $i++)
{
$tariffs[$i] = mysql_fetch_assoc($result[$i]);
}
I am getting an error message saying :
Warning: mysql_fetch_assoc() expects parameter 1 to be resource, null given in /usr/local/www/apache22/data/quote/index.php on line 58
There is no such thing like "mysql object".
Your $db object belongs to some user-defined class and there is no point in asking anyone about this class' behavior.
Assuming that query() method just utilizing ordinary mysql_query() function call, it does return a resource, not object.
If you have a strange idea of using some class to run the query yet bare API functions for the rest,
$tariffs = array();
$result = $db->query("SELECT * FROM `networktariff`");
while ($row = mysql_fetch_assoc($result) {
$tariffs[] = $row;
}
I dunno though why your class doesn't have some helper function to get the whole data at once, something like
$tariffs = $db->query2arr("SELECT * FROM `networktariff`");
Yup, read the docs on mysql_fetch_assoc().
A better construction might be:
while($row = mysql_fetch_assoc($result)) {
// Do stuff with $row
}
To elaborate: $result does not contain any data. It's a "resource" handle that points to a resultset that MySQL has created. To access the data of the resultset, you use mysql_fetch_* and pass it the resource handle. Each time you call a fetch function, the internal pointer is incremented one row. So you'll get fresh data each time until MySQL reaches the end of the results, at which point you'll get FALSE. This is why the while() loop works.
print $result as $db->query is not standard php function, it might return you result set array.
try same code with replacing $db->query to mysql_query

Categories