Directly echo the resulting data show an error msg [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.
When I am echo the $result variable. It display an error msg like this:
Catchable fatal error: Object of class mysqli_result could not be converted to string in D:\Inspiration\server\Table2_yahooData_db.php
on line 13
<?php
// connect to the dataBase
$conn = mysqli_connect('localhost', 'root', '', 'yahooData');
//checking Connection.
if (!$conn) {
die('Error connection failed: ' . mysqli_connect_error($conn));
}
// Creating select query Using sql commands.
$sql = "SELECT * FROM User;" ;
$result = mysqli_query($conn, $sql);
echo $result;
mysqli_close($conn);
?>

$result is an object.
You cannot print it with string's echo function.
You can rather print it with print_r($result);
echo is for scalar variables (which have single value or are single dimensions) like number, string. For multi-dimensional variables e.g. array, objects we need to use print_r() which prints the whole tree.

When using a SELECT query the mysqli_query() function returns a resource, not a string. You need to use mysqli_fetch_assoc() to put the results into an array. Here is an object-oriented example:
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if ($mysqli->connect_errno) {
printf("Connect failed: %s\n", $mysqli->connect_error);
exit();
}
$query = "SELECT name FROM User";
if ($result = $mysqli->query($query)) {
/* fetch associative array */
while ($row = $result->fetch_assoc()) {
echo $row['name'];
}
/* free result set */
$result->free();
}

Related

setting variable value to the row data php [duplicate]

This question already has an answer here:
How to fix Trying to access array offset on value of type null error
(1 answer)
Closed 1 year ago.
I am trying to use table data in a single row data as the value of an variable in my code below and i keep getting "Warning: Trying to access array offset on value of type null in C:\xampp\htdocs\done\test1.php on line 29"
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT lev1 FROM ref where id=1";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "lev1: " . $row["lev1"]. "";
}
}
$mamo=$row["lev1"];
$conn->close();
what I'm I dong wrong ?
Trying to access array offset on value of type null
It means that $row is null (in the $mamo=$row["lev1"]; line), therefore it cannot behave as an array.
If you're using while ($row = $result->fetch_assoc()), it will keep assigning values to $row until it can no more (because that's supposed to break the loop). After you reach the last result, $row will always inevitably be null.

Warning: mysqli_close() expects parameter 1 to be mysqli [duplicate]

This question already has answers here:
php warning: mysqli_close() expects parameter 1 to be mysqli
(2 answers)
Closed 1 year ago.
I have this PHP code on a WAMP server with MySQL and this error appears in a dialog box when I visit the site. How can I fix this?
<?php
// Create connection
$con = mysqli_connect("localhost","userdb","userdb","apptestdb");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// This SQL statement selects ALL from the table 'Locations'
$sql = "SELECT * FROM Locations";
// Check if there are results
if ($result = mysqli_query($con, $sql))
{
// If so, then create a results array and a temporary one
// to hold the data
$resultArray = array();
$tempArray = array();
// Loop through each row in the result set
while($row = $result->fetch_object())
{
// Add each row into our results array
$tempArray = $row;
array_push($resultArray, $tempArray);
}
// Finally, encode the array to JSON and output the results
echo json_encode($resultArray);
}
// Close connections
mysqli_close($result);
mysqli_close($con);
?>
You don't need this line:
mysqli_close($result);
You only need to close the connection.

How to convert the object resource into string and store it in a variable in php [duplicate]

This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 8 years ago.
The error is
Catchable fatal error: Object of class mysqli_result could not be converted to string in C:\xampp\htdocs\posdef\index.php on line 18
Evidently, I perceive that the query returns an object resource, but how to convert it into a string. I am caught up in that problem. How to convert the object resource into string and store it in a variable?
This is the piece of code where I am trying to recover the data stored -
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db($con, "new");
$mylogo = mysqli_query($con, "SELECT first FROM hello WHERE sno=6");
You got the data, now you just need to fetch it:
$con = mysqli_connect("localhost", "root", "");
mysqli_select_db($con, "new");
$mylogo = mysqli_query($con, "SELECT first FROM hello WHERE sno=6");
while ($row = $mylogo->fetch_assoc()) {
echo $row["first"];
}
Check out the docs, there are additional examples. mysqli_fetch_assoc
Once you run the query, you have to read the results. If you're only expecting ONE row back, you can do the following instead of a while loop:
$rslt = mysqli_query($con, "SELECT first FROM hello WHERE son=6");
$row = $result->fetch_assoc();
$mylogo = $row['first'];

update mysql_num_rows to new Mysqli standard: mysqli_stmt_num_rows

I have a PHP page with some Mysqli that I am attempting to convert from MySql. I think I've converted most of it correctly, but I am getting the following error message when I try to execute the code (below):
Connection was OK!
Warning: mysqli_stmt_num_rows() expects parameter 1 to be mysqli_stmt, object given in /quantityremaining5.php on line 25
9999
I'm a bit new to this, so please be gentle - what is that I'm doing wrong? thanks!
<?php
include 'quantitytest_config.php';
// Create connection to MySQL
$link = mysqli_connect($hostname, $username, $password);
// Check connection
if (mysqli_connect_errno($link))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
} else { echo "Connection was OK!\n";}
//select a database to work with
$selected = mysqli_select_db($link, "grace59_countdown");
// or die("Could not select countdown");
// use if TWO SEPARATE columns for date and time
//execute the SQL query and return records
$result = mysqli_query($link,
"SELECT items
FROM cases
WHERE datetime<=NOW()
Limit 1 ");
if(mysqli_stmt_num_rows($result) == 0){
echo "9999";
} else {
//fetch tha data from the database
while ($row = mysqli_fetch_array($result)) {
echo "Quantity:".$row{'items'}."<br>";
}
}
//close the connection
mysqli_close($link);
?>
Use mysqli_num_rows($result) or $result->num_rows. As the name indicates, mysqli_stmt_num_rows() is intended to be used with a mysqli_stmt object (as returned by mysqli_prepare()).
See the documentation.

Error calling MySQL stored procedure through PHP

I'm trying to call a stored procedure from MySQL and get back the two OUT parameters (#eset and #leng). I would like to echo out these two parameters back to JavaScript where I have an XMLHttpRequest waiting for the results.
I'm getting this error :
Strict standards: mysqli::next_result(): There is no next result set.
Here's my code:
<?php
//get the q parameter from URL
$q=$_GET["q"];
$eset= "";
$length= 0;
// Opens a connection to a MySQL server
$db= new mysqli('localhost', 'db_name', 'pass');
if (!$db) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = $db->select_db('db_name');
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$db->multi_query( "CALL mst2($q, #eset, #leng);SELECT #eset as eset;SELECT #leng as length" );
$db->next_result(); // flush the null RS from the call
$eset=$db->store_result(); // get the RS containing the id
//echo $eset->fetch_object()->eset, "\n";
$length= $db->store_result();
//echo $length->fetch_object()->leng, "\n";
$response= $eset.$length;
//$eset->free();
//$length->free();
//$response=str_shuffle($q);
//output the response
echo $response;
?>
I'm assuming the first argument of your stored procedure is VARCHAR, so the first problem is that you are passing the $q variable without quotes in the query. It should be like this:
$db->multi_query("CALL mst2('$q', #eset, #leng); SELECT #eset as eset; SELECT #leng as length");
Also, you don't need to make two SELECT calls, do it only once:
SELECT #eset AS eset, #leng AS leng;
Needless to say that user inputs should never be trusted. You should use prepared statements:
if (($stmt = $db->prepare("CALL mst2(?, #eset, #leng)"))) {
$stmt->bind_param("s", $q);
$stmt->execute();
$stmt->close();
if (($res = $db->query("SELECT #eset AS eset, #leng AS leng"))) {
list($eset, $leng) = $res->fetch_array();
$result = $eset.$length;
echo $result;
$res->free();
}
}

Categories