以下脚本:
<?php
try
{
$db = new PDO("sqlite:./path/phrases");
$result = $db->query('SELECT * FROM phrases');
foreach($result as $row){
$row['phrase'];
$row['score'];
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
正在回归:
Warning: Invalid argument supplied for foreach() in myscript.php on line 5
如果我执行:从短语中选择*;在SQL浏览器中,我得到了一长串结果列表,关于列短语和分数。我做错了什么?
答案 0 :(得分:1)
我在http://juanmanuelllona.blogspot.ca/
找到的第一个例子提供我希望的解决方案。
try {
$db = new PDO("sqlite:./path/phrases");
echo 'database open';
$sql = "SELECT * FROM phrases";
$obj= $db->query($sql) ;
foreach ($obj as $row)
{
print('Phrase ='.$row['phrase'].' Course='.$row['score']. '<br/>'); // or <br/>
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
这个建议取自http://www.phpro.org/tutorials/Introduction-to-PHP-PDO.html
的例子/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=phrases", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database<br />';
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM phrases";
foreach ($dbh->query($sql) as $row)
{
print $row['phrase'] .' - '. $row['score'] . '<br />';
}
/*** close the database connection ***/
$dbh = null;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
答案 1 :(得分:0)
您需要使用echo语句:
$result = $db->query('SELECT * FROM phrases');
foreach($result as $row){
echo $row['phrase'];
echo $row['score'];
}
答案 2 :(得分:-1)
try
{
$db = new PDO("sqlite:./path/phrases");
$result = $db->query('SELECT * FROM phrases;'); // remove the Semicolon
foreach($result as $row){
$row['phrase'];
$row['score'];
}
}
catch(PDOException $e)
{
echo $e->getMessage();
}
尝试删除语句中的分号。