我需要能够检查并查看某个字符串是否在我的SQL表中的任何位置。我使用的表只有一列char。现在它说输入的所有内容都已经在表格中,即使实际上并非如此。
在SQL中,我得到的单词使用了这个:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
然而,在PHP中,用户输入的是单词,然后我将其存储为变量,然后试图找出一种方法来查看该变量是否在表中的某个位置。
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
答案 0 :(得分:2)
您需要做的不仅仅是构建查询,因为mysql_query
只返回资源,而不会提供有关实际结果的任何信息。使用像mysql_num_rows
这样的东西应该有用。
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
注意:不推荐使用
mysql_*
函数,甚至在PHP 7中将其删除。您应该使用PDO。
答案 1 :(得分:0)
在您使用的SQL中
%streeetName%
但是在下面的查询字符串中,您使用了
%$ streeetName%
更改正确的
答案 2 :(得分:0)
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
您需要检查 if($results->num_rows)
是否有查询结果。连接和查询,检查,然后打印或错误句柄的示例,代码是松散的,不检查错误。祝你好运......
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }