Page 1 of 1

PHP Object PDO Isn't Behaving As Advertised

Posted: Mon Jan 16, 2006 10:55 am
by another_php_noob
Greeting DevNetwork forum members!

I'm having a fundamental problem using PDO in a very simple context.

Here's the entire script. It connects to a DB2 dbase called 'SAMPLE'.

There is a table within SAMPLE called TEST2 and TEST2 has two columns, my_name and my_notes. The script:

Code: Select all

<?php

// Get a PDO database handle object
$dbh = new PDO("odbc:SAMPLE");

// Insert two values into database table ( NOT WORKING! )
$sth = $dbh->prepare("INSERT INTO test2 (my_name, my_notes) VALUES(?, ?)");
$sth->execute(array("My Name", "A note..."));

// Select all values from database table, print to stdout
$sth = $dbh->prepare("SELECT * FROM test2");
try { $sth->execute(); }
catch (PDOException $e) { exit($e->getMessage()); }

// Print rows just fetched
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) { print_r($row); }

?>
And the output:

Code: Select all

Array
(
    [MY_NAME] => A note...
    [MY_NOTES] => A note...
)
In my code, I specify "My Name" to go into the my_name column of this table, but it doesn't! Instead, the value for my_notes gets inserted into both columns! Anyone who knows what's wrong here, please reply to this post. Thanks!

Posted: Mon Jan 16, 2006 4:38 pm
by Burrito
try creating a variable for your insert statement then echo it out to see if it's really what you think it is.

Posted: Mon Jan 16, 2006 5:03 pm
by another_php_noob
Thanks for the reply burrito!

Incidentally, have you used PDO? Any luck?

Posted: Mon Jan 16, 2006 5:08 pm
by Burrito
Nope, I have not, but your issue sounds more query related than db access / connectivty type related.

try what I suggested:

change:

Code: Select all

$sth = $dbh->prepare("INSERT INTO test2 (my_name, my_notes) VALUES(?, ?)");
to:

Code: Select all

$query = "insert into test2 (my_name, my_notes) values ('somename','somenotes')";
echo $query;
$sth = $dbh->prepare($query);
obviously replacing with whatever you're using to insert...

Posted: Mon Jan 16, 2006 5:38 pm
by another_php_noob
I see what you mean.

However, that won't help since the issue at hand is slightly more subtle than that.

What I've found is that when I have a pre-defined query (eg, without binding params / use placeholders) and pop that into the prepare method and then have an empty execute() param list, it works.

However, when I try to bind params or use variable placeholders in my prepare statement, as in the opening post, and then make explicit those values in the execute( ... specify placeholders ... ), then it errors on me.

In other words, to use your technique is to send a fully pre-defined query into the prepare method, which again, works just fine, but doesn't address my problem.

Posted: Tue Jan 17, 2006 9:58 am
by another_php_noob
*bump*