2016-09-28 2 views
0

내 wordpress 테이블에 mysqli 대신 $ wpdb 쿼리를 사용하고 싶습니다.

문제의 워드 프레스 표는 다음과 같습니다 : I 시작

<?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

: 내가 좋아하는 것 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 |  
+----+---------------------+------+ 

mysqli 쿼리에 $ wpdb에있을 혼자서 뭔가를 시도했지만 붙어 버렸습니다.

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

그것은 굉장하고 응축되어 모든 것이 중요하다. 나는 그것을 스스로 알아낼 수 없었을 것이다. 더 많은 내용이 수정 된 형식을 사용할 수 있습니까? foreach ($ results AS $ row) { $ user_name = $ row-> name; $ user_age = $ row-> age; }' – mesumosu

+0

네, 그 루프 안에서 원하는대로 할 수 있습니다 - echo, 변수 나 연산에 할당하십시오! –

관련 문제