Why is my PHP prepared statement for MySQL not working? - php

I'm currently learning PHP and MySQL. I'm just wrote a class that handles all the MySQL traffic, but I'm encountering some errors.
function table_exists($tablename){
// check if table exists
$stmt = $this->db->prepare("SHOW TABLES LIKE '?'");
$stmt->bind_param("s", $tablename); //This is line 24.
$stmt->execute();
$ar = $stmt->affected_rows;
$stmt->close();
if ($ar > 0){
return true;
} else {
return false;
}
}
This is the code with the problem, and the error i'm getting is
Generates Warning:
mysqli_stmt::bind_param()
[mysqli-stmt.bind-param]: Number of
variables doesn't match number of
parameters in prepared statement in
C:\xampp\htdocs\mail\datahandler.php
on line 24
Ideas?
Thanks

No need to use quotes when working with prepared statements.
$stmt = $this->db->prepare("SHOW TABLES LIKE ?");
Also, instead of SHOW TABLES, you might want to use information_schema views, which give you a bit more flexibility.

You also have to use a number as first parameter for bind_param()
$stmt->bind_param(1, $tablename);
See here: http://php.net/manual/pdostatement.bindparam.php
For strings you can also just pass an array into execute().

private function table_exists($tablename){
// check if table exists
$stmt = $this->db->query("SHOW TABLES");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)){
$arr[]=$row;
}
$ar=0;
foreach($arr as $val){
foreach($val as $value){
if($value==$tablename) $ar=1;
}
}
unset($stmt);
if ($ar == 1){
return true;
} else {
return false;
}
}

Related

error on bind_param , number of parameters in prepared statement doesn't match

I know there are some questions about this, I have tried, but none of those solved my problem. so here is my problem.
I am trying to get a user's data, there are 2 parameters needed, if both of parameters are available, the code run seamlessly, but if $word parameter is not available, then I have got this warning + correct result
Warning: mysqli_stmt::bind_param(): Number of variables doesn't match number of parameters in prepared statement in
/Applications/XAMPP/xamppfiles/htdocs/Twitter/security/access.php on
line 379
{"users":[{"id":53,"username":"paulpogba","email":"twitter.gadungan#gmail.com","avatar":"","fullname":"paul
pogba"},{"id":56,"username":"waynerooney","email":"islam.idn#gmail.com","avatar":"","fullname":"wayne
rooney"}]}
the JSON result is good as i expect. but i want to omit the warning message. the problem is on the $statement-> bind_param('ss',$words,$words); i believe there are only 2 ? in the SQL syntax.
I don't know why it is said Number of variables doesn't match number of parameters in prepared statement, I can't see what went wrong in here :(
function searchUsers ($currentUser,$words) {
$query = "SELECT id,username,email,avatar,fullname FROM users WHERE NOT username= '$currentUser'";
if (!empty($words)) {
$query .= "AND (username LIKE ? OR fullname LIKE ?)";
}
$statement = $this->conn->prepare($query);
if (!$statement) {
throw new Exception($statement->error);
}
if (!empty($words)) {
$words = "%".$words."%";
}
$statement-> bind_param('ss',$words,$words);
$statement ->execute();
// result we got in execution
$result = $statement->get_result();
// each time append to $returnArray new row one by one when it is found
while ($row = $result->fetch_assoc()) {
$returnArray[] = $row;
}
return $returnArray;
}
Instead of
$statement-> bind_param('ss',$words,$words);
you need
if ($words) {
$statement-> bind_param('ss',$words,$words);
}
Explanation: You need to add those parameters if and only if $words is truey.

MySQLI Prepared Statement: num_rows & fetch_assoc

Below is some poorly written and heavily misunderstood PHP code with no error checking. To be honest, I'm struggling a little getting my head around the maze of PHP->MySQLi functions! Could someone please provide an example of how one would use prepared statements to collect results in an associative array whilst also getting a row count from $stmt? The code below is what I'm playing around with. I think the bit that's throwing me off is using $stmt values after store_result and then trying to collect an assoc array, and I'm not too sure why...
$mysqli = mysqli_connect($config['host'], $config['user'], $config['pass'], $config['db']);
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
$stmt->bind_param('i', $core['id']);
$result = $stmt->execute();
$stmt->store_result();
if ($stmt->num_rows >= "1") {
while($data = $result->fetch_assoc()){
//Loop through results here $data[]
}
}else{
echo "0 records found";
}
I feel a little cheeky just asking for code, but its a working demonstration of my circumstances that I feel I need to finally understand what's actually going on. Thanks a million!
I searched for a long time but never found documentation needed to respond correctly, but I did my research.
$stmt->get_result() replace $stmt->store_result() for this purpose.
So, If we see
$stmt_result = $stmt->get_result();
var_dump($stmt_result);
we get
object(mysqli_result)[3]
public 'current_field' => int 0
public 'field_count' => int 10
public 'lengths' => null
public 'num_rows' => int 8 #That we need!
public 'type' => int 0
Therefore I propose the following generic solution. (I include the bug report I use)
#Prepare stmt or reports errors
($stmt = $mysqli->prepare($query)) or trigger_error($mysqli->error, E_USER_ERROR);
#Execute stmt or reports errors
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
#Save data or reports errors
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
#Check if are rows in query
if ($stmt_result->num_rows>0) {
# Save in $row_data[] all columns of query
while($row_data = $stmt_result->fetch_assoc()) {
# Action to do
echo $row_data['my_db_column_name_or_ALIAS'];
}
} else {
# No data actions
echo 'No data here :(';
}
$stmt->close();
$result = $stmt->execute(); /* function returns a bool value */
reference : http://php.net/manual/en/mysqli-stmt.execute.php
so its just sufficient to write $stmt->execute(); for the query execution.
The basic idea is to follow the following sequence :
1. make a connection. (now while using sqli or PDO method you make connection and connect with database in a single step)
2. prepare the query template
3. bind the the parameters with the variable
4. (set the values for the variable if not set or if you wish to change the values) and then Execute your query.
5. Now fetch your data and do your work.
6. Close the connection.
/*STEP 1*/
$mysqli = mysqli_connect($servername,$usrname,$pswd,$dbname);
/*STEP 2*/
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
/*Prepares the SQL query, and returns a statement handle to be used for further operations on the statement.*/
//mysqli_prepare() returns a statement object(of class mysqli_stmt) or FALSE if an error occurred.
/* STEP 3*/
$stmt->bind_param('i', $core['id']);//Binds variables to a prepared statement as parameters
/* STEP 4*/
$result = $stmt->execute();//Executes a prepared Query
/* IF you wish to count the no. of rows only then you will require the following 2 lines */
$stmt->store_result();//Transfers a result set from a prepared statement
$count=$stmt->num_rows;
/*STEP 5*/
//The best way is to bind result, its easy and sleek
while($data = $stmt->fetch()) //use fetch() fetch_assoc() is not a member of mysqli_stmt class
{ //DO what you wish
//$data is an array, one can access the contents like $data['attributeName']
}
One must call mysqli_stmt_store_result() for (SELECT, SHOW, DESCRIBE, EXPLAIN), if one wants to buffer the complete result set by the client, so that the subsequent mysqli_stmt_fetch() call returns buffered data.
It is unnecessary to call mysqli_stmt_store_result() for other queries, but if you do, it will not harm or cause any notable performance in all cases.
--reference: php.net/manual/en/mysqli-stmt.store-result.php
and http://www.w3schools.com/php/php_mysql_prepared_statements.asp
One must look up the above reference who are facing issue regarding this,
My answer may not be perfect, people are welcome to improve my answer...
If you would like to collect mysqli results into an associative array in PHP you can use fetch_all() method. Of course before you try to fetch the rows, you need to get the result with get_result(). execute() does not return any useful values.
For example:
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new mysqli($config['host'], $config['user'], $config['pass'], $config['db']);
$mysqli->set_charset('utf8mb4'); // Don't forget to set the charset!
$stmt = $mysqli->prepare("SELECT * FROM licences WHERE generated = ?");
$stmt->bind_param('i', $core['id']);
$stmt->execute(); // This doesn't return any useful value
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);
if ($data) {
foreach ($data as $row) {
//Loop through results here
}
} else {
echo "0 records found";
}
I am not sure why would you need num_rows, you can always use the array itself to check if there are any rows. An empty array is false-ish in PHP.
Your problem here is that to do a fetch->assoc(), you need to get first a result set from a prepared statement using:
http://php.net/manual/en/mysqli-stmt.get-result.php
And guess what: this function only works if you are using MySQL native driver, or "mysqlnd". If you are not using it, you'll get the "Fatal error" message.
You can try this using the mysqli_stmt function get_result() which you can use to fetch an associated array. Note get_result returns an object of type mysqli_result.
$stmt->execute();
$result = $stmt->get_result(); //$result is of type mysqli_result
$num_rows = $result->num_rows; //count number of rows in the result
// the '=' in the if statement is intentional, it will return true on success or false if it fails.
if ($result_array = $result->fetch_assoc(MYSQLI_ASSOC)) {
//loop through the result_array fetching rows.
// $ rows is an array populated with all the rows with an associative array with column names as the key
for($j=0;$j<$num_rows;$j++)
$rows[$j]=$result->fetch_row();
var_dump($rows);
}
else{
echo 'Failed to retrieve rows';
}

PHP MySQLi prepared statements and fetching subset of columns

I am using MySQLi and PHP to call a stored MySQL routine with prepared statements. It returns a result set with dozens of columns.
$stmt = $dbconnection->prepare("CALL SomebodysDbProcedure(?);");
$stmt->bind_param("s", $idvalue);
$stmt->execute();
$stmt->bind_result($col1, $col2, $col3, ...);
However, I am only interested in a subset of the output columns.
The documentation says bind_result() is required to handle the complete set of returned columns:
Note that all columns must be bound after mysqli_stmt_execute() and
prior to calling mysqli_stmt_fetch().
Do I need to add code also for those columns I'm uninterested in? If so the application will break if the MySQL stored routine result set is expanded in the future, or even columns rearranged. Is there a workaround for this?
I'm assuming that you just don't want to write out all those variables for the bind_result() function. You could use a function like below instead of the bind_result() function. Pass it your $stmt object and you'll get back an array of standard objects with the fields you want.
function getResult($stmt)
{
$valid_fields = array('title', 'date_created'); // enter field names you care about
if (is_a($stmt, 'MySQLi_STMT')) {
$result = array();
$metadata = $stmt->result_metadata();
$fields = $metadata->fetch_fields();
for (; ;)
{
$pointers = array();
$row = new \stdClass();
$pointers[] = $stmt;
foreach ($fields as $field)
{
if (in_array($field->name, $valid_fields)) {
$fieldname = $field->name;
$pointers[] = &$row->$fieldname;
}
}
call_user_func_array('mysqli_stmt_bind_result', $pointers);
if (!$stmt->fetch())
break;
$result[] = $row;
}
$metadata->free();
return $result;
}
return array();
}
The answer of Jonathan Mayhak guided me in the right direction. On PHP bind_result page, nieprzeklinaj provides a function called fetch(). It works; use it like this:
$stmt = $conn->prepare("CALL SomebodysDbProcedure(?);");
$stmt->bind_param("s", $idvalue);
$stmt->execute();
$sw = (array)(fetch($stmt));
$s = $sw[0]; // Get first row
$dateCreated = $s['date_created']; // Get field date_created
Edit: Unfortunately successive calls within the same PHP file don't seem to work with this method.
Try using fetch_fields php method:
array mysqli_fetch_fields ( mysqli_result $result )
http://php.net/manual/en/mysqli-result.fetch-fields.php

dynamic mysqli prepared statement fails

I am trying to write a very small abstraction layer for my mysqli connection and have run into a problem.
Since I am maintaining older code I need to get an associative array from my query as this is the way the code has been set up and therefor less work for me once this works...
This function does work with all kinds of queries(not just select)...
my function I wrote is this:
function connectDB($query,$v=array()) {
$mysqli = new mysqli(HOST,USER,PW,DATABASE);
if($res=$mysqli->prepare($query)) {
//dynamically bind all $v
if($v) {
$values=array($v[0]);
for($i=1; $i<count($v); $i++) {
${'bind'.$i}=$v[$i];
$values[]=&${'bind'.$i};
}
call_user_func_array(array($res,'bind_param'),$values);
}
$res->execute();
//bind all table rows to result
if(strtolower(substr($query,0,6))=="select") {
$fields=array();
$meta=$res->result_metadata();
while($field=$meta->fetch_field()) {
${$field->name}=null;
$fields[$field->name]=&${$field->name};
}
call_user_func_array(array($res,"bind_result"),$fields);
//return associative array
$results = array();
$i=0;
while($res->fetch()) {
$results[$i]=array();
foreach($fields as $k => $v) $results[$i][$k] = $v;
$i++;
}
}
else {
$results=$mysqli->affected_rows;
if($mysqli->affected_rows<1) $results=$mysqli->info;
}
$res->close();
}
$mysqli->close();
return $results;
}
so if I call:
$MySqlres=connectDB("select * from `modx_events` events limit 1");
var_dump($MySqlres);
I get a nice associative array with the content of my select.
Now unfortunately the following mysql query will return NULL as a value to all of it's array keys:
$MySqlres=connectDB("select *, events.`id` as `ID`,venues.`name` as `venueName`,
venues.`suburb` as `venueSuburb`,venues.`advertiser` as `venueAdvertiser`
from `modx_events` events left join `modx_venues` venues on events.`venue`=venues.`id`
where events.`id`!='e' order by events.`start_date` asc, venues.`name` limit 1");
(the same query runs as pure SQL and will return the correct values)
Any idea what this could be? Does my associative array function fail? Is there something wrong with the way I implemented the query?
ps: PDO is not an option and mysqlnd is not installed... :(
ADDED QUESTION
is this too much of overhead just to preserve the associative array return? Should I go with $res->fetch_object() instead?
Mysqli is very poor with dynamic prepared statements, which makes small abstraction layer creation a nightmare.
I strongly suggest you to switch to PDO or get rid of prepared statements and create a regular query based on the manually handled placeholders (preferred).
As a palliative patch you can try to use get_result() function which will return a regular result variable which you can traverse usual way with fetch_assoc()
But it works only with mysqlnd builds.
Also note that creating mysqli object for the every query is a big no-no.
Create it once and then assign it in your query function using global $mysqli;
is this too much of overhead
I don't understand what overhead you're talking about
I just fixed the function.
Perhaps this is interesting for someone else:
function connectDB($mysqli,$query,$v=array()) {
if($mysqli->connect_errno) {
return array('error'=>'Connect failed: '.$mysqli->connect_error); //error handling here
exit();
}
if(substr_count($query,"?")!=strlen($v[0])) {
return array('error'=>'placeholders and replacements are not equal! placeholders:'.substr_count($query,"?").' replacements:'.strlen($v[0]).' ('.$v[0].')'); //error handling here...
exit();
}
if($res=$mysqli->prepare($query)) {
//dynamically bind all $v
if($v) {
$values=array($v[0]);
for($i=1; $i<count($v); $i++) {
${'bind'.$i}=$v[$i];
$values[]=&${'bind'.$i};
}
call_user_func_array(array($res,'bind_param'),$values);
}
$res->execute();
//bind all table rows to result
if(strtolower(substr($query,0,6))=="select") {
$field=$fields=$tempRow=array();
$meta=$res->result_metadata();
while($field=$meta->fetch_field()) {
$fieldName=$field->name;
$fields[]=&$tempRow[$fieldName];
}
$meta->free_result();
call_user_func_array(array($res,"bind_result"),$fields);
//return associative array
$results=array();
$i=0;
while($res->fetch()) {
$results[$i]=array();
foreach($tempRow as $k=>$v) $results[$i][$k] = $v;
$i++;
}
$res->free_result();
}
else { //return infos about the query
$results["affectedRows"]=$mysqli->affected_rows;
$results["info"]=$mysqli->info;
$results["insertID"]=$mysqli->insert_id;
}
$res->close();
}
return $results;
}
cheers

Is it possible to use mysqli_fetch_object with a prepared statement

All the examples I see using mysqli_fetch_object use mysql_query(), I cannot get it to work with prepared statements. Does anyone know what is wrong with this code snippet, as fetch_object returns null.
$sql = "select 1 from dual";
printf("preparing %s\n", $sql);
$stmt = $link->prepare($sql);
printf("prepare statement %s\n", is_null($stmt) ? "is null" : "created");
$rc = $stmt->execute();
printf("num rows is %d\n", $stmt->num_rows);
$result = $stmt->result_metadata();
printf("result_metadata %s\n", is_null($result) ? "is null" : "exists");
$rc = $result->fetch_object();
printf("fetch object returns %s\n", is_null($rc) ? "NULL" : $rc);
$stmt->close();
The output is:
preparing select 1 from dual
prepare statement created
num rows is 0
result_metadata exists
fetch object returns NULL
This is the code I use to create an object from a prepared statement.
It could perhaps be used in a subclass of mysqli?
$query = "SELECT * FROM category WHERE id = ?";
$stmt = $this->_db->prepare($query);
$value = 1;
$stmt->bind_param("i", $value);
$stmt->execute();
// bind results to named array
$meta = $stmt->result_metadata();
$fields = $meta->fetch_fields();
foreach($fields as $field) {
$result[$field->name] = "";
$resultArray[$field->name] = &$result[$field->name];
}
call_user_func_array(array($stmt, 'bind_result'), $resultArray);
// create object of results and array of objects
while($stmt->fetch()) {
$resultObject = new stdClass();
foreach ($resultArray as $key => $value) {
$resultObject->$key = $value;
}
$rows[] = $resultObject;
}
$stmt->close();
MySql Native Driver extension (mysqlnd), has the get_result method:
$stmt->execute();
$obj = $stmt->get_result()->fetch_object();
I don't believe the interface works like that.
Going by the documentation and examples (http://www.php.net/manual/en/mysqli.prepare.php) it seems that $stmt->execute() does not return a resultset, but a boolean indicating success / failure (http://www.php.net/manual/en/mysqli-stmt.execute.php). To actually get the result, you need to bind variables to the resultset (aftere the execute call) using $stmt->bind_result (http://www.php.net/manual/en/mysqli-stmt.bind-result.php).
After you did all that, you can do repeated calls to $stmt->fetch() () to fill the bound variables with the column values from the current row. I don't see any mention of $stmt->fetch_object() nor do I see how that interface could work with a variable binding scheme like described.
So this is the story for "normal" result fetching from mysqli prepared statments.
In your code, there is something that I suspect is an error, or at least I am not sure you intended to do this.
You line:
$result = $stmt->result_metadata();
assignes the resultset metadata, which is itself represented as a resultset, to the $result variable. According to the doc (http://www.php.net/manual/en/mysqli-stmt.result-metadata.php) you can only use a subset of the methods on these 'special' kinds of resultsets, and fetch_object() is not one of them (at least it is not explicitly listed).
Perhaps it is a bug that fetch_object() is not implemented for these metadata resultsets, perhaps you should file a bug at bugs.mysql.com about that.

Categories