我想搜索名为phpsearch和column college的数据库 我使用爆炸功能将术语与间距分开,而不是用逗号分隔。 关于i术语,我有一个疑问,因为错误说我没有定义但是我虽然php是一种语言,你不必指定数据类型而不是声明变量
代码是
<?php
$k = $_GET['k'];
$terms = explode(" ",$k);
$query = "SELECT * FROM colsearch WHERE ";
foreach ($terms as $each)
{
$i++;
if($i == 1)
$query .= "college LIKE '%$each%' ";
else
$query .= "OR college LIKE '%$each%'";
}
mysql_connect("localhost","root","");
mysql_select_db("phpsearch");
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if($numrows>0){
while ($row = mysql_fetch_assoc($query))
$id = $row ['id'];
$college = $row ['college'];
$govpriv = $row ['govpriv'];
$description = $row ['description'];
$departments = $row ['departments'];
$fees = $row ['fees'];
$location = $row ['location'];
$facilities = $row ['facilities'];
$fests = $row ['fests'];
$placements = $row ['placements'];
$link = $row ['link'];
echo "<h2><a href = '$link'>$college</a></h2>$description<br/><br/>";
} else {
echo "No results found for $k";
}
mysql_close();
?>
错误是什么?我尽力了。
答案 0 :(得分:1)
如果您打算在循环中使用$i = 0;
运算符,则必须在循环之前声明++
。
$i = 0;
foreach ($terms as $each)
{
$i++;
if($i == 1)
$query .= "college LIKE '%$each%' ";
else
$query .= "OR college LIKE '%$each%'";
}
旁注
- 除了$i
的错误之外,您应该阅读SQL注入,以及如何避免它们using mysql_real_escape_string()
答案 1 :(得分:1)
$ i未定义的事实是通知,而不是错误(您应该在循环之前声明它)
这里更大的问题是:
答案 2 :(得分:0)
如果你想使用++运算符,你必须在使用之前初始化$ i:
$k = $_GET['k'];
$terms = explode(" ",$k);
$query = "SELECT * FROM colsearch WHERE ";
$i = 0; //initialize variable here
foreach ($terms as $each)
{
$i++;
if($i == 1)
$query .= "college LIKE '%$each%' ";
else
$query .= "OR college LIKE '%$each%'";
}
答案 3 :(得分:0)
你需要声明我是一个变量,但是你是正确的PHP不要求你指定$ i的类型
所以添加一行代表$ i代码,例如:
$i = 0
foreach ($terms as $each)
{
$i++;
if($i == 1)
$query .= "college LIKE '%$each%' ";
else
$query .= "OR college LIKE '%$each%'";
}
答案 4 :(得分:0)
替代方式:
$k = $_GET['k'];
$terms = implode('|',$k);
$query = "SELECT * FROM colsearch WHERE college REGEXP '$terms'";
MySQL regexp手册页:http://dev.mysql.com/doc/refman/5.1/en/regexp.html