This question already has answers here:
Object of class mysqli_result could not be converted to string
(5 answers)
Closed 1 year ago.
What I am trying to do is get the values of the $r variable (returns some vehicle id values) to display on the page. However, it returns the following error.
Recoverable fatal error: Object of class mysqli_result could not be
converted to string in
C:\xampp\htdocs\SAMADHI\system\module\reservation\controller\reservationcontroller.php
on line 166
The problem is on the echo $r statement. I tried echo '$r' but then it shows nothing even though it displays the the message 'vehicle available'.
if ($nor > 0) {
$r = $objs->searchVehicle($vhandover, $vreturn, $seatcap);
if ($r) {
$msg = "Vehicle available";
$status = 1;
echo $r;
} else {
$msg = "Something is not right!";
$status = 0;
}
}
What am I doing wrong here and how can I correct it?
Let me assume, your vehicle table have following column - id, name, type. When your query executes, $r holds an associative array with search result-
$r = [ ['id'=>1, 'name'=>"toyota", 'type'=> "regular"], ....]
This is not any String. So if you want to echo any of the column value you need to mention it like -
echo $r['name'];
But if your query returns multiple results then, you need to put the echo inside a foreach loop.
foreach($r as $row) {
echo $row['name'];
}
UPDATE
If the above code doesn't work for you then try the following-
while($row = $r->fetch_assoc()) {
echo $row['id'];
}
UPDATE: 2
You can use fetch_array($r) -
while ($row = fetch_array($r)) {
echo $row['name'];
}
Hope that clears your concept!
Related
This question already has an answer here:
How to get column names from PDO's fetchAll result?
(1 answer)
Closed 2 years ago.
The following code works perfectly well unless there is only one result, in which case only the <tr> containing the column names displays in the web page. Further, a search for the name 'Bracker' produces the result as described above but a search for 'Bra' works correctly while 'Brac' does not. The same does not apply to the name 'Dawe' which, if there is only one result, only appears amongst many others when a search for 'Da' is undertaken.
<?php
include 'connect.php';
if (isset($_POST['submit-keyword'])) {
$keyword = ($_POST['keyword']);
$qry = "SELECT * FROM Ely_NBR WHERE Founder LIKE ? ORDER BY DATE";
$stmt = $con->prepare($qry);
$stmt->execute(["%$keyword%"]);
print "<table>";
$result = ($stmt);
//return only the first row (we only need field names)
$row = $result->fetch(PDO::FETCH_ASSOC);
print " <tr>";
foreach ($row as $field => $value){
print " <th>$field</th>";
} // end foreach
print " </tr>";
//second query gets the data
$data = ($stmt);
$data->setFetchMode(PDO::FETCH_ASSOC);
foreach($data as $row){
print " <tr>";
foreach ($row as $name=>$value){
print " <td>$value</td>";
} // end field loop
print " </tr>";
} // end record loop
print "</table>";
}
?>
You are using your first result row to display the column headings. When you call PDOStatement::fetch() it moves its internal cursor on the result set.
Therefore your loop to display the data starts printing the results from the 2nd row.
See PDOStatement::fetch() documentation: Fetches the next row from a result set.
If you want to get the column names you may want to look at:
PDOStatement::columnCount()
PDOStatement::getColumnMeta()
And print headings like this:
for ($i = 0; $i < $stmt->columnCount(); $i++) {
$columnInfos = $stmt->getColumnMeta($i);
echo '<th>' . $columnInfos['name'] . '</th>';
}
This question already has answers here:
How to loop through a mysql result set
(6 answers)
Closed 3 years ago.
I'm trying to loop through a MySQL table using PHP, but it is only showing one line.
//Retrieve a list of outstanding developments
$sql = "SELECT * FROM tblDevelopment WHERE strStatus=?";
$statement = mysqli_stmt_init($conn);
//Check for any errors in the SQL statement
if (!mysqli_stmt_prepare($statement,$sql)){
//Report any errors with the prepared $statement
header("Location: ../sqlerror.php");
exit();
} else {
//If there are no errors, query the database for the username
mysqli_stmt_bind_param($statement,'s', $status);
mysqli_stmt_execute($statement);
$results = mysqli_stmt_get_result($statement);
if ($row = mysqli_fetch_assoc($results)) {
echo 'header';
while ($row = mysqli_fetch_assoc($results))
{
echo $row['strDetail'] . "</";
}
echo 'footer';
} else {
echo 'No results to display';
}
}
The code works when there are no results, but it only shows one result when there are more than one - any ideas what I'm doing wrong?
You are almost there... you need to keep calling mysqli_fetch_assoc until you reach the end of the result set. Changing your if to a while should be enough to get you rolling.
while (($row = mysqli_fetch_assoc($results)) !== null) {
This question already has answers here:
php json_encode not working on arrays partially
(2 answers)
Closed 5 years ago.
I have a PHP script where it fetches all records from a table and encodes it to JSON. The table has a total of 246 records. echo count(); returns 246 as well.
The problem is, whenever I use json_encode, it doesn't display the values from the array at all, all I see is a blank page. But if I reduce the number of records to 13 instead of 246, it works and it displays the encoded JSON result. I have also tried to increase the memory_limit at my php.ini file to 4095M, but no avail.
$result = mysqli_query($con, "SELECT * FROM cities");
if (mysqli_num_rows($result) > 0) {
$response["cities"] = array();
$city = array();
while($row = mysqli_fetch_assoc($result)) {
$city[] = $row;
array_push($response["cities"], $city);
}
$response["success"] = 1;
echo json_encode($response);
}
Try below and you'll get to know what is happening exactly:
$json = json_encode($response);
if ($json)
echo $json;
else
echo json_last_error_msg();
json_last_error_msg() - Returns the error string of the last json_encode() or json_decode() call
Array "city" is expanding for each call and you are pushing the complete array on each iteration in loop .
Try :
while($row = mysqli_fetch_assoc($result)) {
array_push($response["cities"], $row);
}
It should work
Remove $response array push $row into $cities array. After pushing all city set the city and response in json_encode(); function like this echo json_encode(array("cities"=>$cities, "success"=>1));
if (mysqli_num_rows($result) > 0) {
$cities = array();
while($row = mysqli_fetch_assoc($result)) {
array_push($cities, $row);
}
echo json_encode(array("cities"=>$cities, "success"=>1));
}
This question already has answers here:
Mysqli query doesn't work twice
(2 answers)
Closed 5 years ago.
I'm retrieving some data from a mysql database. There are two loops which uses the same result set.
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
This loop ends with success. then in the same page I have the following loop.
while ($row = mysqli_fetch_array($newsQuery)) {
echo $row["news_content"];
}
This loop doesn't return anything even if there are content in the table. When I try it in the first loop. the content is displayed correctly. Any idea on what I'm doing wrong.
From PHP's mysqli_fetch_array DOCS:
Returns an array that corresponds to the fetched row or NULL if there are no more rows for the resultset represented by the result parameter.
You are using a 'while' loop on $row = mysqli_fetch_array($newsQuery)
This means the loop will keep going untill mysqli_fetch_array($newsQuery) returns NULL.
This is the reason why you cant use that loop again, since mysqli has finished fetching the results and the mysqli_fetch_array($newsQuery) now returns NULL untill you make a new query.
Try populating a variable with the results first, then loop on that variable:
$results = array();
while ($row = mysqli_fetch_array($newsQuery)) {
$results[] = $row;
}
foreach ($results as $key => $row) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
}
foreach ($results as $key => $row) {
echo $row["news_content"];
}
While it is best to avoid logic that results in looping through a result set twice, if necessary you need to reset the result set back to the start:-
mysqli_data_seek($newsQuery, 0);
Because you already fetch the value of $newsQuery Try this code
//temporary save the news content into array
$content = array();
$x=0;
while ($row = mysqli_fetch_array($newsQuery)) {
echo "<a href='news-article.php?articleId=" .$row["news_id"]."' class='list-group-item active'>".$row["news_title"]."</a>";
$content[$x]= $row["news_content"];
$x++;
}
and if you want to retrieve it
//now retrieve it
for($y=0; $y<count($content); $y++)
{
echo $content[$y]+"<br/>";
}
I'm trying to figure out why I'm receiving this error when trying to echo data from a database table, but can't exactly see what I'm doing.
$query = "SELECT * from web_projects"; // Select all rows from web_projects table
$result = mysqli_query ($con,$query);
while ($row = mysqli_fetch_array ($result)) {
foreach($row as $web) {
echo "<p>Name: ".$web->name."</p>";
echo "<p>Technologies: ".$web->tech."</p>";
echo "<p>Description: ".$web->description."</p>";
}
}
Theres only one row in the table, but when compiled I'm getting this:
Notice: Trying to get property of non-object in
/Users/leecollings/Sites/leecollings.co/index.php on line 31 Name:
Notice: Trying to get property of non-object in
/Users/leecollings/Sites/leecollings.co/index.php on line 32
etc
Have I missed something glaringly obviously?
I would remove foreach line, and use array accessing:
$query = "SELECT * from web_projects"; // Select all rows from web_projects table
$result = mysqli_query ($con,$query);
while ($row = mysqli_fetch_array ($result)) {
echo "<p>Name: ".$row['name']."</p>";
echo "<p>Technologies: ".$row['tech']."</p>";
echo "<p>Description: ".$row['description']."</p>";
}
Error message is very clear: $web is not object. Read the manual more thoroughly: mysqli_fetch_array() returns array or NULL, not object.
You are fetching an array, but you are trying to echo an object. Use this instead:
echo "<p>Name: ".$web['name']."</p>";
Full edited code:
$query = "SELECT * from web_projects"; // Select all rows from web_projects table
$result = mysqli_query ($con,$query);
while ($row = mysqli_fetch_array ($result)) {
echo "<p>Name: ".$row['name']."</p>";
echo "<p>Technologies: ".$row['tech']."</p>";
echo "<p>Description: ".$row['description']."</p>";
}