我需要能够比较列中的值,而不是值在列中出现的次数。 我有多个表,它们都有相同的 20 列“标题”条目,但另一列“position_order”是不同的数字值。 我有一个包含“正确”值的基表,我想遍历“标题”列中的每个名称并计算它们的“position_order”和我的基例表的“position_order”之间的差异
我相信我已经全部正常工作了,但是当我查询数据库以查找它为列“position_order”存储的值时,出于某种原因,它不会作为我可以计算的数字返回。
<?php
echo "
<h3 class='text-center'>Table Name</h3>
<table class='table table-bordered'>
<tr>
<th>#</th>
<th>Title</th>
<th>Score</th>
</tr>
<tbody class='row_position'>"?>
<?php
require('db_config.php');
$tablename = $_SESSION['username'] . "_laliga";
$_SESSION['tablename'] = $tablename;
$sql = "SELECT * FROM $tablename ORDER BY position_order";
$users = $mysqli->query($sql);
while($user = $users->fetch_assoc()){
$sql1 = "SELECT `position_order` FROM '".$tablename."' WHERE `title` LIKE '".$user['title']."' ";
$sql2 = "SELECT `position_order` FROM `laliga` WHERE `title` LIKE '".$user['title']."' ";
$position1 = $mysqli->query($sql1);
$position2 = $mysqli->query($sql2);
?>
<tr id="<?php echo $user['id'] ?>">
<td><?php echo $user['position_order'] ?></td>
<td><?php echo $user['title'] ?></td>
<td><?php echo abs($position1-$position2); ?></td>
</tr>
<?php } ?>
</tbody>
</table>
这是错误日志
[16-May-2019 22:19:48 UTC] PHP Notice: Object of class mysqli_result could not be converted to number in /Applications/MAMP/htdocs/user.php on line 75
最佳答案
这个:
$result = $mysqli->query($sql1);
if ( ! $result ) {
throw new Exception('Query 1 failed');
}
返回一个 mysqli_result 对象,而不是一个数字。您必须从中提取实际结果。
if ( $result->num_rows ) {
$row = $result->fetch_assoc();
$position1 = $row['position_order'];
}
$result->close();
$result = $mysqli->query($sql2);
if ( ! $result ) {
throw new Exception('Query 2 failed');
}
if ( $result->num_rows ) {
$row = $result->fetch_assoc();
$position2 = $row['position_order'];
}
$result->close();
if ( isset($position1) && isset($position2) ) {
$abs = abs($position1-$position2);
} else {
$abs = null;
}
// output here
关于php - 从数据库中选择列数据(不能转换为数字?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56177337/