【问题标题】:Getting rows from DB in WordPress using $wpdb causes critical error使用 $wpdb 从 WordPress 中的数据库获取行会导致严重错误
【发布时间】:2020-05-23 11:22:58
【问题描述】:

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

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

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

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

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

不确定为什么?我以为是 get_results() 函数,但是according to the docs,这似乎是检索行的正确方法?

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

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>

【问题讨论】:

    标签: php wordpress


    【解决方案1】:

    首先,如果你可以访问phpMyAdmin,你能检查你的表服务员是不是以wordpress前缀为前缀的?

    如果是,您应该通过以下方式更改您的查询:

    global $wpdb;
    $results = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}attendants");
    

    如果您的表格是由插件或以 wordpress 方式创建的,那么肯定会以 wordpress 为前缀。

    其次,您使用mysqli_num_rows函数,这是php方式,结果以wordpress方式返回(背后使用哪种类型的数据库的抽象)。

    由于您没有提供 get_results 返回的结果类型,因此它是一个对象数组。

    因此,要获得返回结果的计数,您应该使用:

    $number_of_results = count($results);
    

    因为它是循环中的对象,所以你应该使用符号:

    $result->first_name
    

    而不是数组表示法。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 2012-06-27
      • 1970-01-01
      相关资源
      最近更新 更多