Wordpress sql fetch_assoc

时间:2017-05-24 16:32:42

标签: sql wordpress

我很难排除故障,为什么我似乎无法在index.php上运行wordpress。它独立运行时。我在wordpress db中创建了额外的表。我跑的时候看到空白数据。不知怎的,它没有拿起数据。我在研究后才知道我需要使用$ wpdb和get_results。所以我从这个旧代码转换它:

$result = $db->query("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC");

/ 到wordpress代码 /

<?php
global $wpdb;
$results = $wpdb->get_results("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC");
?>

//在header.php上

<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

    var data = google.visualization.arrayToDataTable([
      ['name', 'Rating'],
      <?php
      if($result->num_rows > 0){
          while($row = $result->fetch_assoc()){
            echo "['".$row['name']."', ".$row['rating']."],";
          }
      }
      ?>
    ]);

    var options = {
        title: 'Figure',
        width: 900,
        height: 500,
    };

    var chart = new google.visualization.PieChart(document.getElementById('piechart'));

    chart.draw(data, options);
}
</script>

on the body html i have

<body>
    <!-- Display the pie chart -->
    <div id="piechart"></div>
</body>

1 个答案:

答案 0 :(得分:0)

如果您使用的是$ wpdb,那么您必须在get_results中传递'ARRAY_A',如下所示,以获得数组格式的结果。

global $wpdb;
$results = $wpdb->get_results("SELECT name,rating FROM wp_figure where status = '1' ORDER BY rating DESC",'ARRAY_A');