警告:从数据库检索数据时为foreach()提供的参数无效

时间:2012-06-05 16:05:35

标签: php mysql join foreach

我试图从两个表中检索数据并回显结果,sql似乎是正确的,但它告诉我参数无效。 继承我的代码:

// Retrieve all information related to this post
    function get_post_data($post_id){

        //test the connection
        try{
            //connect to the database
            $dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
        //if there is an error catch it here
        } catch( PDOException $e ) {
            //display the error
            echo $e->getMessage();
        }

        $sql = 'SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = $post_id';
        $result = $dbh->query( $sql );

        foreach($result as $row):

            echo $row['img_id'];

        endforeach;

    }

2 个答案:

答案 0 :(得分:1)

查询中的$post_id将不会被展开,因为该字符串是单引号。

它应该更好地用于:

$sql = "SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = $post_id";

或:

$sql = 'SELECT * FROM mjbox_images JOIN mjbox_posts USING (post_id) WHERE post_id = '.$post_id;

答案 1 :(得分:0)

你需要告诉PDO抛出错误:

$dbh = new PDO("mysql:host=localhost;dbname=mjbox","root", "usbw");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

这可能会告诉你发生了什么(除了在它之前创建pdo对象时的潜在问题......)。

我还建议切换到预准备语句,以避免潜在的SQL注入或格式错误的查询问题。

我希望这不是你真正的密码...