I know they're many, many questions already about this, but I have no idea why mine doesn't work.
If I just use the following, my code works fine:
$this->stmt->bind_param("ii", $params[0], $params[1]);
But if I use the call_user_func_array, it breaks. One suggestion I got was passing the $parameters array by reference, but adding an & before the variable also broke my code...
Any help is greatly recieved!
Here's my code:
DB class:
function selectQuery($sql, $paramTypes = false, $params = false) {
//Prepare statement
$this->stmt = $this->conn->prepare($sql);
if($this->stmt === false) {
//We have an error
echo 'Wrong SQL: ' . $sql . ' Error: ' . $this->conn->error;
}
//This part doesn't work...
// if ($params) {
// //Bind an unknown number of parameters
// $parameters = array_merge(array($paramTypes), $params);
// call_user_func_array(array($this->stmt, 'bind_param'), $parameters);
// }
//This works.
$this->stmt->bind_param("ii", $params[0], $params[1]);
//Execute statement
$this->stmt->execute();
if ($this->stmt->error) {
echo $this->stmt->error;
return false;
}
//Get the results
$result = $this->stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
//Close statement
$this->stmt->close();
//Return the results
return $data;
}
Test page:
<?php
require_once('DatabaseAccess.php');
$db = new DB();
$sql = "SELECT * FROM table WHERE id = ? OR id = ?";
echo "Fetching data....<br>";
$result = $db->selectQuery($sql, "ii", array(1, 2));
foreach($result as $r) {
echo "<pre>".print_r($r, 1)."</pre>";
}
?>
Decided to add more information:
I'll be using this function to pass in the parameter types and parameters, but the amount will vary. When I looked up how to do this everyone suggested the call_user_func thing, but each time I try it (tried a few different ways) it won't work. Read through many threads, but it never seems to work. If I just use the bind_params function directly it works and I get the correct data returned.
Using the call_user_func thing I was getting the no data for the ? mysqli error, which is when I tried passing by reference and the code just broke completely...
Put it before call_user_func_array()
$res = array();
foreach($parameters as $key => $value) {
$res[$key] = &$parameters[$key];
}
Related
I have a very simple query that works when I don't use parameters. With parameters, it returns nothing. Someone else posted the same issue over here:
Query with input parameters doesn't work whereas direct query works
However no one has answered it. Below is my code.
require_once('database.class.php');
class Plan extends Database {
public function getBenefitAmounts($plan_id, $group_id, $level) {
$sql = 'SELECT DISTINCT benefit FROM rates WHERE plan_id = :plan AND group_id IS NULL AND `level` = :lvl';
$params = array(':plan'=>896, ':lvl'=>1);
$this->sqlQuery($sql, $params);
// $sql = 'SELECT DISTINCT benefit FROM rates WHERE plan_id = 896 AND group_id IS NULL AND `level` = 1';
// $this->sqlQuery($sql);
$results = $this->sth->fetchAll(PDO::FETCH_COLUMN);
$options = '';
foreach ($results as $value) {
$options .= '<option value="' . $value . '">$' . $value . '</option>';
}
return $options;
}
}
In the database class:
public function sqlQuery($sql, $values_to_bind=null) {
$this->sth = $this->pdo->prepare($sql);
if (isset($values_to_bind)) {
foreach ($values_to_bind as $param => $value) {
$this->sth->bindValue($param, $value);
}
}
$success = $this->sth->execute();
if (!$success) {
$arr = $this->$sth->errorInfo();
print_r($arr);
}
}
The code commented out of the first code snippet works just fine, but with parameters, it returns nothing. The getBenefitAmounts function is called from another PHP file which is called using a JQuery get.
Did you try to add the third param which is optional for bindValue(). It can be something like PDO::PARAM_INT, PDO::PARAM_STR etc. Just try to debug and see if it helps.
I don't know why do you like so much try...catch if you use with no sense code. Because this technique: } catch (PDOException $e) { throw new PDOException($e);} means the same as } catch (PDOException $e) {;} like you ask php to do nothing if catch. Why do you asked to catch if you do nothing in case it happens?
Now my guess about how to fix your code:
public function sqlQuery($sql, $values_to_bind=null) {
$this->sth = $this->pdo->prepare($sql);
if (isset($values_to_bind)) {
foreach ($values_to_bind as $param => $value) {
$this->sth->bindValue($param, $value);
}
}
$success = $this->sth->execute();
if (!$success) {
$arr = $this->$sth->errorInfo();
print_r($arr);
}
}
By the way you use $this->sth = $this->pdo->prepare($sql); that means your sqlQuery function is a method of some class that you didn't show to us. and your first piece of code is somewhere outside that class? it would be better if you post full version of code, not just lines you think are involved.
and here you can switch to regular way:
//$results = $this->sth->fetchAll(PDO::FETCH_COLUMN); //you don't need it
$options = '';
while ($row = $this->sth->fetch(PDO::FETCH_ASSOC)) {
$options .= '<option value="' . $row['benefit'] . '">$' . $row['benefit'] . '</option>';
}
Why not bind the parameters using bindParam?
$plan = 896;
$lvl = 1;
$sth = $dbh->prepare("SELECT DISTINCT benefit FROM rates WHERE plan_id = :plan AND group_id IS NULL AND `level` = :lvl");
$sth->bindParam(":plan", $plan);
$sth->bindParam(":lvl", $lvl);
$sth->execute();
$r = $sth->fetchAll();
I have developed a simple REST API using PHP Slim and implemented a simple function which will return a list of track upon matching the album name passed thought REST call.
This is my index.php file for making those rest calls,
http://localhost/my_gallery/v1/tracks/:name
$app->get('/tracks/:name', 'authenticate', function($album_keyword) {
global $user_id;
$response = array();
$db = new DbHandler();
// fetch task
$result = $db->getTracksByName($album_keyword);
if ($result != NULL) {
$response["error"] = false;
$response["album_name"] = $result["album_name"];
$response["track_artist"] = $result["track_artist"];
$response["track_name"] = $result["track_name"];
echoRespnse(200, $response);
} else {
$response["error"] = true;
$response["message"] = "The requested resource doesn't exists";
echoRespnse(404, $response);
}
});
This is the getTracksByName() function for returning a list a tracks after matching the album name,
public function getTracksByName($album_keyword) {
$stmt = $this->conn->prepare(
"SELECT `album`.album_name, `track`.track_artist, `track`.track_name "
. "FROM `category_album` ,`album` , `track` "
. "where `album`.album_id=`track`.album_id AND`album`.`album_name` LIKE ?");
$stmt->bind_param("i", $album_keyword);
if ($stmt->execute()) {
$res = array();
$stmt->bind_result($album_name, $track_artist, $track_name);
$stmt->fetch();
$res["album_name"] = $album_name;
$res["track_artist"] = $track_artist;
$res["track_name"] = $track_name;
$stmt->close();
return $res;
} else {
return NULL;
}
}
Now after making the REST call its returns null values for each track items. Just to mention I've change the SQL query from
... ANDalbum.album_name LIKE ?
to
... ANDalbum.album_id LIKE ?
and its works but for some reason itsn't working with the following query
... ANDalbum.album_name LIKE ?
I'm absolutely new to PHP and any kind of help would be greatly appreciated.
$stmt->bind_param("i", $album_keyword); binds a parameter of type INTEGER. Change to $stmt->bind_param("s", $album_keyword); to bind a parameter of type STRING.
http://php.net/manual/en/mysqli-stmt.bind-param.php
There is two potential issues in your prepared statement code.
First off, you are telling the statement that the parameter is a int:
$stmt->bind_param("i", $album_keyword);
The i indicates Integer. While you want a string (s).
Second issue is that when using LIKE in a prepared statement, you still need the % signs used in a standard LIKE.
For example:
$stmt->bind_param("s", "%$album_keyword%");
Okay, I've never ever used dynamic functions, not sure why, I've never liked using explode(), implode(), etc.
but I've tried it out, and something went wrong.
public function fetch($table, array $criteria = null)
{
// The query base
$query = "SELECT * FROM $table";
// Start checking
if ($criteria) {
$query .= ' WHERE ' . implode(' AND ', array_map(function($column) {
return "$column = ?";
}, array_keys($criteria)));
}
$check = $this->pdo->prepare($query) or die('An error has occurred with the following message:' . $query);
$check->execute(array_values($criteria));
$fetch = $check->fetch(PDO::FETCH_ASSOC);
return $fetch;
}
This is my query.
Basically I will return the variable $fetch which holds the fetch method.
and then somewhere, where I want to use the while loop to fetch data, I will use that:
$r = new Database();
while ($row = $r->fetch("argonite_servers", array("server_map" => "Wilderness")))
{
echo $row['server_map'];
}
Now, I am not getting any errors, but the browser is loading and loading forever, and eventually will get stuck due to lack of memory.
That's because the loop is running and running without stopping.
Why is it doing this? How can I get this dynamic query to work?
EDIT:
$r = new Database();
$q = $r->fetch("argonite_servers", array("server_map" => "Wilderness"));
while ($row = $q->fetch(PDO::FETCH_ASSOC))
{
echo $row['server_map'];
}
One nice feature of PDO is that the PDOStatement implements the Traversable. This means you can iterate it directly:
// `$check` is a `PDOStatement` object
$check = $this->pdo->prepare($query) or die('An error has occurred with the following message:' . $query);
$check->execute(array_values($criteria));
$check->setFetchMode(PDO::FETCH_ASSOC);
return $check;
Use it:
$statement = $r->fetch("argonite_servers", array("server_map" => "Wilderness"));
foreach ($statement as $row) {
}
this is because you call your fetch function in a loop and it re-starts the query every time. You need to call the $check->fetch() in loop instead.
or in other words, if your fetch function (which should probably have a different name) would return $check, then on the returned object you should call fetch() in a loop:
$r = new Database();
$q = $r->fetch(...);
while($q->fetch()){...}
you also need to edit your fetch function to end like this:
$check->execute(array_values($criteria));
return $check;
}
I have created a class to handle all database operations for my application. So far I have gathered and displayed the data in foreach statements within my view. What I wish to be able to do is get and set individual elements from a function from my database class.
Here is my database function for displaying data within a foreach:
public function test($sql, $type, $param)
{
$variables = array();
$results = array();
// Mysqli
if($stmt = $this->AC->Mysqli->prepare($sql))
{
$params = array_merge($type, $param);
call_user_func_array(array($stmt, 'bind_param'), $this->make_values_referenced($params));
$stmt->execute();
$stmt->store_result();
// Existance
if($stmt->num_rows > 0)
{
$meta = $stmt->result_metadata();
while($field = $meta->fetch_field())
{
$parameters[] = &$row[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $parameters);
while($stmt->fetch())
{
$elemet = array();
foreach($row as $key => $val)
{
$element[$key] = $val;
}
$results[] = $element;
}
return $results;
}
else
{
$results = FALSE;
return $results;
}
}
else
{
die("ERROR: We could not connect.");
}
}
The function below is called from my model:
public function profile_information($account_name)
{
// Mysqli Variables
$sql = "SELECT $this->account_details.bio
FROM account_details
WHERE $this->account_details.account_name = ? LIMIT 10";
$type = array("s");
$param = array($account_name);
$results = $this->AC->Database->prepared_select_loop($sql, $type, $param);
$this->AC->Template->set_data('profile_information', $results, FALSE);
}
Once set within my model, I call the function within my controller and access it within my view with a foreach for displaying data:
$profile_information = $this->get_data('profile_information');
foreach ($profile_information as $row) :
//Displaying data here
endforeach;
The above works fine for displaying a large amount of data, but what I'm wanting to do is call the a database function that will allow me set individual data elements. Therefore not having to use a foreach if im only getting a limited amount of data (i.e. one row of Name, age, address)
A non dynamic way I have tackled this problem is to write the database for every function that only desires one row from the database:
function name($variable)
{
$sql = 'statement here';
$stmt = $this->AC->Mysqli->prepare($sql);
$stmt->bind_param("i", $id);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result(bind results);
$stmt->fetch();
$this->AC->Template->set_data('id', $id);
$this->AC->Template->set_data('account_name', $account_name);
}
So in basically I want to make the above statement refactored into my database class and thus making it more dynamic.
I dont know how I would be able to tackle this problem, I don't want to use PDO, as I wish to find a solution within Mysqli. Any help would be appreciated.
Would you recommend just switching over to PDO?
Definitely.
Whole your function test() could be rewritten into three lines (assuming $param contains an array with parameters for the prepared statement):
public function test($sql, $param)
{
$stmt = $this->AC->pdo->prepare($sql);
$stmt->execute($param);
return $stmt->fetchAll();
}
I've got a database query function that works well -- except that I'm running into what's apparently a known issue with mysqli prepared statements and longtext fields. What happens is that the longtext field always comes up empty even though running the query through phpMyAdmin works fine. According to http://www.workinginboxershorts.com/php-mysqli-returns-empty-variables-from-longtext-column, switching the datatype to text solves the problem. However, in my case I'd really prefer to leave the field as longtext as I can foresee times when that extra space would be valuable.
I'm using parameterized queries, which evidently is the problem. Here's my function:
// Bind results to an array
// $stmt = sql query, $out = array to be returned
function stmt_bind_assoc (&$stmt, &$out) {
$data = mysqli_stmt_result_metadata($stmt);
$fields = array();
$out = array();
$fields[0] = $stmt;
$count = 1;
while($field = mysqli_fetch_field($data)) {
$fields[$count] = &$out[$field->name];
$count++;
}
call_user_func_array('mysqli_stmt_bind_result', $fields);
}
// DB Query
// $query = SQL query, $params = array of parameters, $rs = whether or not a resultset is expected, $newid = whether or not to retrieve the new ID value;
// $onedimensionkey = key required to convert array into simple one dimensional array
function db_query($query, $params, $rs = true, $newid = false, $onedimensionkey = false) {
$link = mysqli_connect(DB_SERVER, DB_USER, DB_PASS, DB_NAME);
if (!$link) {
print 'Error connecting to MySQL Server. Errorcode: ' . mysqli_connect_error();
exit;
}
// Prepare the query and split the parameters array into bound values
if ($sql_stmt = mysqli_prepare($link, $query)) {
if ($params) {
$types = '';
$new_params = array();
$params_ref = array();
// Split the params array into types string and parameters sub-array
foreach ($params as $param) {
$types .= $param['type'];
$new_params[] = $param['value'];
}
// Cycle the new parameters array to make it an array by reference
foreach ($new_params as $key => $parameter) {
$params_ref[] = &$new_params[$key];
}
call_user_func_array('mysqli_stmt_bind_param', array_merge(array($sql_stmt, $types), $params_ref));
}
}
else {
print 'Error: ' . mysqli_error($link);
exit();
}
// Execute the query
mysqli_stmt_execute($sql_stmt);
// If there are results to retrive, do so
if ($rs) {
$results = array();
$rows = array();
$row = array();
stmt_bind_assoc($sql_stmt, $results);
while (mysqli_stmt_fetch($sql_stmt)) {
foreach ($results as $key => $value) {
$row[$key] = $value;
}
$rows[] = $row;
}
if ($onedimensionkey) {
$i = 0;
foreach ($rows as $row) {
$simplearray[$i] = $row[$onedimensionkey];
$i++;
}
return $simplearray;
}
else {
return $rows;
}
}
// If there are no results but we need the new ID, return it
elseif ($newid) {
return mysqli_insert_id($link);
}
// Close objects
mysqli_stmt_close($sql_stmt);
mysqli_close($link);
}
According to the link that I posted there is a workaround involving the order in which things are done, but either I'm handling my query in a completely different manner than the example or I'm simply not understanding something important.
Thanks to anyone who can help!
EDIT: Thanks to Corina's answer, I've solved this -- for anyone else who runs into the problem, you will simply need to add the following after the mysql_stmt_execute command:
// Execute the query
mysqli_stmt_execute($sql_stmt);
// Store results
mysqli_stmt_store_result($sql_stmt);
I managed to solve the same issue by calling mysqli_stmt_store_result before binding the data.
Someone had the same problem and shared the answer on the php.net website:
Apparently, if you have longtext present, you HAVE to call
store_result before using bind_result.
http://bugs.php.net/bug.php?id=47928