Mysqli Prepared Statement in bindParam() not working - php

Just as usual i was looking around best practices with PHP, and prepared statements seems the kind of stuff i should now how do with my eyes closed. So i started playing around with some examples i've found.
I've got this error when running the script:
Fatal error: Call to a member function
bindParam() on a non-object in
/opt/lampp/htdocs/phpSecurity/PreparedStatments/Insert-Multi-Binded-Params/Insert
Simple Method.php on line 10
Here it goes the code.
Insert Simple Method.php
<?php
require_once '../config.php';
$stmt = $db->prepare("INSERT INTO coisas (nome, telefone, bi) VALUES (?, ?, ?)");
$nome = 'Fabio Antunes';
$telefone = 916810641;
$bi = 123093456;
$stmt->bindParam(1, $nome);
$stmt->bindParam(2, $telefone);
$stmt->bindParam(3, $bi);
$stmt->execute();
$stmt->close();
$db->close();
?>
config.php
<?php
$server_host = 'localhost';
$server_user = 'root';
$server_password = '';
$server_db = 'PreparedStatements';
$db = new mysqli($server_host, $server_user, $server_password, $server_db);
?>
Not sure what i'm doing wrong here, this is similar example found at php.net, why isn't working?
PS: I think the mysqli connection isn't the problem because I've used it to do some prepared statements with SELECT SQL commands. And worked pretty well.
EDIT
The Resolution and why.
Well in the example i should use bind_param() for each value in the query. But thanks to Bart, he managed to solve the problem with my code.
Where it is:
$stmt->bindParam(1, $nome);
$stmt->bindParam(2, $telefone);
$stmt->bindParam(3, $bi);
It should be:
$stmt->bind_param("sii", $nome, $telefone, $bi);
Now for those who might wondering what is "sii".
Well bind_param for what i see it binds the "$var" to each question mark "?" in order.
So with one bind_param() i can bind them all at the same time, and the normal use of bind_param() requires to specify the type of data being binded.
My first value to be binded is $nome a String, specified by the "s";
And the others $telefone and $bi are Integers for that he have "i";
For others that have a similar problem here it goes other data types (from php.net).
i = Integer;
s = String;
d = Double;
b = Blob;
If someone as a better explanation please post it or comment. So i can improve my own.
Thanks.

You may think there's nothing wrong with the connection, but you should check to make sure:
$db = new mysqli($server_host, $server_user, $server_password, $server_db);
if (mysqli_connect_errno()) {
printf("DB error: %s", mysqli_connect_error());
exit();
}
EDIT:
What happens when you do:
$stmt = $db->prepare("INSERT INTO coisas (nome, telefone, bi) VALUES (?, ?, ?)");
$stmt->bind_param("sii", $nome, $telefone, $bi);
$stmt->execute();
?
Is the table coisas spelled properly?

do a print_r on $stmt after you get it back on line 4. Is it a real object? I am guessing no.

Related

Insert SQL statements in php bind_param function

So I am trying to use sql commands preparation to avoid injection but I can't figure out how can I use SQL statements in the bind_param function. My code is this :
function saveContent($POST_DATA) {
$conn = new mysqli("HOST", "USER", "PASSWORD");
if ($conn->connect_error) {
return false;
} else {
$command = $conn->prepare("INSERT INTO events (title, dateHappening, time, topic,
subtopic, extraMessage) VALUES (?, ?, ?, ?, ?, ?)";
$command->bind_param("ssssss", $POST_DATA["inputTitre"], $POST_DATA["inputDate"],
$POST_DATA["inputHour"], $POST_DATA["selectTopic"], $POST_DATA["selectSubTopic"],
$POST_DATA["inputMessage"]);
$command->execute();
$command->close();
$conn->close();
}
}
The thing here is that I would like extraMessage to be NULL if it is blank (because this field is not mandatory). To optimize this code I would have liked to use something like
NULLIF($POST_DATA["inputMessage"], "")
Is inserting the statement above in the bind_param function possible ?
Question solved (see comment under my question) :
No. You have to write all the SQL expressions in the query and only insert the placeholder where the value goes. So, essentially, you would put NULLIF(?, "") in the query instead of just a ?. –

"Object of class mysqli could not be converted to string" error in php insert

When I run this code I get the error "Object of class mysqli could not be converted to string" on the line where I declare a new mysqli object. I can't find the error no matter how many times I read it over.
if(isset($_SESSION['username']))
{
echo $_POST['course'],
$mysqli = new mysqli("localhost","sec_user","Uzg82t=u%#bNgPJw","GPA_Tracker");
$user = $_SESSION['username'];
$stmt = $mysqli->prepare("INSERT into assessment_type (username, courseID, assessment, percentage) VALUES (?, ?, ?, ?)");
$stmt->bind_param('ssss', $user, $_POST['course'], $_POST['assesment'], $_POST['percentage']);
$stmt->execute();
}
As noted in the comments, this is where you have the problem:
echo $_POST['course'], //notice the comma, rather than a semi-colon ";"
$mysqli = new mysqli("localhost","sec_user","Uzg82t=u%#bNgPJw","GPA_Tracker");
The echo statement/construct accepts a comma-separated list of statements, hence coming across the , it thinks the next statement following it is also to be echoed. As it turns out, that next statement is an object-creation statement, whereas echo accepts only strings.
To fix the error, properly close your echo $_POST['course'] with a semicolon like below:
echo $_POST['course'];

PHP MySQL Call to a member function execute() on a non-object

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.

can't concatenate strings with quotes

Good evening to everyone,
Sorry if my question apperes sily but I'm pazzled by my very trivial problem
In one of the pages of my project I can't concatenate a string containing ' signs
this string can't be concatenated:
$stidR = "INSERT INTO rec_ret_info VALUES('".$rrcode."', ".$modnum.", '".$sdate."', '".$venue."', ".$fac.", ".$date.", ".$sem.")";
but this can:
$stidR = "INSERT INTO rec_ret_info VALUES(".$rrcode.", ".$modnum.", ".$sdate.", ".$venue.", ".$fac.", ".$date.", ".$sem.")";
Apparently if I remove ' signs it works. But i really need them. I really don't know where is the problem. Would be gratefull if you can point me on it.
Can you use a prepared statement to bind a variable?
Connection to Oracle with PDO - More information!
Update
PDO Prepared Statement as an example. The only thing you need to change is the query structure if Oracle is different to MySql in that regard. The binding of variables and the execution will work the same :)
$queryString= "INSERT INTO tablename (ColumnName1,ColumnName2,ColumnName3,ColumnName4,ColumnName5,ColumnName6,ColumnName7) VALUES (?,?,?,?,?,?,?)";
$query = $db->prepare($queryString);
$query->bindValue(1, $variable1, PDO::PARAM_STR);
$query->bindValue(2, $variable2, PDO::PARAM_STR);
$query->bindValue(3, $variable3, PDO::PARAM_STR);
$query->bindValue(4, $variable4, PDO::PARAM_STR);
$query->bindValue(5, $variable5, PDO::PARAM_STR);
$query->bindValue(6, $variable6, PDO::PARAM_STR);
$query->bindValue(7, $variable7, PDO::PARAM_STR);
$query->execute();
simply make echo of your statement like
echo $stidR ; and check the resulting sql, and see what you are doing wrong

Warning: PDOStatement::execute(): SQLSTATE[HY093]:

I am trying to start getting to grips with PHP and also PDO. As I am starting now, I hear that PDO is more beneficial, that is why I am not using the more popular mysqli.
I am having trouble getting data inserted into my db using PDO. I wanted to try and use prepared statements to minimize sql injection. I have tried many ways and keep hitting a brick wall.
I could do with some pointers please.
here is the error message.
Warning: PDOStatement::execute(): SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\wamp\www\test-search\insert_property.php on line 61
This is the relevant php code.
// Insert Property
// Include db
include 'db_connect_pdo.php';
include 'defines.php';
try {
// create SQL
$sql = "INSERT INTO property (pid, title, intro_en, description_en, bedrooms,
bathrooms, address, city, country, stype, ptype, price)
VALUES(:pid, :title, :intro_en, :description_en, :bedrooms, :bathrooms, :address,
:city, :country, :stype, :ptype, :price)";
// prepare the statement
$stmt = $conn->prepare($sql);
// bind the parameters and execute the statement
$stmt->bindValue(':pid', $pid);
$stmt->bindValue(':title', $title);
$stmt->bindValue(':intro_en', $intro_en);
$stmt->bindValue(':description_', $description_en);
$stmt->bindValue(':bedrooms', $bedrooms);
$stmt->bindValue(':bathrooms', $bathrooms);
$stmt->bindValue(':address', $address);
$stmt->bindValue(':city', $city);
$stmt->bindValue(':country', $country);
$stmt->bindValue(':stype', $stype);
$stmt->bindValue(':ptype', $ptype);
$stmt->bindValue(':price', $price);
// execute the statement
$stmt->execute();
}
catch (Exception $e)
{
echo $e->getMessage();
}
$conn = null;
?>
</blockquote></code>
Not sure where it is going wrong, any advice will be greatly appreciated.
Your error is this line:
$stmt->bindValue(':description_', $description_en);
Should be:
$stmt->bindValue(':description_en', $description_en);

Categories