使用 $wpdb 从 WordPress 中的数据库获取行会导致严重错误

我的数据库中有一个表attendants和一个页面,results.php该页面将包含所有返回行的数据。

本质上我正在尝试做两件事:

  • 获取表中的行数。

  • 对于表中的每一行,将其数据输入到.card

但是,在注释掉几行之后,我发现这一行在我的页面上导致了严重错误:

$results = $wpdb->get_results("SELECT * FROM attendants");

不确定为什么?我认为这是 get_results() 函数,但根据文档,这似乎是检索行的正确方法?

我也不认为正在检索数据,因为当试图回显一个值时,它什么都不返回。

结果.php

<?php

global $wpdb;

$results = $wpdb->get_results("SELECT * FROM attendants");

$number_of_results = mysqli_num_rows($results);

echo $results; // returns "Array"

?>


<div class="resultsPage">

    <div class="card">

        <div class="card__header">

            <!-- trying to print number of rows in attendants table -->

            <!-- i.e there are 7 rows in this table, so $number_of_results should return 7 -->

            <h4>Total respondants: <?php echo $number_of_results; ?></h4>

        </div>

    </div>



    <?php

    foreach($results as $result){ 

        $first_name     = $result["first_name"];

        $last_name      = $result["last_name"];?>

        <div class="card">

            <div class="card__copy">

                <p><span class="card__data">Full name:</span> <?php echo $first_name+" "+$last_name; ?></p>

            </div>

        </div>

    <?php } ?>



</div>


慕的地8271018
浏览 94回答 1
1回答

饮歌长啸

首先,如果您有权访问 phpMyAdmin,您能否检查您的表 Attendants 是否以 wordpress 前缀为前缀?如果是,您应该通过以下方式更改查询:global&nbsp;$wpdb; $results&nbsp;=&nbsp;$wpdb->get_results("SELECT&nbsp;*&nbsp;FROM&nbsp;{$wpdb->prefix}attendants");如果您的表是由插件或以 wordpress 方式创建的,则可以肯定它会以 wordpress 为前缀。其次,您使用 mysqli_num_rows 函数,这是 php 方式,结果以 wordpress 方式返回(后面使用哪种类型的数据库的抽象)。由于您没有提供 get_results 返回的结果类型,它是一个对象数组。因此,要计算返回的结果,您应该使用:$number_of_results&nbsp;=&nbsp;count($results);因为它是循环中的一个对象,所以你应该使用符号:$result->first_name而不是数组符号。希望能帮助到你
打开App,查看更多内容
随时随地看视频慕课网APP