PDO returns NULL on longtext column, even if it’s not NULL

I’m trying to manually fetch a row on the WordPress table wp_post from outside wordpress. I use PDO as follows:

$dbh2 = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASSWORD);
    $dbh2->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $dbh2->prepare("SELECT WP.* FROM wp_posts WP, wp_term_relationships WTR WHERE WP.ID = WTR.object_id AND WP.ID = '821'");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $result){
    print_r($result);

}

The query works but I get a really weird result: the column post_content is returned as NULL even if it’s not empty (I checked on PhpMyAdmin. The post with ID: 821 exists and is full of content).

Read More

Why is it returning NULL on that column?

Additional notes:

  1. post_content column has longtext type
  2. post_content has a very long text inside, 2086 chars and full of html tags.

EDIT: The answer is correct and works. What’s weird is that var_dump correctly outputs the content, while the function fb() from FirePHP returns NULL. Be careful!

Related posts

Leave a Reply

1 comment

  1. An implementation of the example to retrieve a ‘longtext’ (blob) column.

    Note: the manual is incorrect about returning a stream as it returns a string containing the contents of the ‘lob’.

    $pdo = new PDO("mysql:host=localhost;dbname=testmysql", 'test', 'test');
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    
    $stmt = $pdo->prepare("SELECT WP.ID,
                                WP.post_title,
                                WP.post_content,
                                length(WP.post_content) AS post_length
                           FROM
                                 wp_posts WP
                           WHERE
                                 WP.ID = :ID");
    
    // which record to select
    $stmt->bindValue(':ID', 821, PDO::PARAM_INT);
    
    // store output in these variables
    $stmt->bindColumn(1, $wpId, PDO::PARAM_INT);
    $stmt->bindColumn(2, $wpTitle, PDO::PARAM_STR);
    $stmt->bindColumn(3, $wpContent, PDO::PARAM_LOB);
    $stmt->bindColumn(4, $wpLength, PDO::PARAM_INT);
    
    $stmt->execute();
    $results = $stmt->fetch(PDO::FETCH_BOUND);
    
    // display output
    var_dump($wpId, $wpTitle, $wpLength);
    var_dump($wpContent);
    

    Table Definition

    Field         Type          
    ------------  ------------  
    ID            bigint(20)    
    post_title    varchar(255)  
    post_content  longtext
    

    Sample Output:

    int 821
    string 'first' (length=5)
    int 2741
    
    string 'First Post - Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean lacus urna, impe'... (length=2741)