I’m trying to edit an INSERT query using bindParam().
Here is my code.
public function addProduct()
{
$query = "INSTERT INTO producten (name, model, price, image, description)
VALUES (:name, :model, :price, :image, :description)";
$stmt = $this->dbh->prepare($query);
$stmt->bindParam(":name", $_POST['name']);
$stmt->bindParam(":model", $_POST['model']);
$stmt->bindParam(":price", $_POST['price']);
$stmt->bindParam(":image", $_FILES['file']['name']);
$stmt->bindParam(":description", $_POST['description']);
print_r($stmt);
}
$dbh object is created in the contruct function of the class;
public function __construct()
{
$user = "root";
$pass = "";
$this->dbh = new \PDO('mysql:host=localhost;dbname=projectname', $user, $pass);
}
The $stmt->bindParam() returns true when tested but does not replace the given parameters.
Does anyone know what i’m doing wrong?
The whole idea about prepared statements is that you don’t need to inject your raw parameters into the query to compose some SQL code with escaped data. Instead, you use simple place-holders and keep the data somewhere else. When the query needs to be run, you feed the database engine with both pieces of data (the SQL query with place-holders and the values that correspond to those place-holders) and the database itself takes care of the rest.
So:
Note: some PDO drivers don’t allow regular prepared statements (for instance, because the underlying DB engine does not fully support them). In that case, PDO will emulate prepared statements and actually perform good old escaping. But since PDO is an abstraction layer, this shouldn’t change the way you deal with it.