WordPress MySQL query fails

$query2 = "SELECT * FROM wp_posts WHERE post_status = 'publish'";
$result2 = mysql_query($query2);
if (!$result2) {
  die('Invalid query: ' . mysql_error());
}

if (mysql_numrows($result2) == 0) {
    echo("zero");
} else {
    echo(mysql_numrows($result2));
}

.. spent an hour on this, it should work but it doesn’t, not sure where I’m going wrong.

Thanks

Related posts

Leave a Reply

3 comments

  1. re. your comment: Call to undefined function  die()

    It looks like you might have some non-ASCII character in the whitespace before your die() statement. Try deleting that whitespace and reinserting it, and maybe you’ll find out what the database error is

  2. You should use query like this

     $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish'";
     $pageposts = $wpdb->get_results($querystr, OBJECT);
    

    Should be using wpdb class to communicate with the database…

  3. Try this:

    $query2 = "SELECT * FROM wp_posts WHERE post_status = 'publish'";
    $result2 = mysql_query("$query2");
    

    Double quotes in the query.

    Without the double quotes in the query, the query will look like:

    $result2 = mysql_query(SELECT * FROM wp_posts WHERE post_status = 'publish');
    

    Instead of:

    $result2 = mysql_query("SELECT * FROM wp_posts WHERE post_status = 'publish'");