我在 php 中编写了一个函数,它根据给定的数组更新 mysql-table。 在更新之前,我检查是否已存在具有相同“描述”值的条目。
// $fachtyp is given by foreach
$query = "SELECT IF(EXISTS(SELECT 1 FROM fachtyp WHERE `Description`='$fachtyp'),'true','false')"
. " AS existance";
$result = mysqli_query($con, $query);
$row = mysqli_fetch_assoc($result);
$exists = ($row['existance'] === 'true');
if (!$exists) { /* update */ }
问题如下:当我调试这个时,我发现 $row['exists'] 是在调试时)在 netbeans 中返回“false”。怎么会发生这种事?
感谢卢卡斯的回复
最佳答案
首先检查实际的查询和返回结果:
echo $query; // debug query
var_dump($row); // see what is returned
我建议你用更简单的查询替换sql查询(除非你真的必须像那样执行它),并用php计算出逻辑(true,false):
$query = "SELECT 1 FROM fachtyp WHERE `Description`='$fachtyp'";
$result = mysqli_query($con, $query);
$exists = (bool) mysqli_num_rows($result); // just count returned rows is enough to determine if value exists in database
if (!$exists) { /* update */ }
此外,如果 $fachtyp
值来自请求(GET 或 POST 值,实际上即使它不是来自请求),您应该使用 mysqli_real_escape_string()
来在将值放入查询之前对其进行清理。
关于PHP:MYSQL 查询返回错误值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18771983/