Turning a query result to an associative array - php

In my php I am running a simple query which returns a resultset(0 or many) from the database I have.
Currently on the fronted the rersult looks like this :
name: Smoothie description: Banana Smothie name: Phad Thai description: Noodles with shrimps name: Noodles description: Noodles with noodles.
The string can also look like this, aka name: Smoothie description: Banana Smothie or with more entries, like in the example above.
What I am aiming to have is an associative array from my result, which I can turn into json string and pass it to the frontend.
Unfortunately what i tried so far didn't work.
This is my php :
<?php
include_once 'db/dbconnect.php';
$input = json_decode(stripcslashes($_POST['data']));
for ($i=0; $i < count($input); $i++) {
$stmt=$con->prepare("SELECT recipes.recipeName, recipes.recipeDescription FROM ingredients, recipes, recipesingredients WHERE recipes.recipeId = recipesingredients.recipeIdFK AND recipesingredients.ingredientIdFK = ingredients.IngredientId AND ingredients.ingredientName = ?");
$stmt->bind_param("s", $input[$i]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($db_recipe_name, $db_recipe_description);
while ($stmt->fetch()) {
echo "name: ".$db_recipe_name." description: ".$db_recipe_description." ";
}
}
?>
Can someone help me make the result from the query to an associative array with the current code i have?

Just add each one to an array. Also, use modern JOIN syntax:
<?php
include_once 'db/dbconnect.php';
$input = json_decode(stripcslashes($_POST['data']));
for ($i=0; $i < count($input); $i++) {
$stmt=$con->prepare("SELECT recipes.recipeName,
recipes.recipeDescription
FROM ingredients i
JOIN recipesingredients ri
ON ri.ingredientIdFK = i.IngredientId
JOIN recipes r
ON r.recipeId = ri.recipeIdFK
WHERE i.ingredientName = ?");
$stmt->bind_param("s", $input[$i]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($db_recipe_name, $db_recipe_description);
$rslt = array();
$rowno = 0;
while ($stmt->fetch()) {
$rslt[$rowno] = array('name' => $db_recipe_name, 'description' => $db_recipe_description);
$rowno++;
echo "name: ".$db_recipe_name." description: ".$db_recipe_description." ";
}
$jsonRslt = json_encode($rslt);
echo "<p>JSON Results:<pre>".$jsonRslt."</pre></p>\n";
$stmt->close();
}

You can use fetch_assoc method and save it into an array. Like
// In the beginning of your code initialize an ampty array
$result = array();
// Have your query here.
while($row = $stmt->fetch_assoc()) {
$result[] = $row;
}
$stmt->close();
echo json_encode($result);

Just call fetchAll(PDO::FETCH_ASSOC) on $stmt. It returns a associative array of all results. No need to use a while loop.
http://php.net/manual/en/pdostatement.fetchall.php#refsect1-pdostatement.fetchall-examples
include_once 'db/dbconnect.php';
$input = json_decode(stripcslashes($_POST['data']));
$stmt = $con->prepare("SELECT recipes.recipeName, recipes.recipeDescription FROM ingredients, recipes, recipesingredients WHERE recipes.recipeId = recipesingredients.recipeIdFK AND recipesingredients.ingredientIdFK = ingredients.IngredientId AND ingredients.ingredientName = ?");
for ($i=0; $i < count($input); $i++) {
$stmt->bind_param("s", $input[$i]);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
}

Related

PHP Array to string conversion

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;

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';
}

Dynamically Bind Params in Prepared Statements with MySQLi

So like the title says, i've search here and tried almost everything, with no success.
I've try to test something very simple before going more deep, to make sure it works. But even at its simplest, i always get 0 results and i know there are 67 results.
What's wrong with my code?
Thanks
$conn = connect(); // connect to the db
$a_bind_params = array('love', 'circle');
$a_param_type = array('s', 's');
$totalKeywords = count($a_bind_params);
$q = 'SELECT id, name
FROM album
WHERE name LIKE ?';
for ($i = 1; $i < $totalKeywords; $i++) {
$q .= ' AND name LIKE ?';
}
echo $q; // for testing purposes: verify that query is OK
// bind parameters.
$param_type = '';
$n = count($a_param_type);
for($i = 0; $i < $n; $i++) {
$param_type .= $a_param_type[$i];
}
/* with call_user_func_array, array params must be passed by reference */
$a_params = array();
$a_params[] = & $param_type;
for($i = 0; $i < $n; $i++) {
/* with call_user_func_array, array params must be passed by reference */
$a_params[] = & $a_bind_params[$i];
}
$stmt = $conn->prepare($q);
/* use call_user_func_array, as $stmt->bind_param('s', $param); does not accept params array */
call_user_func_array(array($stmt, 'bind_param'), $a_params);
$stmt->execute();
$stmt->store_result();
$num_rows = $stmt->num_rows;
echo $num_rows; // how many found ?
$stmt->bind_result($id, $name);
while($stmt->fetch()) {
echo $name;
}
$stmt->free_result();
$stmt->close();
$conn->close();
There are not 67 rows with query
SELECT id, name
FROM album
WHERE name LIKE 'love' AND name LIKE 'circle'
There should be OR instead of AND in WHERE clause.
Possibly, you may also need %love% and %circle%?

Mysqli with unknown bind_results

Ok, I thought I had this, but I can't see why it's not working...
I have a SELECT with a variable table, hence my columns (bind_result) is going to be variable.
I need to adjust for any number of columns coming back, and fetch as an associated array, since there will be multiple rows coming back:
// Get table data
$mysqli = new mysqli('host','login','passwd','db');
if ($mysqli->connect_errno()) { $errors .= "<br>Cannot connect: ".$mysqli->connect_error()); }
$stmt = $mysqli->prepare("SELECT * FROM ?");
$stmt->bind_param('s', $table);
$stmt->execute();
// Get bind result columns
$fields = array();
// Loop through columns, build bind results
for ($i=0; $i < count($columns); $i++) {
$fields[$i] = ${'col'.$i};
}
// Bind Results
call_user_func_array(array($stmt,'bind_result'),$fields);
// Fetch Results
$i = 0;
while ($stmt->fetch()) {
$results[$i] = array();
foreach($fields as $k => $v)
$results[$i][$k] = $v;
$i++;
}
// close statement
$stmt->close();
Any thoughts are greatly appreciated ^_^
EDIT: New code:
$mysqli = new mysqli('host','login','passwd','db');
if ($mysqli->connect_errno)) { $errors .= "<br>Cannot connect: ".$mysqli->connect_error()); }
$stmt = "SELECT * FROM ".$table;
if ($query = $mysqli->query($stmt)) {
$results = array();
while ($result = $query->fetch_assoc()) {
$results[] = $result;
}
$query->free();
}
$mysqli->close();
You can not bind the table name. Bind_param accept the column name and its datatype.
To use the table name dynamically use the below code:
$stmt = $mysqli->prepare("SELECT * FROM ".$table);

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