This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 2 months ago.
I've been stuck on this error , please help me this is my code
PHP Fatal error: Call to a member function bind_param()
$statement= $db->prepare("insert into uploaddetails(idnum,title,desc,author,tags,title) values(?,?,?,?,?,?)");
$id='NULL';
$title=$_POST['title'];
$description=$_POST['description'];
$author=$_POST['author'];
$tags=$_POST['tags'];
$file= basename($_FILES["fileToUpload"]["name"]);
$statement->bind_param( 'isssss', $id,$title, $description,$author,$tags,$file);
$statement->execute();
$db->close();
$statement->close();
Since nobody else has spotted the issue, I'll post it for you. The reason you're prepare() is failing is because you're trying to use a MySQL Reserved Word. The word desc is a reserved word in MYSQL, which means you need to wrap it in backticks like this:
$statement= $db->prepare("insert into uploaddetails(idnum,title,`desc`,author,tags,file) values(?,?,?,?,?,?)");
It also helps to use proper practice when inserting into a database/using prepared statements.
$statement= $db->prepare("insert into uploaddetails(idnum,title,`desc`,author,tags,title) values(?,?,?,?,?,?)");
if($statement !== FALSE) {
// do the binds...etc
}
Notes
file is also a reserved word, I don't know what your actual file columns name is, so keep that in mind.
Your prepare statement is failing because of the query, what you need to do is to make sure the statement is not false in order to execute bind_param, otherwise view the prepare query error as follows :
//Make sure the statement is not false
if($statement !== FALSE)
{
$statement->bind_param( 'isssss', $id,$title, $description,$author,$tags,$file);
$statement->execute();
$db->close();
$statement->close();
}
//Otherwise check why the prepare statement failed
else
{
die('prepare() failed: ' . htmlspecialchars($db->error));
}
Try this. your code is modified.
$statement= $db->prepare("INSERT INTO uploaddetails (title,desc,author,tags,file) VALUES(?,?,?,?,?)");
//$id='NULL';
$title=$_POST['title'];
$description=$_POST['description'];
$author=$_POST['author'];
$tags=$_POST['tags'];
$file= $_FILES["fileToUpload"]["name"];
$statement->bind_param( 'isssss',$title, $description,$author,$tags,$file);
$statement->execute();
$db->close();
$statement->close();
//---- Move the file to desired location...
-ID is not required because it is auto increment and mysql will take care of it,
-and you had wrong field name for file, which was title and I change it to file(correct it if you have any other name instead).
possible errors
1)column count in the table is different from your query.
2)although it shows the error in the bind_param line, the error may occur in the prepare statement line(in your case line 1)
3)you can put echo statement before and after these lines and caught the error
(in my case I repeated the same field name twice in the prepared statement)
fetch following code with your requirements and tryout
$stmt = $conn->prepare("INSERT INTO SalesReturn(CRDNUMBER, CRDDATE, REFERENCE,CUSTOMER,ITEM,QTYRETURN,UNITPRICE,TIAMOUNT1,TIAMOUNT2,EXTCRDMISC,TAMOUNT1,TAMOUNT2,CRDSUBTOT,CRDNET,CRDETAXTOT,CRDNETNOTX,CRDNETWTX,TransactionType) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)");
echo "after prepare";
$stmt->bind_param("ssssssssssssssssss",$CRDNUMBER,$CRDDATE,$REFERENCE,$CUSTOMER,$ITEM,$QTYRETURN,$UNITPRICE,$TIAMOUNT1,$TIAMOUNT2,$EXTCRDMISC,$TAMOUNT1,$TAMOUNT2,$CRDSUBTOT,$CRDNET,$CRDETAXTOT,$CRDNETNOTX,$CRDNETWTX,$TransactionType);
echo "after bind_param statement";
Related
I got an error when I prepare my $query.
Here are the lines :
$query="INSERT INTO bm(title,season) VALUES(:title, :season)";
$stmt = $mysqli->prepare($query);
//$stmt->bind_param("ss", $title, $season);
$stmt->execute(array(':title' => $title, ':season' => $season));
I put the line with bind_param in //
I saw on others that could solve but error became roughly the same :
Fatal error: Call to a member function bind_param() on a non-object
So, I thought of my query but it's so simple I can't see anymore clearly. It's driving me nuts. :-/ I also tested the var $titleand $season with an echo just before the $query line to be sure, like this :
echo $title." et ".$season;
but nothing is wrong, values are ok. These are strings var. Any help would be very appreciated. Thanks.
Here is the complete code :
<?php
include("connexion.php");
// Get vars from previous form
//$id="";
$title = isset($_POST['title']) ? $_POST['title'] : "";
$season = isset($_POST['season']) ? $_POST['season'] : "";
// Testing vars
if (empty($titre) && empty($saison))
{
echo '<font color="red">Must be filled...</font>';
}
// Vars ok : could be inserted in "bm" table
else
{
// Protect - inject SQL
$title=$mysqli->real_escape_string(strip_tags($title));
$season=$mysqli->real_escape_string(strip_tags($season));
// Test
echo $title." et ".$season;
// Insert method
$query="INSERT INTO bm(title,season) VALUES(:title, :season)";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("ss", $title, $season);
$stmt->execute(array(':title' => $title, ':season' => $season));
// Insert ok ?
if ($stmt) {
echo "Insert ok.";
}
else {
echo "Insert failed !";
}
}
//Close connexion
$mysqli->close();
?>
Try to change your database call as follows:
$query="INSERT INTO bm(title,season) VALUES(?, ?)";
$stmt = $mysqli->prepare($query);
//could be false if prepared statemant is somehow wrong
if ($stmt === false){
echo "Insert failed !";
}
else{
//bind the params to the variables
$stmt->bind_param("ss", $title, $season);
//no parameters allowed for execute method according to the doc
$success = $stmt->execute();
//check for $success if true/false
}
Why not use the most common used queing to fetch data from the database? The most commonly used is by using while loop for fetching data from the database right? I think that your approach(based on your code) perfectly works if you are using sqlsrv, but mysql and mysqli has almost the same syntax unlike from sqlsrv wherein it uses params to pass data, just my opinion :D
If you reference the documentation on PHP MYSQLI (http://php.net/manual/en/mysqli.prepare.php) you will notice that FALSE is returned when an error occurs in the prepare.
mysqli_prepare() returns a statement object or FALSE if an error occurred.
Instead of the call being from a mysqli_stmt object, it is from a FALSE boolean.
My assumption would be that the error occurs in your connection string if you are passing in proper variables. More code would be needed to troubleshoot further.
I've been trying to get prepared statements working - however, I keep running into the following error
<b>Fatal error</b>: Call to a member function bindParam() on a non-object on line <b>41</b><br />
I have copied exactly many tutorials and even the provided code did not work and threw the same error.
My code is below:
$mysqli = new mysqli(connect, username,pass, datatbase);
$name = 'Tester';
if (mysqli_connect_errno()) {
echo "Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error();
}
$stmt = $mysqli->prepare("INSERT INTO Parks VALUES (null,?,?,?,?,?,?,?,?,?,?,?,?,?,Now(),?,?,?, 0, 0, 0)");
if ($stmt === FALSE) {
die ("Mysql Error: " . $mysqli->error);
}
$stmt->bind_param('ssssssssssssssss', $name, $theme, $size, $mountains, $hills, $river, $lake, $island, $setofislands, $ocean, $waterfalls, $file, $image, $description, $author,$cs);
$stmt->execute();
$stmt->close();
$mysqli->close();
It's the BindParam Line causing the error.
thanks in advance :)
EDIT: Error resolved, however, no data is being inserted into the database.
EDIT: Updated query, database contains VARCHARs except for Description which is LONGTEXT. The final 3 are ints/doubles and there is a current date field.
bindParam is the PDO function. You are using mysqli so try bind_param instead. Where you have 'name' should also be the type definition, so you need 's' for string.
E.g:
$stmt->bind_param('s', $name);
Edit: Although saying that, the error doesn't say the function is incorrect. It says the object doesn't exist... Running this could would give you information as to why the prepare is failing.
$stmt = $mysqli->prepare("INSERT INTO 'Parks' VALUES(null, ?");
if ($stmt === FALSE) {
die ("Mysql Error: " . $mysqli->error);
}
Most likely the prepare is failing as the SQL is incorrect (My guess is the table name 'Parks' should NOT be in qutoes)
Edit 2: My guess for it still not working is:
$stmt->bindParam('name', $name);
Where you have 'name' should actually be the variable type, as in integer, double, string, etc. This is so the database knows what your variable is.
Try replacing that line with:
$stmt->bindParam('s', $name);
This question already has an answer here:
PHP mysqli prepare statement not working
(1 answer)
Closed 1 year ago.
I simply want to select a bunch of fields from a data base - as I have done it a lot of times before... But somehow I get this error:
Warning: mysqli_stmt_bind_result(): Number of bind variables doesn't match number of fields in prepared statement
But I count exactly 14 columns, so why when I add 14 variables does it throw this error?
public function get_invitation_fields()
{
$this->fields_db = array();
include('system/mysqli_db.php'); //db connection opens here
$statement="SELECT
invitation_ID,
recipient,
text,
name,
usr_ID,
deleted,
send_date,
resend_date,
last_date,
status,
register_date,
verify_date,
redeem_date
trans_ID
FROM invitations WHERE email=?";
if ($stmt = mysqli_prepare($db, $statement))
{
mysqli_stmt_bind_param($stmt, "s", $this->email);
if(!mysqli_stmt_execute($stmt))
{echo mysqli_stmt_error($stmt); echo mysqli_error($db); }
mysqli_stmt_bind_result($stmt,
$this->fields_db['invitation_ID'],
$this->fields_db['recipient'],
$this->fields_db['text'],
$this->fields_db['name'],
$this->fields_db['usr_ID'],
$this->fields_db['deleted'],
$this->fields_db['send_date'],
$this->fields_db['resend_date'],
$this->fields_db['last_date'],
$this->fields_db['status'],
$this->fields_db['register_date'],
$this->fields_db['verify_date'],
$this->fields_db['redeem_date'],
$this->fields_db['trans_ID']
); //PHP points the error to this line.
mysqli_stmt_fetch($stmt);
$this->invite_fields_db = $this->fields_db;
mysqli_stmt_close($stmt);
}
else
{
echo mysqli_stmt_error($stmt);
echo mysqli_error($db);
}
mysqli_close($db);
}
Can anyone see what's wrong?
Just don't use mysqli with it's bind_result, which indeed makes you ask other people to count your variables.
Either use PDO, which will make your code as short as
public function get_invitation_fields($email)
{
global $pdo; // connection should be opened ONCE at the beginning of the whole app
$sql = "SELECT * FROM invitations WHERE email=?";
$stm = $pdo->prepare($sql);
$stm->execute(array($email));
return $stm->fetch(); // values have to be RETURNED, not assigned
}
or at least use get_result() to get a familiar array from the query, without need of binding every variable manually, though it's not guaranteed to work.
$data = $mysqli->prepare("SELECT amount FROM items WHERE id=:id");
echo 'forward1';
if(!$data->execute(array(':id' => $id)))
die("error executing".$data->error);
echo '2';
$row = $data->fetch_object();
die('Losing my mind'.$row->amount);
This will only echo "forward1", not "error executing..." or "2". It works with *$mysqli->query". If I add quotes '' to :id in the query, it will echo "forward1error executing".
First, make sure you understand the prepared statements syntax and working model.
As in:
$data = $mysqli->prepare("SELECT amount FROM items WHERE id=(?)");
// THIS ^^ actually "prepares" an object to be used in the statement
$data->bind_param("i",$id)
// ...then you "bind" the parameter for your statement as "i"(nteger)
echo 'forward1';
if(!$data->execute()) // And now you simply run it, with no other args
die("error executing".$data->error);
echo '2';
$row = $data->fetch_object();
die('Loosing my mind'.$row->amount);
I suggest though using something more like
$data->execute() or die("error executing".$data->error);
The main steps of a prepared statement are:
1. Prepare the query with some placeholder values;
2. "Bind" the required number of values to the query;
3. Execute it!
I fail to see why this is relevant in your case, with such a simple query. I also assume you actually need it for something bigger.
Please let me know if I misunderstood your point or code sample.
Oh, and.. have fun! :-)
Turn on your error reporting.
You get a fatal error by accessing the method execute on your mysqli::statement after prepare failed. Check if $data === false before calling execute.
Error message: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ':id' at line 1
See this answer to why this error is triggered: MYSQLI::prepare() , error when used placeholder :something
See the PHP manual on how to use mysqli, or use PDO instead.
I create my prepared statement as:
pg_prepare('stm_name', 'SELECT ...');
Today, I had a problem (calling twice a function for mistake) when declaring a prepared statement with the same name twice:
Warning: pg_prepare() [function.pg-prepare]: Query failed: ERROR: prepared statement "insert_av" already exists in xxx on line 221
So, as the question title, there is a way to check if a prepare statement with the same label already exists, and in case, overwrite it?
I know this error is from my mistake and will be solved by simply declaring the prepared statements at the begin of my code, but I'm wondering if there is a solution to have more control over them.
EDIT:
After the Milen answer, is quite simply to check if the prepared statement is already in use, simply querying the db for the table pg_prepared_statements:
try{
$qrParamExist = pg_query_params("SELECT name FROM pg_prepared_statements WHERE name = $1", array($prepared_statement_name));
if($qrParamExist){
if(pg_num_rows($qrParamExist) != 0){
echo 'parametized statement already created';
}else{
echo 'parametized statement not present';
}
}else{
throw new Exception('Unable to query the database.');
}
}catch(Exception $e){
echo $e->getMessage();
}
But, I don't think this is a good solution, because i have to query the database every time.
Ok, usually the prepared statements are declared in the begin of the script and then just reused, but, I have a class nicely wired and I don't like to declare 10 prepared statements when I'll use just 3 of them.
So, I think I'll use a simple PHP array to keep track the statements I create, and then with isset() function check if it exists or needs to be created:
try{
$prepare = pg_prepare('my_stmt_name', "SELECT ...");
if($prepare){
$this->rayPrepared['my_stmt_name'] = true;
}else{
throw new Exception('Prepared statement failed.');
}
}catch(Exception $e){
echo $e->getMessage();
}
One way (I hope someone will point out a simpler one):
<?
$prepared_statement_name = 'activity1';
$mydbname = '...';
$conn = pg_connect("host=... port=... dbname=... user=... password=...");
$result = pg_query_params($conn, 'SELECT name FROM pg_prepared_statements WHERE name = $1', array($prepared_statement_name));
if (pg_num_rows($result) == 0) {
$result = pg_prepare($conn, $prepared_statement_name, 'SELECT * FROM pg_stat_activity WHERE datname = $1');
}
$result = pg_execute($conn, $prepared_statement_name, array($mydbname));
while($row = pg_fetch_row($result)) {
var_dump($row);
}
Haven't tried this in php but if this is feasible in your application (if you need the statement only in one place and don't have to "fetch" it again by name) you could try to prepare an unnamed statement.
http://www.postgresql.org/docs/8.4/interactive/libpq-exec.html says:PQprepare
...stmtName may be "" to create an unnamed statement, in which case any pre-existing unnamed statement is automatically replaced; otherwise it is an error if the statement name is already defined in the current session.php_pg uses PQprepare, so this might work for you.
Why are you using prepared statements at all ? They only offer a performance advantage if you use the same statement many times over.