如果用户的名字包含一些字符串插入到数据库表中,我想锁定用户的注册。我用了这段代码:
$repWor = mysql_query("SELECT * FROM reportedWord WHERE Word LIKE '%$username%'");
if (strpos($username, $repWor) !== false) {
echo 'The name contains characters or words not allowed.';
}
但它不起作用。如何解决?
答案 0 :(得分:2)
查询后,您需要使用mysql_fetch_array
:
<?php
$repWor = mysql_query("SELECT * FROM reportedWord WHERE Word LIKE '%$username%'",$cnx);
$dat = mysqli_fetch_array( $repWor ); // <====================
if (strpos($username, $dat["Word"] ) !== false) { echo 'The name contains characters or words not allowed.';
?>
正如@apokryfos所说,你应该改为mysqli
,这很简单:
<?php
$repWor = mysqli_query($cnx,"SELECT * FROM reportedWord WHERE Word LIKE '%$username%'");
$dat = mysqli_fetch_array( $repWor ); // <===================
if (strpos($username, $dat["Word"] ) !== false) { echo 'The name contains characters or words not allowed.';
?>
答案 1 :(得分:1)
使用mysql_query返回结果资源。它不会根据您的SQL返回字符串或数组。您必须将mysql_query与mysql_fetch_row或mysql_fetch_assoc结合使用。
可以找到一个完整的例子 http://php.net/manual/en/function.mysql-fetch-assoc.php
然后将您的代码转换为:
$search = mysql_real_escape_string($username);
$query = "SELECT * FROM reportedWord WHERE Word LIKE '%{$search}%'";
$result = mysql_query($query, $connection);
$row = mysql_fetch_assoc($result);
if (strpos($username, $row['reportedWord']) !== false) {
echo 'The name contains characters or words not allowed.';
}
在获得强大的解决方案之前,您还有很长的路要走,您应该考虑使用mysqli并按照快速入门指南进行操作:http://php.net/manual/en/mysqli.quickstart.statements.php
或者更进一步,使用像Doctrine http://www.doctrine-project.org/
这样的库