1

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?

4

2 に答える 2

3

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:

  1. PDO will not edit your query. It doesn't need to.
  2. You still need to run the query. The "prepare" phase simply links a place holder with a variable, so the value can be read from the appropriate location when the query runs.
  3. You can actually prepare once and run many times with different parameters.

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.

于 2012-05-04T16:03:27.700 に答える
0

Well, you have a typo (INSTERT). How to avoid it next time?

When constructing the PDO object, make sure PDO::ATTR_ERRMODE is PDO::ERRMODE_EXCEPTION, this will cause PDO to throw PDOExceptions upon errors. Do it as follows:

$this->dbh = new \PDO('mysql:host=localhost;dbname=projectname', $user, $pass, array(
                                                                                    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
                                                                               ));

Or using PDO::setAttribute():

$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

What that does, is that it causes PDO (and PDOStatement) to throw a PDOException upon error. It will kill the script if unhandled, and can be handled in the following way:

try {
    $this->addProduct();
}
catch (PDOException $e) {
    echo $e->getMessage();
}
于 2012-05-04T16:05:14.803 に答える