PHP Array to string conversion - php

So I made a query which returns many restaurants and I put them in a variable $row:
<?php if(count($Result_restaurants)>0)
{
foreach($Result_restaurants as $row)
{ ?>
<div id="ForEveryRestaurant">
<?php
$Rest_Name = $row['name'];
//$Rest_Name = $row;
$stmt = $db->prepare("SELECT Restaurant.idRestaurant FROM Restaurant WHERE Restaurant.name = \"$Rest_Name\"");
$stmt->execute();
$idRestaurant = $stmt->fetch();
$avg = 0;
$rateSum = 0;
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
$stmtcard = $db->prepare($strcard);
$stmtcard->execute();
$result = $stmtcard->fetchAll();
if (count($result) === 0)
{
return 0;
}
foreach( $result as $coments)
{
$rateSum += $coments['rating'];
}
$avg = $rateSum / count($result);
$avg = round($avg, 1);
When I try to run my code, it prints Array to string conversion.
The problem appears in this line:
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
I searched about the error and I understand but I tried many resolutions and didn't solved the problem.
can someone help please?

You should do like the following
$stmt->execute();
$stmt->bind_result($idRestaurant);
$stmt->fetch();
Try For PDO:
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$idRestaurant = $result['idRestaurant'];

The problem is in this statement
$idRestaurant = $stmt->fetch();
Have you tried $idRestaurant = $stmt->fetch()[0];?
You can actually check what's coming into $idResturant by checking it via var_dump
var_dump($idResturant)

Check this:
$idRestaurant = $stmt->fetch();
// Its an array and you cannot use an array directly with WHERE clause in a query. Convert it to normal variable and use it.
$strcard = "SELECT rating FROM Review WHERE Review.idRestaurant = $idRestaurant";
// here you are using the array in WHERE clause
To do this:
$rating = isset($stmt->fetch()[0]) ? $stmt->fetch()[0]: null;

Related

PHP Mysql fetched data blank

Having a bit of an issue with my php code..
$stmt = $db->prepare("SELECT * FROM mytable WHERE TheGroup = :SearchName ORDER BY TheTime DESC");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
$count = count($result);
for ($i = 0; $i < $count; $i++) {
$mTheAvatar = $result[$i]->TheAvatar;
$mTheDirection= $result[$i]->TheDirection;
$mTheGroup = $result[$i]->TheGroup;
$mTheMedia = $result[$i]->TheMedia;
$mTheMessage = $result[$i]->TheMessage;
$mTheSenderName= $result[$i]->TheSenderName;
$mTheThumbImage = $result[$i]->TheThumbImage;
$mTheTime = $result[$i]->TheTime;
$mTheMediaExtension = $result[$i]->TheMediaExtension;
echo "hello";
echo $mTheAvatar;
echo " <- this is avatar";
}
If I do a Var_dump() I see the data being requested without a problem.
If I echo the variables , they are blank..
I have triple checked that the table column names are correct..
the $mTheAvater is a pic in table, if that gives a possible clue, but the rest are blank as well so not sure what is up?!?
You can test:
$mTheAvatar = $result[$i]['TheAvatar'];
As I know in the FETCH_ASSOC it returns data in above structure.
You are trying to read them as if they are objects, but PDOStatement::fetchAll returns an array, so your code should look like:
for ($i = 0; $i < $count; $i++) {
$mTheAvatar = $result[$i]['TheAvatar'];
$mTheDirection= $result[$i]['TheDirection'];
.
.
.
.
echo "hello";
echo $mTheAvatar;
echo " <- this is avatar";
}
If you want to handle objects, you should use PDOStatement::fetchObject
This should be better - 1) it's using foreach; 2) unset(); 3) different structure
$stmt = $db->prepare("SELECT * FROM mytable WHERE TheGroup = :SearchName ORDER BY TheTime DESC");
$stmt->bindParam(':SearchName', $request, PDO::PARAM_STR);
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
if($results){
foreach($results as $result_data) {
echo $result_data['TheAvatar'];
echo $result_data['TheDirection'];
//and so on
unset($result_data);
}
}
else{
echo 'Empty';
}

PHP PDO only fetch 1 row

I want to fetch all the rows of a table but it only echos 1 row. (The latest)
Tried much but nothing worked for me. Tried answers on stackoverflow but it is not working.
Here is the code that i use to fetch the rows:
$stmt = $pdo->prepare("SELECT * FROM admin");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
$gebruikersnaam = $row['gebruikersnaam'];
$wachtwoord = $row['wachtwoord'];
}
Hope that anyone can help me with this.
I want to fetch all the rows of a table but it only echos 1 row. (The latest)
foreach ($result as $row) {
$gebruikersnaam = $row['gebruikersnaam'];
$wachtwoord = $row['wachtwoord'];
}
I can bet 5 dollars on the assumption that you are using those variables outside the loop :) That's why you only see the last row's data. Either remove fetchAll() and fetch() them one by one or manipulate your variables within the loop so you get new values for every row.
Try this and you will know what i mean
foreach ($result as $row) {
print_r($row);
}
$stmt = $pdo->prepare("SELECT * FROM admin");
$stmt->execute();
$result = $stmt->fetchAll();
$count = $stmt->rowCount();
for ($i=0; $i < $count; $i++) {
$gebruikersnaam = $result[$i]['gebruikersnaam'];
$wachtwoord = $result[$i]['wachtwoord'];
echo 'Gebruikersnaam is : '.$gebruikersnaam.'<br/>';
echo 'Wachtwoord is : '.$wachtwoord.'<br/>';
}
Or if you want to use foreach:
$stmt = $pdo->prepare("SELECT * FROM admin");
$stmt->execute();
$result = $stmt->fetchAll();
foreach ($result as $row) {
$gebruikersnaam .= $row['gebruikersnaam'];
$wachtwoord .= $row['wachtwoord'];
}
echo 'Gebruikersnamen zijn : '.$gebruikersnaam.'<br/>';
echo 'Wachtwoorden zijn : '.$wachtwoord.'<br/>';
you have to style it al little bit because it'll stick them all together.

SELECT SUM() always returns 0 when it should be xxx amount

Needing help with SELECT SUM()... This is all my query and whenever it runs the result is always 0 any body see my problem cant seem to figure it out...
$data = $db->query("SELECT SUM(credit_amount) FROM a_creditpurchase");
$creditsbought = 0;
while($row = $data->fetch(PDO::FETCH_ASSOC)) {
$creditsbought += $row['credit_amount'];
}
echo $creditsbought;
Try this
$data = $db->query("SELECT SUM(credit_amount) as sum FROM a_creditpurchase");
$creditsbought = 0;
$row = $data->fetch(PDO::FETCH_ASSOC);
$creditsbought = $row['sum'];
echo $creditsbought;
Have you tried the SQL query with GROUP(credit_amount)?
$data = $db->query("SELECT SUM(credit_amount) FROM a_creditpurchase GROUP(credit_amount)");
this worked great keune Thanks
$data = $db->query("SELECT SUM(credit_amount) as totalAmount FROM a_creditpurchase");
while($row = $data->fetch(PDO::FETCH_ASSOC)) {
$creditsbought += $row['totalAmount'];
}

Mysql prepared statements - $mysqli->num_rows() returns 0

Here is the code that I have problem with :
function getQuestions($mysqli, $subjectIdOrCode, $isStudent){
$idSubject = getSubjectId($mysqli, $subjectIdOrCode);
//writing the statement
$query = "select id,description from questions where id_subjects = ? and
is_for_student = ?";
//prepare statement
$stmt = $mysqli->prepare($query);
//binding the statement
$stmt->bind_param("si", $idSubject, $isStudent);
//execute the statement
$stmt->execute();
//get the result
$result = $stmt->get_result();
//store the result
$stmt->store_result();
//get the number of rows
$noOfRows = $stmt->num_rows();
$questions = null;
for ($i = 0; $i < $noOfRows; $i++) {
echo "test";
$row = $result->fetch_array(MYSQLI_ASSOC);
$questions[$i]['id'] = $row['id'];
$questions[$i]['sno'] = $i+1;
$questions[$i]['description'] = $row['description'];
}
return $questions;
}
When this function is called, nothing is printed (which implies that $noOfRows is 0). Now, when the line :
//get the result
$result = $stmt->get_result();
is removed, it prints test along with some error message that $result is undefined (which clearly shows that $noOfRows is > 0).
Where have I made a mistake in my code?
Thanks in advance!
OK ... I have got your point. I have just put code to fetch num_rows
//get the number of rows
$noOfRows = $stmt->num_rows;

Pass a variable amount of parameters into a PDO statement & return JSON obj

This function takes an array of integers
$this->grades
this array varies in size depending on what the user inputs.
I can get it to work perfectly with only one number, but when I try more than one I run into the problem. Do I need to somehow concatenate the responses together before encoding them? Or is there a more efficient way to run this?
private function retrieve_standards_one(){
$dbh = $this->connect();
for($x = 0; $x < (count($this->grades)); $x++){
$stmt = $dbh->prepare("SELECT code, standard_one_id
FROM standard_one
WHERE grade_id = :grade_id
ORDER BY standard_one_id");
$stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
$stmt->execute();
$stnd = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$json = json_encode($stnd);
return $json;
}
Just use an array to store the results and encode the array
private function retrieve_standards_one(){
$dbh = $this->connect();
$data = array();
for($x = 0; $x < (count($this->grades)); $x++){
$stmt = $dbh->prepare("SELECT code, standard_one_id
FROM standard_one
WHERE grade_id = :grade_id
ORDER BY standard_one_id");
$stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
$stmt->execute();
$data[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
$json = json_encode($data);
return $json;
}
The problem is this:
$stnd = $stmt->fetchAll(PDO::FETCH_ASSOC);
Each time you go through the loop, you overwrite the contents of $stnd. So yes, in order for it to work properly, you'd need to instead append each individual result to an overall array, and then encode the array.
Here's a rewritten version of your function that both utilizes an array and also doesn't unnecessarily re-prepare the query each loop iteration:
private function retrieve_standards_one(){
$dbh = $this->connect();
$stmt = $dbh->prepare("SELECT code, standard_one_id
FROM standard_one
WHERE grade_id = :grade_id
ORDER BY standard_one_id");
$stnd = array();
for($x = 0; $x < (count($this->grades)); $x++){
$stmt->bindParam(':grade_id', $this->grades[$x], PDO::PARAM_STR);
$stmt->execute();
$stnd[] = $stmt->fetchAll(PDO::FETCH_ASSOC);
}
return json_encode($stnd);
}
Note: the $stnd = array(); line is not strictly necessarily, but it'll prevent things from crashing if $this->grades ever has 0 elements in it.
If you’re wanting to pass an array of numbers, then you can do this:
<?php
$grades = array(1,2,3,4,5);
private function retrieve_standards_one($grades)
{
// ensure only numbers get into the SQL statement
$grade_ids = array();
foreach ($grades as $grade) {
if (is_numeric($grade)) {
$grade_ids[] = $grade;
}
}
$grade_ids = implode(',', $grade_ids);
$dbh = $this->connect();
$sql = "SELECT code, standard_one_id
FROM standard_one
WHERE grade_id IN ($grade_ids)
ORDER BY standard_one_id";
$stmt = $dbh->query($sql);
$stmt->execute();
$stnd = $stmt->fetch(PDO::FETCH_ASSOC);
$json = json_encode($stnd);
return $json;
}

Categories