0

我试图从两个表中检索数据并回显结果,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;

    }
4

2 回答 2

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;
于 2012-06-05T16:14:33.177 回答
0

You need to tell PDO to throw errors:

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

That will probably tell you what is happening (except for a potential problem when creating the pdo object the line before it...).

I would also recommend switching to prepared statements to avoid potential sql injection or malformed query problems.

And I hope that is not your real password...

于 2012-06-05T16:08:49.953 回答