How to use $ wpdb variable in wordpress

0

I have this code in a php file inside the wordpress installation, it does not work, I do not know what is wrong.

global $wpdb;

$tableName = "wp_posts";

$result = $wpdb->get_results("SELECT * FROM $tableName");

foreach ($result as $row) {

echo '<p>' .$row->coluna_teste. '</p>';
    
asked by anonymous 08.03.2017 / 19:52

1 answer

2
___ erkimt ___ How to use $ wpdb variable in wordpress ______ qstntxt ___

I have this code in a php file inside the wordpress installation, it does not work, I do not know what is wrong.

global $wpdb;

// Para tabelas padrãdo do WP Use $wpdb->nomedatabela para buscar o nome 
// já com o prefixo, que pode não ser o mesmo em todos os ambientes
$result = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} LIMIT 10" );

foreach ( $result as $row ) {
    echo '<p>' . $row->post_title . '</p>';
}
    
______ ___ azszpr188807

$wpdb::get_results() returns a list of objects by default, in which each property is a column . The wp_posts table does not have a coluna_teste column, so the error.

The code below is correct and will bring the titles:

global $wpdb;

// Para tabelas padrãdo do WP Use $wpdb->nomedatabela para buscar o nome 
// já com o prefixo, que pode não ser o mesmo em todos os ambientes
$result = $wpdb->get_results( "SELECT * FROM {$wpdb->posts} LIMIT 10" );

foreach ( $result as $row ) {
    echo '<p>' . $row->post_title . '</p>';
}

complete documentation of the class $wpdb %

PS: The result of this query is the same as get_posts() . Using the function is preferable.

    
___
08.03.2017 / 21:48