已解决,见下文
我想检查一个字符串是否已经在我的 mysql 数据库中
function checkStatus($articlename)
{
$articlename = mysql_real_escape_string($articlename);
$query = "SELECT name FROM table WHERE name LIKE '$articlename' LIMIT 1";
echo $query;
$result = mysql_query($query);
if(mysql_fetch_array($result) !== false)
return true;
return false;
}
if (checkStatus($element[$i]) == true)
echo $element[$i];
元素 [$i] 未打印,但当我将回显的 $query 复制到 phpmyadmin 时,我得到了结果。 此外,当我只是回显 $element[$i] 并复制/粘贴该值时,让我们把它的 Landskron Hell 说到代码中以获取
$query = "SELECT name FROM table WHERE name LIKE 'Landskron Hell' LIMIT 1";
然后它也有效。所以打印的变量 $element[$i] 是字符串 ABC 但在我的代码中它不是。为了检查这一点,我尝试了
if ($element[$i] == 'Landskron Hell')
echo "It worked!"
即使 echo $element[$i] 显示 Landskron Hell,这也不起作用。
我真的很困惑,希望得到任何帮助!
TL:DR PHP 变量怎么可能不等于它在回显/打印时显示的字符串?
编辑 var_dump($query)
给出 string(64) "SELECT name FROM table WHERE name LIKE 'Landskron Hell' LIMIT 1"
而 phpmyadmin 中的这个精确查询恰好给出了 1 行结果!
EDIT2: 感谢 andrewsi
我添加了
$test = 'Landskron Hell';
var_dump($articlename);
var_dump($test);
它显示:
string(15) "Landskron Hell" string(14) "Landskron Hell"
显然是有区别的!但它是什么???
EDIT3 我使用 strToHex
function strToHex($value, $prefix = '') {
$result = '';
$length = strlen($value);
for ( $n = 0; $n < $length; $n++ ) {
$result .= $prefix . sprintf('%02x', ord($value[$n]));
}
return $result;
}
结果是:
%4c%61%6e%64%73%6b%72%6f%6e%20%20%48%65%6c%6c
和
%4c%61%6e%64%73%6b%72%6f%6e%20%48%65%6c%6c
显然有 2 个空格?在我的元素?但它们没有打印出来?
已解决!:我使用了 $articlename = preg_replace('/\s+/', ' ',$articlename);
感谢 andrewsi
让我加入正确的轨道!
最佳答案
这是一个很好的函数,如果不存在则返回 false,如果存在则返回值。
// For a simple query that should return a single value, this returns just that value (or FALSE) so you can process it immediately
function db_result_single($result)
{
return ($row = mysql_fetch_row($result)) && isset($row[0]) ? $row[0] : false;
}
这是来自 php.net 的示例
我们可以修改它,让它在值已经存在时返回 true:
function db_result_single($result)
{
return ($row = mysql_fetch_row($result)) && isset($row[0]) ? true : false;
}
请注意 mysql_fetch_row
自 PHP 5.5.0 起已弃用,因此应避免使用。
关于PHP 变量不等于代码中的字符串,但打印时是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19987810/