foreach提供的参数无效; PDO [英] Invalid argument supplied for foreach; PDO

查看:310
本文介绍了foreach提供的参数无效; PDO的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到,但这些都不帮助我的情况,这就是为什么我知道地打开一个问题, 。






我的代码是:

 < ;? 
$ getGame = $ database-> prepare('SELECT * FROM mainSite_games WHERE id =:gameID');
?>
< div class ='container_12'>
< div id ='contentcont'>
< div id ='content'>
< ;?
if(isset($ _ GET ['gameID'])){
$ getGame-> bindValue(':gameID',$ GET ['gameID'],PDO :: PARAM_INT);
$ getGame-> execute();
$ rows = $ getGame-> fetch(PDO :: FETCH_ASSOC);

foreach($ rows as $ game){

$ gameName = str_replace('','_',strtolower(strips_ashes($ game ['gameName'])) );
?>
< section class ='< ;? echo $ gameName; >'>


< h1>< ;? echo stripslashes($ game ['gameName']); ?>< / h1>

< p>< ;? echo stripslashes($ game ['gameDesc']); ?>< / p>


< article class ='grid_5 alpha'style ='float:left;'>

< h3>< a href ='viewQuests.php?game ID =< ;? echo $ game ['id']?>'>查看< ;? echo stripslashes($ game ['gameName']); ?>任务< / a>< / h3>
< p>提供在<?中查看可用任务的功能echo stripslashes($ game ['gameName']); ?>以及关于他们的信息和每个人的简单指南。< / p>

< / article>


< article class ='grid_5 omega'style ='float:right;'>

< h3>< a href ='viewDB.php?gameID =< ;? echo $ game ['id']?>'>查看< ;? echo stripslashes($ game ['gameName']); ?>数据库< / a>< / h3>
< p>优惠信息< ;? echo stripslashes($ game ['gameName']); ?>项目,地点和字符。我们努力扩大我们的信息。< / p>

< / article>


< / section>

< ;?
}
} else {
echo'< h3>游戏ID未设置!< / h3> ;;'
exit
}

?>
< / div>
< / div>
< / div>
< / body>
< / html>
< ;?
$ database = null;
unset($ database);
?>

数据库已初始化并连接到我的globhead文件提供的包含:

  $ function = new srFunc(); 
try {
$ database = new PDO('mysql:host = localhost; dbname = expunged; charset = utf8','expunged','expunged',array(
//数据库属性
PDO :: ATTR_EMULATE_PREPARES => false,//使用真正准备的语句
PDO :: ATTR_ERRMODE => PDO :: ERRMODE_EXCEPTION,//设置错误以杀死应用程序
PDO :: ATTR_PERSISTENT => true //保持连接无限期打开
));
} catch(PDOException $ e){
$ function-> logPDO($ e-> getMessage());
exit();
}

logPDO由我的函数类提供:

  public function logPDO($ err){
try {
$ filename ='logPDO';
$ filehandle = fopen($ filename,'a');
fwrite($ filehandle,'['.date('Y-m-d Ga e')。']'$ err。\\\
\\\
);
fclose($ filehandle);
} catch(exception $ e){
return $ e;
}
}

OK现在我们知道我的代码如何工作 - 在我的foreach的最上面的代码框中,它在我的错误日志中报告:

  foreach提供的参数无效

现在,改变刚刚上面的那行( $ rows = $ getGame-> fetch PDO :: FETCH_ASSOC))添加到 $ rows = $ getGame-> fetchAll(PDO :: FETCH_ASSOC)无。它只是成为一个空白的页面,我的造型和结构完好无损。



我不知道发生了什么,我对PDO很新,所以我不是确保如何解决此问题。



我已经尝试在try,catch块中包装,但没有报告(也没有使用我的日志功能记录到文件),所以我在亏损。有没有更多的PDO经验的人看到我的代码错误的任何东西?

解决方案


不知道发生了什么,我对PDO很新,所以我不知道如何解决这个问题。


是的,你有一个空的数据库结果。如果你遍历空结果,没有(零)迭代。因此,您看不到输出,因此您看不到错误。



如何解决问题?我认为最好理解空数据库结果和失败的数据库查询之间的区别。例如。只要您有选择行的查询,就会有 rowCount()方法






其他备注: / p>


  • 您正在使用PHP短标记<?,请参阅 是否可以接受PHP短标签,并了解所带来的潜在问题。我们诚挚地要求用户在此网站上发布PHP源代码,而不是使用它们向广大受众群体解答这个问题(因为这是本网站的用意)。

  • 输出代码你不应该包含数据库交互。您可以通过只传递 $ rows 变量并移动其周围的if子句来实现。

  • 分配 NULL $ database 变量只到 unset($ database);

  • 根本不需要 unset($ database); 。 PHP将在您结束脚本时为您清除此错误。如果您想要关闭PDP中的数据库连接,并且正在使用mysql,请参阅 使用PDO打开的SQL连接PHP必须关闭 ,如果您真的需要关闭连接,您可以了解如何完成此操作在此答案中


I have seen this and this, but neither of these help my situation, this is why I am knowledgeably opening a question that has been asked before.


My code is:

<?
    $getGame = $database->prepare('SELECT * FROM mainSite_games WHERE id=:gameID');
?>
    <div class='container_12'>
        <div id='contentcont'>
            <div id='content'>
            <?
            if (isset($_GET['gameID'])) {
                $getGame->bindValue(':gameID',$GET['gameID'],PDO::PARAM_INT);
                $getGame->execute();
                $rows = $getGame->fetch(PDO::FETCH_ASSOC);

                foreach ($rows as $game) {

                    $gameName = str_replace(' ','_',strtolower(stripslashes($game['gameName'])));
            ?>
                    <section class='<? echo $gameName; ?>'>


                        <h1><? echo stripslashes($game['gameName']); ?></h1>

                        <p><? echo stripslashes($game['gameDesc']); ?></p>


                        <article class='grid_5 alpha' style='float:left;'>

                            <h3><a href='viewQuests.php?gameID=<? echo $game['id'] ?>'>View <? echo stripslashes($game['gameName']); ?> Quests</a></h3>
                            <p>Offers the ability to see the available quests in <? echo stripslashes($game['gameName']); ?> along with information about them and a simple guide to go along with each.</p>

                        </article>


                        <article class='grid_5 omega' style='float:right;'>

                            <h3><a href='viewDB.php?gameID=<? echo $game['id'] ?>'>View <? echo stripslashes($game['gameName']); ?> Database</a></h3>
                            <p>Offers information about <? echo stripslashes($game['gameName']); ?> items, places, and characters. We try to be extensive with our information.</p>

                        </article>


                    </section>

            <?
                }
            } else {
                echo '<h3>Game ID is not set!</h3>;'
                exit();
            }

            ?>
            </div>
        </div>
    </div>
</body>
</html>
<?
    $database = null;
    unset($database);
?>

The database is initialized and connected to in an include provided by my globhead file:

$function = new srFunc();
try {
    $database = new PDO('mysql:host=localhost;dbname=expunged;charset=utf8','expunged','expunged',array(
        //database attributes
        PDO::ATTR_EMULATE_PREPARES=>false, //use real prepared statements
        PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION, //set errors to kill application
        PDO::ATTR_PERSISTENT=>true //keep the connection open indefinitely
        ));
} catch (PDOException $e) {
    $function->logPDO($e->getMessage());
    exit();
}

logPDO is provided by my functions class:

public function logPDO($err) {
    try {
        $filename = 'logPDO';
        $filehandle = fopen($filename, 'a');
        fwrite($filehandle,'[ '.date('Y-m-d Ga e').' ]  '.$err."\n\n");
        fclose($filehandle);
    } catch (exception $e) {
        return $e;
    }
}

OK..so now we know how my code works -- in the uppermost code box at my foreach, it reports in my error log:

Invalid argument supplied for foreach

Now, changing the line just above ($rows = $getGame->fetch(PDO::FETCH_ASSOC)) to $rows = $getGame->fetchAll(PDO::FETCH_ASSOC) (adding All), nothing is reported. It just becomes a blank page with my styling and structure intact.

I'm not sure what's going on, and I am very new to PDO, so I'm not sure how to troubleshoot this.

I have tried wrapping this in a try,catch block but nothing was reported (nor logged to file using my log function), so I'm at a loss. Does anyone with more experience with PDO see anything that's wrong with my code?

解决方案

I'm not sure what's going on, and I am very new to PDO, so I'm not sure how to troubleshoot this.

What's going on is, that you've got an empty database result. If you foreach over an empty result, there are no (zero) iterations. Hence you see no output and hence you see no error. It's a perfectly fine programming of doing nothing.

How to troubleshoot? I think it's best to understand the difference between an empty database result and a failed database query. E.g. as long as you have a query that selects rows, there is a rowCount() method with the result object.


Additional remarks:

  • You are using PHP short-tags <?, please see "Are PHP short tags acceptable to use?" and understand the potential problems this carries. We kindly asks users when posting PHP source-code on this website here to not use them to address the question to the general audience (as this is the intention of this website).
  • The output code you have should not contain the database interaction. You can achieve this by only passing the $rows variable in there and move the if-clause around it.
  • Assigning NULL to the $database variable only to unset($database); it is not necessary in PHP.
  • You do not need to unset($database); at all. PHP will clean this up for you when you end the script. If you want to close the database connection in PDP and you're using mysql, please see "Do SQL connections opened with PDO in PHP have to be closed" and if you really need to close the connection, you can learn how this can be done in this answer to it.

这篇关于foreach提供的参数无效; PDO的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆