未定义的变量 x 带有 mysql 的搜索引擎


Undefined variable x search engine with mysql

我做了一个搜索页面,现在它终于可以工作了,但它仍然给出错误:

注意:未定义的变量:x在 C:''xampp''xampp''htdocs''horsemask''search.php 第 21
行 注意:未定义的变量:在第 23 行的 C:''xampp''xampp''htdocs''horsemask''search.php 中构造

我确实使用本地主机,我不知道这是否是问题所在。它仍然会命中并且有效,但它看起来很丑......这是我的代码:

<?php
$button = $_GET ['submit'];
$search = $_GET ['search']; 
if(!$button)
echo "you didn't submit a keyword";
else
{
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "Jou zoekterm <b>$search</b> leverde dit op: <hr size='1'></br>";
mysql_connect("localhost","root","");
mysql_select_db("search");
$search_exploded = explode (" ", $search);
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="keywords LIKE '%$search_each%'";
else
$construct .="AND keywords LIKE '%$search_each%'";
}
$construct ="SELECT * FROM searchengine WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if ($foundnum==0)
echo "Er is niks gevonden op de zoekterm <b>$search<b>. Probeer een andere zoekterm.";
else
{
echo "$foundnum results found !<br>";
while($runrows = mysql_fetch_assoc($run))
{
$title = $runrows ['title'];
$desc = $runrows ['description'];
$url = $runrows ['url'];
echo "
<a href='$url'><b>$title</b></a><br>
$desc<br>
<a href='$url'>$url</a><p>
";
}
}
}
}
?>
只需在

像这样使用它之前初始化变量:

(如果你不初始化你的变量,它会尝试增加"undefined",并试图将一个字符串附加到"undefined",这显然是行不通的)

$x = 0;
$construct  = "";
foreach($search_exploded as $search_each) {
    $x++;
    if($x == 1)
        $construct .="keywords LIKE '%$search_each%'";
    else
        $construct .="AND keywords LIKE '%$search_each%'";
}

另外,为什么您可能会在服务器上看到错误,但在本地主机上看不到,这是因为错误报告已打开/关闭。

我建议您仅在暂存中打开错误报告:

<?php
    ini_set("display_errors", 1);
    error_reporting(E_ALL);
?>

您尚未定义变量$x并在任何地方$construct,但正在尝试递增它($x++;),因此只需创建一个像 $x = 0;$construct = ''; 这样的变量即可递增它。

在初始化任何值之前,您可以对变量$x$construct进行操作。

您应该在代码中的某个地方添加类似 $x = 0$construct = '' 的东西。

更正代码:

<?php
$button = $_GET ['submit'];
$search = $_GET ['search']; 
if(!$button)
echo "you didn't submit a keyword";
else
{
if(strlen($search)<=1)
echo "Search term too short";
else{
echo "Jou zoekterm <b>$search</b> leverde dit op: <hr size='1'></br>";
mysql_connect("localhost","root","");
mysql_select_db("search");
$search_exploded = explode (" ", $search);
$x = 0;
$construct = '';
foreach($search_exploded as $search_each)
{
$x++;
if($x==1)
$construct .="keywords LIKE '%$search_each%'";
else
$construct .="AND keywords LIKE '%$search_each%'";
}
$construct ="SELECT * FROM searchengine WHERE $construct";
$run = mysql_query($construct);
$foundnum = mysql_num_rows($run);
if ($foundnum==0)
echo "Er is niks gevonden op de zoekterm <b>$search<b>. Probeer een andere zoekterm.";
else
{
echo "$foundnum results found !<br>";
while($runrows = mysql_fetch_assoc($run))
{
$title = $runrows ['title'];
$desc = $runrows ['description'];
$url = $runrows ['url'];
echo "
<a href='$url'><b>$title</b></a><br>
$desc<br>
<a href='$url'>$url</a><p>
";
}
}
}
}
?>