我必须开发一个 appStore 插件,但有一个查询无法正常工作。
函数
function addItem($installed){...
通过回显将商店商品(一些 html 东西)添加到 div 中
<div class="flexRow order2 topLine">
<?php
addItem("false");
?>
</div>
和
<div class="flexRow order2 topLine">
<?php
addItem(true);
?>
</div>
数据选择查询如下:
$sql = "SELECT * FROM shopitems Where installed = ". $installed ;
我的问题: 如您所见,假 bool 值在引号中。否则它不会工作。 truestatement 可以在引号中,也可以不在引号中。我的查询有问题吗?
“已安装”列来自 bool 值。
网站上显示的警告 php 如下:
mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in C:\xampp\htdocs\setupItems.php on line 31
0 results
第 31 到 33 行:
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
<?php
整个函数
function addItem($installed )
{
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "appmarket";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
/*if($installed == true){
$sql = "SELECT * FROM shopitems Where installed = true ";
} else if ($installed == false){
$sql = "SELECT * FROM shopitems Where installed = false ";
}else{
error_log("forgot to enter installed bool");
}*/
$sql = "SELECT * FROM shopitems Where installed = ". $installed ;
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo'<div id="1" class="blockItem order2"> <!-- this div contains an Table for the Content of the downloadabel app-->
<div>
<table id=itemTable style="table-layout:fixed"><!--this table contains the header and the version number-->
<tr>
<th id="itemHeader" class="itemheader"><h2>' . $row["Header"] . '</h2></th>
<td id="itemAppVersion" class="version">' . $row["Version"] . '</td>
</tr>
</table>
<table id=itemTable style="table-layout:fixed"><!--this table contains the image and the description-->
<tr class="tableformat">
<td id="itemAppThumbnail" width="120px">
<img class="itemThumbnail" src="Images/' . $row["Imageurl"] . '">
</td>
<td id="itemAppDescription" style="width: 200px;">
<a class="whiteAnchor" href="Downloadable/' . $row["Downloadurl"] . '" download="logo">
' . $row["Content"] . '
</a>
</td>
</tr>
</table>
</div>
</div>'
;
}
} else {
echo "0 results";
}
mysqli_close($conn);
}
?>
最佳答案
问题源于未使用参数化语句和未检查数据类型。
仅供引用,你应该看看
的输出echo true;
打印“1”
echo false;
什么都不打印。
现在,在您的情况下,您尝试将 bool 值连接到字符串。这是不可能的,因此 PHP 会隐式地尝试将您的 bool 值转换为字符串本身,就像它对 echo 所做的那样。
false,在这种情况下,不会转换为 "false"
或 "0"
,而是转换为 ""
,这会导致您的查询:
"SELECT * FROM shopitems Where installed = "
这不是有效的 SQL。
作为快速修复,您可以使用
"SELECT * FROM shopitems Where installed = ". ($installed?"1":"0")
它明确地将您的 bool 值“转换”为“0”并生成有效查询。
从长远来看,您应该查看 parameterized statements
有关更多信息,您还应该查看 type juggling
关于php - php函数中sql查询中的假值仅在引号中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40788503/