这是我第一次尝试使用SQLite,我试图从SQLite中检索数据但是没有成功,也没有抛出任何异常。
我的代码如下:
$sql_query = "SELECT * FROM `item` WHERE combo LIKE '" . $value . "' LIMIT 1;";
try {
/*** connect to SQLite database ***/
$dbh = new PDO("sqlite:src/mydb.s3db");
foreach ($dbh->query($sql_query) as $row) {
$name = $row['name'];
echo "name".$name;
$style = $row['style'];
echo $style;
$appr = $row['appr'];
echo $appr;
$style = $row['style'];
echo $style;
}
} catch(PDOException $e) {
//echo $e -> getMessage();
echo "problem with DB";
echo "<br>";
}
请指导我完成这件事。 谢谢。
//phpnifo();
PDO
PDO support enabled |
PDO drivers mysql, sqlite, sqlite2
PDO_SQLITE
PDO Driver for SQLite 3.x enabled |
PECL Module version (bundled) 1.0.1 $Id: pdo_sqlite.c 293036 2010-01-03 09:23:27Z sebastian $
SQLite Library 3.3.7
答案 0 :(得分:2)
a)告诉PDO您希望它使用例外报告错误
$dbh = new PDO("sqlite::memory:");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
b)而不是将有效载荷的参与者放入sql语句中使用准备好的参数化语句
try {
$stmt = $dbh->prepare( 'SELECT * FROM `item` WHERE combo LIKE ? LIMIT 1' );
$stmt->execute( array($value) );
foreach( $stmt as $row ) { ...
c)如果你仍然没有得到任何输出尝试无条件打印的代码。例如。 SELECT Count(*)将始终返回至少一条记录(如果没有错误发生)。
$stmt = $dbh->prepare( 'SELECT Count(*) as cnt FROM `item` WHERE combo LIKE ?' );
$stmt->execute( array($value) );
foreach( $stmt as $row ) {
echo 'Count: ', $row['cnt'], "\n";
}
$stmt = null;
编辑:自包含示例
<?php
ini_set('display_errors', true);
error_reporting(E_ALL);
echo "start\n";
try {
$dbh = new PDO("sqlite::memory:");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
setup($dbh);
$stmt = $dbh->prepare('SELECT * FROM item WHERE combo LIKE ? LIMIT 1');
$stmt->execute( array('comboB') );
foreach( $stmt as $row ) {
echo
$row['name'], " ",
$row['style'], " ",
$row['appr'], "\n"
;
}
}
catch(Exception $ex) {
var_dump($ex);
}
echo "done.\n";
function setup($dbh) {
$dbh->exec('
CREATE TABLE item (
combo TEXT,
name TEXT,
style TEXT,
appr TEXT
)
');
$stmt = $dbh->prepare('INSERT INTO item (combo,name,style,appr) VALUES (?,?,?,?)');
$stmt->execute( array('comboA','nameA','styleA','apprA') );
$stmt->execute( array('comboB','nameB','styleB','apprB') );
$stmt->execute( array('comboC','nameC','styleC','apprC') );
}