拆分这个SQL查询,以便它可以像在工作台上一样在php上运行

时间:2017-11-30 15:59:00

标签: php mysql wordpress

这个查询在MySQL工作台上运行正常但是当我在PHP上运行它时,我做错了什么?

  $q = "SELECT post_title, post_content FROM wp_posts p1
        LEFT JOIN  wp_postmeta wm1  ON (wm1.post_id = p1.id AND wm1.meta_value IS NOT NULL AND wm1.meta_key = "_thumbnail_id")
        LEFT JOIN wp_postmeta wm2 ON (wm1.meta_value = wm2.post_id AND wm2.meta_key = "_wp_attached_file" AND wm2.meta_value IS NOT NULL)
        WHERE p1.post_status="publish" AND p1.post_type="post" AND p1.ID in ('800','808', '569')
        ORDER BY p1.post_date DESC";

   if ($result = $conn->query($q))
   {
       while ($row = $result->fetch_assoc())
       {
           // SHOW three specific posts
           printf("Title: %s\r\n",$row['post_title']); echo "<br><hr>";
           printf("Content: %s\n",$row['post_content']); echo "<br><hr>";

1 个答案:

答案 0 :(得分:1)

由于您使用双引号创建字符串,因此需要在查询中转义所有其他双引号:

$q = "SELECT post_title, post_content FROM wp_posts p1
        LEFT JOIN  wp_postmeta wm1  ON (wm1.post_id = p1.id AND wm1.meta_value IS NOT NULL AND wm1.meta_key = \"_thumbnail_id\")
        LEFT JOIN wp_postmeta wm2 ON (wm1.meta_value = wm2.post_id AND wm2.meta_key = \"_wp_attached_file\" AND wm2.meta_value IS NOT NULL)
        WHERE p1.post_status=\"publish\" AND p1.post_type=\"post\" AND p1.ID in ('800','808', '569')
        ORDER BY p1.post_date DESC";