0

I am trying to do a prepared statement. My code is below. I use PHP and MySQLi. I get this error message:

Fatal error: Call to a member function prepare() on a non-object in/path/path/

$sql = "INSERT INTO person(name, $lastname)
VALUES (?, ?)";
$stmt = $sql->prepare($sql);
$stmt->bind_param("ss", $name, $lastname);
$name= '?';
$lastname='?';
$stmt->execute();

The error message points to this line:

$stmt = $sql->prepare($sql);

What is the issue?

Benjamin W.
  • 33,075
  • 16
  • 78
  • 86
Alison
  • 147
  • 9
  • look at this properly. `INSERT INTO person(name, $lastname)` `$lastname` – Rotimi Jan 03 '18 at 18:50
  • INTO person(name, $lastname) - that dollar-sign is wrong – Lars Stegelitz Jan 03 '18 at 18:50
  • 1
    You define $sql as a string, that is why you can't use it as an object. You should read a bit more about how to use mysqli and objects in generel – Frederik Banke Jan 03 '18 at 18:50
  • also you should get an undefined variable for `$name` and `$lastname` as you declared them after and not before – Rotimi Jan 03 '18 at 18:51
  • 1
    `$sql` is a string as you overwritten it with the query. – Lawrence Cherone Jan 03 '18 at 18:57
  • What exactly are you binding with `bind_param()` here? Why are you assigning to `$name` and `$lastname` after you've used them? Are you really assigning `'?'` or is that just an example of something else? I think you need to work through more examples and read more before coming to SE. – Octopus Jan 03 '18 at 19:32

1 Answers1

0

You're stomping your database connection with a string, and then everything goes berserk. Fix that:

$stmt = $db->prepare("INSERT INTO person(name, lastname) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $lastname);
$name= '?';
$lastname='?';
$stmt->execute();

Here $db is your database connection, wherever that's created with new mysqli(...).

tadman
  • 194,930
  • 21
  • 217
  • 240