2

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?

1
  • 2
    Remove the single quotes arount ':name'. The system already knows it is a string. Commented Aug 19, 2017 at 13:34

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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.

1 Comment

Thank you, I've already removed them, but I keep getting the same error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.