views:

683

answers:

1

I've tried following the PHP.net instructions for doing Select queries but I am not sure the best way to go about doing this.

I would like to use a parameterized Select query, if possible, to return the ID in a table where the name field matches the parameter. This should return one ID because it will be unique.

I would then like to use that ID for an Insert into another table, so I will need to determine if it was successful or not.

I also read that you can prepare the queries for reuse but I wasn't sure how this helps.

+2  A: 

You select data like this:

$db = new PDO("...");
$statement = $db->prepare("select id from some_table where name = :name");
$statement->execute(array(':name' => "Jimbo"));
$row = $statement->fetch(); // Use fetchAll() if you want all results, or just iterate over the statement, since it implements Iterator

You insert in the same way:

$statement = $db->prepare("insert into some_other_table (some_id) values (:some_id)");
$statement->execute(array(':some_id' => $row['id']));

I recommend that you configure PDO to throw exceptions upon error. You would then get a PDOException if any of the queries fail - No need to check explicitly. To turn on exceptions, call this just after you've created the $db object:

$db = new PDO("...");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
troelskn
I assume you mean PDOStatement where you have new PDO(...), right?
Joe Philllips
no. PDO is the connection-class (Should probably have been named PdoConnection instead). The connection can create PdoStatements. You call setAttribute() on the connection object - not the individual statements. (Alternatively, you can pass it to the constructor)
troelskn