Dynamically Bind Params in Prepared Statements with MySQLi - php

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%?

Related

Turning a query result to an associative array

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

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;

MySQLi creating random string, but checking it doesn't already exist

Below is my code that i have written to create a random string. Works well. It also checks to make sure that the generated string doesn't already exist, and if it does, then it makes another one. HOWEVER i haven't yet worked out a way to make the code generated if one already exists be checked to see if that one exists. Would i be best doing an elseif statement?
PHP
<?PHP
require_once('dbConfig.php');
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 12; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
//$generatedId = "SPI-E7HN2SBIIF5W";
$generatedId = 'SPI-'.$randomString;
//Prepare select query
$statement = $db->prepare("SELECT client_unique_id FROM clients WHERE client_unique_id = ? LIMIT 1");
//Determine variable and then bind that variable to a parameter for the select query ?
$id = $generatedId;
$statement->bind_param('s', $id);
//Execute and store result so that num_rows returns a value and not a 0
$statement->execute();
$statement->store_result();
//Bind result to a variable for easy management afterwards
$statement->bind_result($clientId);
// Generate a random ID for the user if the previously generated one already exists
if($statement->num_rows > 0){
$randomstring = '';
$characters = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ';
for ($i = 0; $i < 0; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$generatedId = 'SPI-'.$randomString;
echo $generatedId;
} else {
// If there's no issue with what's been created, echo it out :)
echo $generatedId;
}
?>
Any help is appreciated :)
try this.
// initialize a variable to hold the last generated id,
$generatedId = '';
// and another to hold the returned client_unique_id,
$clientId = '';
setup your prepared statement
bind the parameter,
$statement->bind_param('s', $id)
do
{
generate a new Id. (Code for generating random id goes here).
$generatedId = '...';
// bind the generated id to the prepared statement.
$id = $generatedId
// execute the prepared statement,
$statement->execute()
// fetch the results into $clientId
$statement->bind_result($res);
while($statement->fetch()) {
$clientId = $res;
}
} while ($clientId != '');
$statement->close();
// echo the last generated Id
echo $generatedId;
cheers,
William

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