Object can't be converted to a string in MySQLi PHP [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.
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\xxx\dash.php on line 20
I am quite fairly new, and being a old-school coder, simply using mysql_result to grab such data, I am unaware of how to go about this. I have a class->function setup.
Line 20 of dash.php contains:
echo $user->GetVar('rank', 'Liam', $mysqli);
While, the function is:
function GetVar($var, $username, $mysqli)
{
$result = $mysqli->query("SELECT " . $var . " FROM users WHERE username = '" . $username . "' LIMIT 1");
return $result;
$result->close();
}
Now, to my understanding, I am meant to convert $result into a string, but I am not fully aware of how to do so. I've tried using a few methods, but to no avail. So I've come to the community to hopefully get a answer, I've also looked around but noticed that all other threads are asking for num_rows, while I just want to grab the string from the query select.

You have to fetch it first before echoing the results. Rough Example:
function GetVar($var, $username, $mysqli) {
// make the query
$query = $mysqli->query("SELECT ".$var." FROM users WHERE username = '".$username."' LIMIT 1");
$result = $query->fetch_assoc(); // fetch it first
return $result[$var];
}
Then use your function:
echo $user->GetVar('rank', 'Liam', $mysqli);
Important Note: Since you're starting out, kindly check about prepared statements. Don't directly append user input on your query.

if ($result = $mysqli->query($query)) {
while($row = $result->fetch_object()) {
echo row['column_name'];
}
}
$result->close();
where you see 'column_name put the name of the column you want to get the string from.

Related

Is there a solution to "object of class mysqli_result could not be converted to string"? [duplicate]

This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
I searched the Internet for some Solutions but none of it works and I can't find out why. I'm new to PHP and MYSQL/MyAdmin so I really don't understand what I did wrong.
I've already tried several commands and "while $row = $result->fetch_array()" and stuff like that.
$Word = "SELECT Word FROM RandWord WHERE Number = '$Number'";
$Word = mysqli_query($data, $Word);
echo $Word;
$Amount = count($Word);
I want it to Output the "Count($Word);" for me, but it can't even echo because it can not be converted into a string. I want to see the word and use it.
You need to actually fetch the results first, before you can use it. You are also vulnerable to SQL injection attacks, so use a prepared statement instead.
In your code $Word is a result-object, which holds information - but you need to use a fetching method to retrieve the data first. count() in PHP is only usable on arrays (or on objects, but not that object which you get from mysqli_query()).
$query = "SELECT Word FROM RandWord WHERE Number = ?";
$stmt = $data->prepare($query);
$stmt->bind_param("s", $Number);
$stmt->execute();
$stmt->bind_result($word);
while ($stmt->fetch()) {
echo $word;
}
$stmt->close();
If you want it to be a count of each word, you have to run a query using the MySQL function COUNT() instead.
$query = "SELECT Word, COUNT(Word) as cnt FROM RandWord WHERE Number = ? GROUP BY Word";
$stmt = $data->prepare($query);
$stmt->bind_param("s", $Number);
$stmt->execute();
$stmt->bind_result($word, $count);
while ($stmt->fetch()) {
echo $word." has count ".$count;
}
$stmt->close();

How do you convert a mysqli_result into a string? [duplicate]

This question already has answers here:
Single result from database using mysqli
(6 answers)
Closed 3 years ago.
I'm trying to echo the result of a mysqli_query however I keep getting the error 'Catchable fatal error: Object of class mysqli_result could not be converted to string' on line 'echo $result;'.
Is there any way I can convert it into a string so that it can be echoed? (P.S sorry if this is easy, I'm new to coding.)
My database is successfully connected and the SQL statements definitely work.
$sql= "SELECT ImageURL FROM `unnormalisedtable` WHERE Yeargroup = 9 ORDER BY RAND() LIMIT 1" ;
$result = mysqli_query($db, $sql);
echo $result;
The expected output is that the result of my SQLi query will be printed on screen, however the error is generated instead. Thanks for any help in advance.
Since you limit the selection to one entry use
$row = mysqli_fetch_array($result);
echo $row['ImageURL'];
If you select more than one entry loop over the result.
while($row = mysqli_fetch_array($result)) {
echo $row['ImageURL'];
}

fetch_assoc mysqli returning empty [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 years ago.
I an trying to query a mySQL database using a PHP function. Intermittantly, the function that I am using does not seem to return a result. As far as I can detect, it's not a null response, and based on the function, it doesn't seem to be returning an invalid result ( the return string Nuthin in this case ).
function GeneratePiece2 ($sqlstr){
$conn = new mysqli(gHOST, gUSER, gPASSWORD, gDATABASE);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = $conn->query($sqlstr);
$returnable = "";
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo $row;
$returnable = $row;
}
} else {
return "nuthin";
}
$conn->close();
return $returnable;
}
I've been using the same SQL Query of
SELECT Name FROM Char_Name_full WHERE Male=1 AND DivisionID=12 ORDER BY RAND() LIMIT 1
Around 80% of the time I will receive a result of something like {"Name":"Christoph"} but 1 out of 10 returns nothing.
If someone is having problems with fetch_assoc() returning "Undefined index":
Check the indexes names (database Column name) - they are case sensitive.
Example:
For "SELECT Name FROM..." Your code must be $row["Name"]. Not NAME or name.
In your query, you are checking if the number of rows is greater than zero, but you are not doing anything to check if the value that is returned is Null. The behaviour that you are describing matches the scenario of at least 1 row in 'Name' that has a NULL value.
Note that I am not going to comment on your code structure or syntax here, but I have changed your response values to help identify / prove that a null value is the issue here.
Also, if your query is limited to a single row, then the while loop will only iterate once.
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
// Echo out the values for Name in the result set
if(is_null($row["Name"], ))
echo '[NULL]';
else
echo $row["Name"];
// your application logic ;)
$returnable = $row;
}
} else {
return "no rows";
}
Please consider using a SQL IDE like Toad for MySQL along side your development, then you can visually inspect your data for these issues without writing code hacks :)

PHP bind_param not binding parameter [duplicate]

This question already has answers here:
MySQLI Prepared Statement: num_rows & fetch_assoc
(5 answers)
Closed 5 years ago.
I am trying to search a table for specific items using a prepared statement in PHP. I am getting no errors, but also getting no record. Here is my code:
$items = [];
$search = "john";
if ($stmt = $this->con->prepare("SELECT * FROM phptest WHERE search = ?")) { //'john'";
$stmt->bind_param("s",$search);
$stmt->execute();
while ($row = mysqli_fetch_array($stmt)) {
$item = [];
$item['id'] = $row['id'];
$item['first'] = $row['search'];
$item['last'] = $row['data'];
array_push($items, $item);
}
}
return $items;
Now, when I don't use a prepared statement, and just SELECT * FROM phptest I get all the results in the table (including the item where search = 'john'). Furthermore, if I use the query SELECT * FROM phptest WHERE search = 'john' I get the one record where search = 'john'
But as soon as I turn it into the prepared statement, I get zero errors but zero records. I do get a warning:
mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given
Which made me think my bind_param or execute() was returning FALSE, but when I check, it does not appear to be returning false.
I started off my adventure working through the tutorial https://www.simplifiedcoding.net/android-mysql-tutorial-to-perform-basic-crud-operation/, which I thought I understood fully but ran into my error when trying to make my own PHP API.
I then went to the manual http://php.net/manual/fr/mysqli.prepare.php, but still cannot find my error.
Though it has been closed as "off-topic," I have reviewed PHP bind_param not working and found nothing applicable to my situation.
Likewise, I am not finding the error in PHP bind_param not defined nor php bind_param is not working.
You're very close. mysqli_fetch_array() expects to be passed a result object, not the statement object itself:
$stmt = $conn->prepare(...);
$stmt->bind_param(...);
$stmt->execute();
$result = $stmt->get_result();
while ($row = mysqli_fetch_array($result)) {
Or, in the fully OO manner:
while ($row = $result->fetch_array()) {

How to retrieve information using PDO method [duplicate]

This question already has answers here:
How to fetch a row with PDO
(2 answers)
Closed 8 years ago.
I am building a login script using the PDO method. I would like to register some sessions from the user account. Every time I try to pull information from the database I get blank. I am new to PDO. Here is what I have so far:
try{
$conn = new PDO(...........);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
$conn->exec("SET CHARACTER SET utf8");
$sql = "SELECT * FROM $table WHERE USER = ':user' AND pass = ':pass'";
$UpdateSql = $conn->prepare($sql);
$UpdateSql->bindValue(':user',$user,PDO::PARAM_STR);
$UpdateSql->bindValue(':pass',$pass,PDO::PARAM_STR);
$results = $UpdateSql->execute();
/*Here is where the error comes in
foreach($results as $row)
{
$_SESSION['account'] = $row['account'];
}
*/
/*I also tried this
foreach($UpdateSql as $row)
{
$_SESSION['account'] = $row['account'];
}
*/
}catch(PDOException $e){
echo $e->getMessage();
}
When I tried the first foreach() I received an error Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\drug_center\dc_login.php on line 26 and the second foreach() gave me an empty result. Can someone please explain to me where I am making my mistake?
You'll be needing the $UpdateSql->fetchAll() method. This will give you a result set which can be traversed.
Secondly you'll be specyfing the parameters trough bindValue, so you don't need the ' around the values.
$table = (in_array($table, array('table1','table2')) ? $table : false;
//make sure you put some input-validation on the $table variabel!!
if($table){
$sql = "SELECT * FROM $table WHERE user = :user AND pass = :pass";
//lose the ' around the :pass
$UpdateSql = $conn->prepare($sql);
$UpdateSql->bindValue(':user',$user,PDO::PARAM_STR);
$UpdateSql->bindValue(':pass',$pass,PDO::PARAM_STR);
$UpdateSql->execute();
foreach($UpdateSql->fetchAll() AS $row){
// do some magic
}
}else{
throw new Exception("Error: table not allowed", 1);
}
Execute is to run a stored procedure on a SQL Server, you can
$results = $UpdateSql->fetchAll($sql);
foreach ($results as $row)
//stuff
}
The function prepare() returns an object of PDOStatement class. As it says on the PHP manual, PDOStatement::execute() does not return results, it returns a boolean instead to indicate if the query was successful or not. You need to use the fetch commands the PDOStatement has.

Categories