kalia
kalia

Reputation: 219

Fatal error: Call to a member function bindParam() on string

I have a database with a table called users and a field called name. I have the following HTML code:

 <form action="change.php?link=edit" method="post">
        <input type="text" name="name" id="name" class="lg" value="">
        <input type="submit" name="sub" value="Save changes">
    </form>

And this PHP code, that updates the name field with what the user writes in the input:

  if(isset($_POST['sub'])) {
    if (!empty($_POST['name'])) {
       $name= $_POST['name'];
       $id=$_SESSION['id'];
       $sql = "UPDATE users SET name=:name WHERE id=$id";
       $sql->bindParam(":name", $name);
       $consulta = $db->prepare($sql);
       $result = $consulta->execute();
    }
  }
}

That code gives me the error "Fatal error: Call to a member function bindParam() on string", however, if I change the PHP code to:

$sql = "UPDATE users SET name='$name' WHERE id=$id";

And commenting the line:

//$sql->bindParam(":name", $name);

I get no errors. However I know that's a bad programming practice since that code is vulnerable to sql injection. How could I solve this problem?

Upvotes: 2

Views: 2878

Answers (2)

yoeunes
yoeunes

Reputation: 2945

change :

$sql = "UPDATE users SET name=:name WHERE id=$id";
$sql->bindParam(":name", $name);
$consulta = $db->prepare($sql);

to

$sql = "UPDATE users SET name=:name WHERE id=:id";
$consulta = $db->prepare($sql);
$consulta->bindParam(":name", $name, PDO::PARAM_STR);
$consulta->bindParam(":id", $id, PDO::PARAM_INT);

Upvotes: 3

Gordon Linoff
Gordon Linoff

Reputation: 1269493

That is an interesting error message. You should be able to fix it by removing the single quotes:

   $sql = "UPDATE users SET name = :name WHERE id = :id";

PHP/SQL already knows the types of the parameters. The single quotes are unnecessary.

Note: You should make :id a parameter as well.

Upvotes: 0

Related Questions