Hi guys.
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.