我有这个 php 代码来对变量 $rowA 中的表名进行查询循环,但我收到"数组到字符串转换"错误。有谁知道为什么?我们可以这样做查询循环吗?
$sql = "SELECT `id`, `first_name` FROM `clients` ORDER BY `id` DESC";
$result = $DB_CON_C->query($sql);
$sql_email = "SELECT `email` FROM `clients` ORDER BY `id` DESC";
$account = $DB_CON_C->query($sql_email);
foreach($result as $row) {
foreach($account as $rowA) {
$stmt = "SELECT SUM(value) AS total_amount FROM `".$rowA."`";
$amount = $DB_CON_C->query($stmt);
$sum = $amount->total_amount;
$data_row .= '<tr>'
. '<td>' .$row['id'].'</td>'
. '<td>' .$row['first_name'].'</td>'
. '<td>' .$sum.'</td>';
}
}
}
$data_row .= '</tbody>'
. '</table>';
echo $data_row;
处理数据值的方式似乎存在一个根本上奇怪的问题。
以您的第一个查询为例,$result
,这将(显然取决于确切的$DB_CON_C
类方法)输出一个用于id
和first_name
的值数组
然而,在第二次调用时,$account
使用相同的方法,您将调用值,就好像它们是类变量一样$amount->total_amount
。
我怀疑这些语法之一是错误的,但是如果没有看到您的类,我无法说出哪个。
您是否意识到您的两个 SQL 调用都返回了整个数据库?
您是否意识到您将一个表中的数据值(电子邮件地址)用作另一个表中的列名?这可以工作,但这真的不是最佳实践。
对于新行上的字符串,不需要使用
.
。$string = "Hello this string works fine";
因为空格在 HTML 中减少到一个字符长度,所以这无关紧要(太多)。
解决您的问题:
var_dump($account)
一旦填充了值,与$results相同,是否var_dump($results)
并查看值中的内容,如果这些值是class variables
的还是arrays of data
的?
看到您的两个变量都在调用同一表的不同部分,我在下面重写了您的代码:
$sql = "SELECT `id`, `first_name`, `email` FROM `clients` ORDER BY `id` DESC";
$result = $DB_CON_C->query($sql);
/***
* $result is assumed to be an array, within which is a set of values such as:
* $result[0]['id']
* $result[0]['first_name']
* $result[0]['email']
* $result[1]['id'], etc.
***/
foreach($result as $row) {
$stmt = "SELECT SUM(value) AS total_amount FROM `".$row['email']."`";
$amount = $DB_CON_C->query($stmt);
/***
* this is inconsistent, your data structure must be like $result as it
* uses the same methods, therefore you will need to enter the first
* "row" before getting the 'total_amount' value
***/
$sum = $amount[0]['total_amount'];
$data_row .= '<tr>
<td>' .$row['id'].'</td>
<td>' .$row['first_name'].'</td>
<td>' .$sum.'</td>
</tr>'; //you forgot your /tr !!
}
// Always clean up after foreach loops.
unset($row);
$data_row .= '</tbody>
</table>';
echo $data_row;
您正在尝试将数据库行解析为字符串,即使它只包含一个内容。
更改以下行
$stmt = "SELECT SUM(value) AS total_amount "
. "FROM `".$rowA."`";
自
$stmt = "SELECT SUM(value) AS total_amount "
. "FROM `".$rowA['email']."`";
$rowA
是数据库行,包含数据库中的email
字段。