开发者

Mysqli Prepared Statement in bindParam() not working

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜