简体   繁体   English

MySQL PDO无法从表中进行选择

[英]mySQL PDO not able to SELECT from TABLE

I am trying to learn mySQL PDO .. read tutorial after tutorial and trying to apply different ways to perform a simple SELECT statement. 我正在尝试学习mySQL PDO ..逐一阅读本教程,并尝试应用不同的方法来执行简单的SELECT语句。

Here is my latest attempt: 这是我最近的尝试:

<?
include("inc/connPDO.php"); // hostname, username and password and dbName are in here
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbName", $username, $password);
/*** echo a message saying we have connected ***/
echo 'Connected to database';   // this outputs appropriately

/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM rofWeapons";
echo '<p>'.$sql;
foreach ($dbh->query($sql) as $row){   // *** line 11 error 
    print $row['weaponName'] .' - '. $row['weaponType'] . '<br />';
}


/*** close the database connection ***/
$dbh = null;    
}
    catch(PDOException $e)
{
    echo $e->getMessage();
}

?>

The output is the following: 输出如下:

Connected to database 连接到数据库

SELECT * FROM rofWeapons 选择*来自rofWeapons

Warning: Invalid argument supplied for foreach() in /home/path/to/script/script.php on line 11 警告:第11行的/home/path/to/script/script.php中为foreach()提供的参数无效

I am following a tutorial.. the foreach looks good. 我正在学习一个教程.. foreach看起来不错。 Why is it an invalid argument? 为什么它是无效的论点?

When I enter "SELECT * FROM rofWeapons" into mySQL queries the table perfectly fine. 当我在MySQL查询中输入“ SELECT * FROM rofWeapons”时,表就很好了。

A little help please? 请帮忙一下吗?

Another Attempt 另一尝试

If I try a PREPARE statement: 如果我尝试一个PREPARE语句:

/*** The SQL SELECT statement ***/
$weaponType=1;
    $sql = "SELECT * FROM rofWeapons WHERE weaponType=:weaponType";

$stmt = $dbh->prepare($sql);   // *** error Line 12 ***
$stmt->bindValue(':weaponType', $weaponType, PDO::PARAM_INT);
$stmt->execute();
$stmt->setFetchMode(PDO::FETCH_ASSOC); 

while($row = $stmt->fetch()) {
        print $row['weaponName'] .' - '. $row['weaponType'] . '<br />';
    }

I get no error. 我没有错。 Nothing at all. 没事

This is very frustrating. 这非常令人沮丧。 What am I doing wrong? 我究竟做错了什么?

You have not fetched the array for using in the loop. 您尚未获取要在循环中使用的数组。

Change: 更改:

foreach ($dbh->query($sql) as $row){
    //YOUR CODE STUFF
}

To: 至:

foreach ($dbh->query($sql)->fetchAll as $row){
    //YOUR CODE STUFF
}

It works fine. 工作正常。

Im not sure if this would fix your problem but you may want to try this: 我不确定这是否可以解决您的问题,但您可能需要尝试以下方法:

$sql = "SELECT * FROM rofWeapons";
$sth = $dbh->query($sql);
while($row = $sth->fetch(PDO::FETCH_ASSOC))
{
     print $row['weaponName'] .' - '. $row['weaponType'] . '<br />';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM