tags:

views:

1204

answers:

2
+3  Q: 

PDO Insert Help

Hello all, I'm having a bit of trouble inserting into a sqlite3 database with pdo. You'll have to excuse my ignorance with PDO, it seems so foreign coming from Python's database interface.

So here's my problem. I have a simple insert:

$dbh = new PDO('sqlite:vets.db');
    $count = $dbh->exec("INSERT INTO vets(name,email,clinic,streetname,citystatezip,link,phone,fax,animal,region,visible) VALUES ($name,$email,$clinic,$streetname,$citystatezip,$link,$phone,$fax,$animal,$region,$visible)");
    $dbh = null;

I simply want to execute that SQL command on my database and be done with it. Though executing this script causes no errors, it never updates the database. I've tried all sorts of permissions on the database itself, even made it 777 but it doesn't make a difference.

Could someone help me?

A: 

You can have an error in your SQL query. You could print it and then try to execute it in some SQLite GUI interface like SQLite Database Browser.

// you can skip PDO part for now, because we know it doesn't work
// $dbh = new PDO('sqlite:vets.db');
$query = "INSERT INTO vets(name,email,clinic,streetname,citystatezip,link,phone,fax,animal,region,visible) VALUES ($name,$email,$clinic,$streetname,$citystatezip,$link,$phone,$fax,$animal,$region,$visible)";
echo $query;
// $count = $dbh->exec($query);
// $dbh = null;

I see that you are not wrapping your values in quotes, probably that's the source of the problem. Maybe some typos in table field names as well. All will come out once you actually see the query.

RaYell
You were right, I was forgetting to quote my data. Thank you.
kodai
+5  A: 

One of the great benefits of PDO is that you can create prepared statements. Here's some code from a PHP project of mine:

$qry = $db->prepare(
    'INSERT INTO twocents (path, name, message) VALUES (?, ?, ?)');
$qry->execute(array($path, $name, $message));

As you can see, I use ? where I want to insert a value, then I execute the query with an array of values that should be put in place of the question marks.

If you do this, your query will be much safer, and more likely to work (since a missing value would stop your query from working if you insert variables directly in the query like you do.)

Blixt
Thank you so much for clearing this up for me. I didn't really understand these Prepared statements. Thank you!
kodai
I can never remember why it demands that the parameters be wrapped in an array() (even for one param!). Why not just accept a list of parameters?
pat
Good question... It's most likely to support/behave like the underlying library for PDO. It's definitely possible, since PHP supports a variable number of arguments. You could make your own sub-class with an `execute` that calls `parent::execute(func_get_args())`
Blixt