2016-09-28 5 views
0

私のwordpressテーブルにmysqliの代わりに$ wpdb queryを使用したいと思います。

問題のwordpressのテーブルを次のようにwp_example

+----+---------------------+------+ 
| id | name    | age | 
+----+---------------------+------+ 
| 1 | Sandy Smith   | 21 |  
| 2 | John Doe   | 22 |   
| 3 | Tim Robbins   | 28 |   
| 4 | John Reese   | 29 |   
| 5 | Harold Finch  | 20 |  
+----+---------------------+------+ 

私は$のwpdbになりたいmysqliのクエリ:

<?php 
// Make a MySQL Connection 

$query = "SELECT * FROM wp_example"; 
$result = $mysqli->query($query); 
$row = $result->fetch_array(MYSQLI_ASSOC); 
printf ("%s (%s)\n", $row["name"], $row["age"]); 

/* close connection */ 
?> 

Reference 1
Reference 2

私が始めました私自身で何かを試してみたが、立ち往生した。

global $wpdb; 
$query = $wpdb->get_results($wpdb->prepare("SELECT * FROM wp_example", ARRAY_A)); 

は、さらに指針を持っています。あなたのテーマの機能ファイルで

+3

あなただけの 'SQLを持っていることは、準備された文であってはならない'「wp_example SELECT * FROM」にしたい場合。 SQLに変数がある場合は、準備されたステートメントのみが必要です。あなたは '$ query = $ wpdb-> get_results(" SELECT * FROM wp_example "、ARRAY_A);' – sdexp

答えて

1

、これを追加します。

function test_query() { 
    // Global in the database 
    global $wpdb, $table_prefix; 
    // Set up the table name, ensuring you've got the right table prefix 
    $table = $table_prefix . 'example'; 
    // For demo purposes, set up a variable 
    $age = 21; 
    // For TESTING ONLY, turn on errors to be sure you see if something goes wrong 
    $wpdb->show_errors(); 
    // Use $wpdb->prepare when you need to accept arguments 
    // Assign the query to a string so you can output it for testing 
    $query = $wpdb->prepare("SELECT * FROM {$table} WHERE age = %d", $age); 
    // For TESTING ONLY, output the $query so you can inspect for problems 
    var_dump($query); 
    // Get the results 
    $results = $wpdb->get_results($query); 
    // Output the results 
    foreach($results AS $row) { 
     // Don't use ARRAY_A - just access as an object 
     echo '<p>' . $row->name . '</p>'; 
     echo '<p>' . $row->age . '</p>'; 
    } 
} 

// Run your function 
test_query(); 
+0

を持っています。それはすごく凝縮し、簡潔でした!私は自分でそれを理解することができなかったでしょう。 もう1つのものは、この変更された形式を使用できますか? 'foreach($ results AS $ row){ $ user_name = $ row-> name; $ user_age = $ row-> age; } ' – mesumosu

+0

はい、ループ内で好きなことをすることができます - エコー、または変数、または操作に割り当てる! –

関連する問題