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);
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 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 just learning to use prepared statement in mysqli & php. Here's the snippet of the code in question.
$stmt = $mysqli->prepare ("UPDATE courses set id=?, title=?, description=?, videourl=?, article=?, colcount=?, questiondisplayed=?, onfield=? WHERE id = ?");
if ($stmt == false) { die ('prepare() failed: ' . htmlspecialchars($mysqli->error)); }
$res = $stmt->bind_param("sssssiiis", $id, $title, $description2, $videourl, $article2, $colcount, $questiondisplayed, $onfield, $oldid);
if ($res == false) { die ('bind_param() failed: ' . htmlspecialchars($mysqli->error)); }
$res = $stmt->execute();
if ($res == false) die ('execute() failed: ' . htmlspecialchars($mysqli->error));
The problem is, even after these codes run successfully (the die function never gets called), the database is not updated at all. But it's updated successfully if I'm not using prepared statement (construct the SQL query string manually). I want to convert from using manually constructed SQL query string into prepared statement. But I'm stuck in this area. Btw, the variables supplied in bind param have been set right before these codes run. I've run a print_r ($_POST); and it shows that my POST values are contain the right data. Where's the problem? Thanks.
I've update the question to further clarify
This is my first time dealing with MySQLi inserts. I had always used MySQL and directly ran the queries. Apparently, not as secure as MySQLi.
Anyhow, I’m attempting to pass two variables into the database. For some reason my prepared statement fails to do anything.
Edit: IT WORKSSS NOWWWW!!!! I added in wayyyyy more error checking. Took a bit of research, but adding checks into each function. That way I find the error code corresponding to the correct function. Once again, thank you for all your help. SURELY wouldn't of done this without you. The code listed below is now the working code
<?php
error_reporting(E_ERROR | E_WARNING | E_PARSE | E_NOTICE);
function InsertIPs($decimnal,$cidr)
{
$mysqli = new mysqli("localhost","jeremysd_ips","","jeremysd_ips");
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$stmt = $mysqli->prepare("INSERT INTO subnets VALUES ('',?,?,'1','','0','0','0','0','0', '', '0', '0', NULL)");
if( false===$stmt ){
die('prepare() failed: ' . htmlspecialchars($mysqli->error));
}
$rc = $stmt->bind_param('ii',$decimnal,$cidr);
if( false===$rc ){
die('bind_param() failed: ' . htmlspecialchars($stmt->error));
}
$rc=$stmt->execute();
if( false===$rc ){
die('execute() failed: ' . htmlspecialchars($mysqli->error));
}
printf("%d Row inserted.\n", $stmt->affected_rows);
$stmt->close();
$mysqli -> close();
}
$SUBNETS = array ("2915483648 | 18");
foreach($SUBNETS as $Ip)
{
list($TempIP,$TempMask) = explode(' | ',$Ip);
echo InsertIPs($TempIP,$TempMask);
}
?>
Thank you again
Look at your pure query:
"INSERT INTO subnets
(id, subnet, mask,sectionId,description,vrfld,masterSubnetId,allowRequests,vlanId,showName,permissions,pingSubnet,isFolder,editDate)
VALUES
('',?,?,'1','','0','0','0','0','0', '{'3':'1','2':'2'}', '0', '0', NULL)"
What is that '{'3':'1','2':'2'}' which has a comma in it? Should that be reformatted so the MySQL query doesn’t choke on it? Should those values be escaped like this:
'{\'3\':\'1\',\'2\':\'2\'}'
Or perhaps with " since you seem to now indicate you need double quotes?
'{\"3\":\"1\",\"2\":\"2\"}'
Because the single quotes mixed in with that comma just seem problematic.
Or another solution is to just bind that value to the query like this:
$raw_query = "INSERT INTO subnets (id, subnet, mask, sectionId, description, vrfld, masterSubnetId, allowRequests, vlanId, showName, permissions, pingSubnet, isFolder, editDate)
VALUES ('',?,?,'1','','0','0','0','0','0',?, '0', '0', NULL)";
if($stmt = $mysqli -> prepare($raw_query))
{
$stmt-> bind_param('ii',$decimnal,$cidr,$cidr,'{"3":"1","2":"2"}');
I've searched a lot of basically the same questions on SO which haven't seemed to help. Been a while since i've touched php so i'm guessing there's a simple solution but really can't figure it out.
config.php: (included into admin.php)
$mysqli = new mysqli($mHost, $mUser, $mPass, $db);
admin.php:
$sqlQuery = "INSERT INTO `category` (`id`, `name`) VALUES ('', '$_POST[name]')";
$result = $mysqli->query($sqlQuery);
var_dump($result) returns:
NULL
and gives error:
Fatal error: Call to a member function query() on a non-object in
You are not checking the result of the call to new mysqli. If that fails, then $mysqli will be null and not a valid object you can query against.
Also, by building SQL statements with outside variables, you are leaving yourself open to SQL injection attacks. Also, any input data with single quotes in it, like a name of "O'Malley", will blow up your SQL query. Please learn about using parametrized queries, preferably with the PDO module, to protect your web app. My site http://bobby-tables.com/php has examples to get you started, and this question has many examples in detail.
At the setout, you should call
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
This enables you don't have to check any return values, just put try { ... } catch { ... } blocks.
try {
if (
!isset($_POST['name']) ||
!is_string($_POST['name']) ||
$_POST['name'] === ''
) {
throw new UnexpectedValueException('$_POST[\'name\'] is empty');
}
$mysqli = new mysqli($mHost, $mUser, $mPass, $db);
$stmt = $mysqli->prepare("INSERT INTO `category` (`name`) VALUES (?)");
$stmt->bind_param('s', $_POST['name']);
$stmt->execute();
echo 'Success';
} catch (Exception $e) {
echo $e->getMessage();
}