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.
Related
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";
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);
I'm trying to make the following code work but I can't reach the execute() line.
$mysqli = $this->ConnectLowPrivileges();
echo 'Connected<br>';
$stmt = $mysqli->prepare("SELECT `name`, `lastname` FROM `tblStudents` WHERE `idStudent`=?");
echo 'Prepared and binding parameters<br>';
$stmt->bind_param('i', 2 );
echo 'Ready to execute<br>'
if ($stmt->execute()){
echo 'Executing..';
}
} else {
echo 'Error executing!';
}
mysqli_close($mysqli);
The output that I get is:
Connected
Prepared and binding parameters
So the problem should be at line 5, but checking the manual of bind_param() I can't find any syntax error there.
When binding parameters you need to pass a variable that is used as a reference:
$var = 1;
$stmt->bind_param('i', $var);
See the manual: http://php.net/manual/en/mysqli-stmt.bind-param.php
Note that $var doesn't actually have to be defined to bind it. The following is perfectly valid:
$stmt->bind_param('i', $var);
foreach ($array as $element)
{
$var = $element['foo'];
$stmt->execute();
}
here it is just a simple explaination
declare a variable to be bind
$var="email";
$mysqli = $this->ConnectLowPrivileges();
echo 'Connected<br>';
$var="email";
$stmt = $mysqli->prepare("SELECT name, lastname FROM tablename WHERE idStudent=?" LIMIT=1);
echo 'Prepared and binding parameters<br>';
$stmt->bindparam(1,$var);
Your actual problem is not at line 5 but rather at line 1.
You are trying to use unusable driver.
While PDO does exactly what you want.
$sql = "SELECT `name`, `lastname` FROM `tblStudents` WHERE `idStudent`=?"
$stm = $this->pdo->prepare($sql);
$stm->execute(array(2));
return $stm->fetch();
After all the years passed since this answer has been written, a new PHP feature emerged, called "argument unpacking". So, since version 5.6 you can pass a value into bind_param:
$stmt->bind_param('i', ...[2]);
But still you have a trouble with getting your data back out of a prepared statement :)
I have been getting the following error when I uploaded to a live server. It works OK on localhost which I thought was strange.
Fatal error: Call to a member function close() on a non-object....
The line it refers to
$stmt->close();
The connection to the DB
$connection=new mysqli($MYSQL_HOST,$MYSQL_USER,$MYSQL_PASS,$DB)or die(mysqli_error($connection));
The class itself.
function getTimes(){ //this method just pulls the results of the query and returns them as an array
global $connection;
$route = $this->route;
$station = $this->station;
$day = $this->day;
// create a prepared statement
if ($stmt = $connection->prepare("select time from timetable where route=? and day=? and station=?")) {
$stmt->bind_param("sss", $route, $day, $station); // bind parameters for markers
$stmt->execute(); //execute query
$stmt->bind_result($col1); //bind result variables
while ($stmt->fetch()){
$results[]=$col1;
}
}
$stmt->close();//close statement
return $results;
}
You should put $stmt into you if clause. There is a possiblity that if (false) and still get to your $stmt->close();
Your problem was that the $stmt object was instantiated as part of an if condition test. In the cases it failed, i.e. when it returns false, you were still trying to call ->close() on it anyway. I moved the method call within the if block.
Now you need to add an else clause to handle the fact that your script couldn't prepare the statement and given you say this works locally but not on your live server, I suggest there is some configuration difference causing a problem here. You need to turn on error handling with display_errors('1') and error_reporting(E_ALL). Don't forget to turn these off before letting the world at your new script. :)
function getTimes(){ //this method just pulls the results of the query and returns them as an array
global $connection;
$route = $this->route;
$station = $this->station;
$day = $this->day;
// create a prepared statement
if ($stmt = $connection->prepare("select time from timetable where route=? and day=? and station=?")) {
$stmt->bind_param("sss", $route, $day, $station); // bind parameters for markers
$stmt->execute(); //execute query
$stmt->bind_result($col1); //bind result variables
while ($stmt->fetch()){
$results[]=$col1;
}
$stmt->close();//close statement
}
return $results;
}
Move the close() call into your if statement, so that it will only be called if a $stmt was successfully created.
// create a prepared statement
if ($stmt = $connection->prepare("select time from timetable where route=? and day=? and station=?")) {
$stmt->bind_param("sss", $route, $day, $station); // bind parameters for markers
$stmt->execute(); //execute query
$stmt->bind_result($col1); //bind result variables
while ($stmt->fetch()){
$results[]=$col1;
}
$stmt->close();//close statement
}
I suspect on your local machine you don't have errors turned on, but on the server you upload to, errors are on.
The root issue to address here is the fact that prepare() is failing. The problem there most likely is the database on the server is missing the timetable table or that table is missing one or more fields route, day or station. As said by cbuckley, check $connection->error for the full error message.
When you uploaded to the server, did you remember to also make any database structure changes on the server?
i am trying to use prepared statements but having trouble getting it to successfully run.
here is my code:
function addAlbum($album){
$connection = mysqli_connect(HOST,USER,PASS,DATABASE);
/*$sql = 'INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")';
$result = mysqli_query($connection,$sql);*/
$stmt = $dbh->prepare('INSERT INTO `'.TABLE_ALBUMS.'` (albumName) VALUES ("'.$album.'")');
$stmt->bindParam(':albumName', $album);
$result = $stmt->execute();
if($result){
header("Location: index.php?success");
} else {
header("Location: index.php?fail");
}
}
i have ran this in firefox with errors on and this is what i get:
Fatal error: Call to undefined method
mysqli_stmt::bindParam() in
/Applications/MAMP/htdocs/PHPproject/includes/functions.inc.php
on line 16
could any one please tell me where i am going wrong?
many thanks
First argument for bind should be the type of variable:
$stmt->bind_param("s", $album);
Also you should check the return value of execute() and not the $stmt:
$result = $stmt->execute();
if($result){
echo "yes";
}
else {
echo "no";
}
Also I'd say that it's not a good ideea to prepare the statement each time you insert something. Prepared statements should be class variables or if you're not in oop, global variables, so you don't prepare the statement each time you call the function. Just write a function init() that will prepare all the statements that you'll use.