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?
':name'. The system already knows it is a string.