开发者

Why is this SQL SELECT statement not retrieving the row I just inserted?

I am creating an in-memory SQLite database and inserting some a row into it. Unfortunately, I am unable to select the row I just inserted.

<?php

const CACHE_SCHEMA = <<<EOD

CREATE TABLE test ( column1 TINYTEXT,
                    column2 MEDIUMTEXT,
                    column3 INT,
                    column4 INT )

EOD;

$db = new PDO('sqlite::memory:');

$statement = $db->query(CACHE_SCHEMA);
$statement->execute();

$statement = $db->prepare('INSERT INTO test (co开发者_如何学Pythonlumn1, column2, column3, column4) VALUES (?,?,?,?)');
$statement->execute(array('a', 'b', 123, 2));

$statement = $db->prepare('SELECT column2 FROM test WHERE column1 = ? AND column3 + column4 >= ?');
$statement->execute(array('a', 124));

var_dump($statement->fetch(PDO::FETCH_ASSOC));

?>

Output: bool(false)

As you can see, the 'SELECT' statement is not returning the row I inserted:

  • Adding 'column3' and 'column4' of the row I inserted yields 125.
  • The 'WHERE' clause of the statement becomes:

    'WHERE column1 = "a" AND column3 + column4 >= 124'

    once parameters are filled in.

  • Unless I'm mistaken, 125 >= 124.


It took a bit of thinking to figure this one out, but according to the documentation for PDOStatement::execute():

"All values are treated as PDO::PARAM_STR."

So I need to change:

$statement->execute(array('a', 124));

to:

$statement->bindValue(1, 'a');
$statement->bindValue(2, 124, PDO::PARAM_INT);
$statement->execute();

...and then instead of binding a string value to the last parameter, it will bind an integer.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜