为什么这个SQL代码不工作

时间:2010-06-09 09:53:00

标签: php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>اول اسكربت باذن الله</title>
</head>

<body>
<table width="100%" border="1">
 <tr>
    <td>name</td>
    <td>number</td>
    <td>math</td>
    <td>arab</td>
    <td>history</td>
    <td>geo</td>

  </tr>


<?php


require_once "conf.php";

$sql2=("SELECT * FROM student WHERE snum = $ss");
$rs2 = mysql_query($sql2) or die(mysql_error());
$num = mysql_num_rows($rs2);
$ss= $_POST["ss"];

if (empty($ss))
{ echo "please write your search words";}
else if ($num < 1 )   {
   echo  "not found any like ";

}else {
$sql=("SELECT * FROM student WHERE snum = $ss ");
$rs = mysql_query($sql) or die(mysql_error());



while($data=mysql_fetch_array($rs)){
$name=$data["sname"];
$number=$data["snum"];
$math=$data["math"];
$arab=$data["arab"];
$history=$data["history"];
$geo=$data["geo"];





echo"
  <tr>
    <td>$name</td>
    <td>$number</td>
    <td>$math</td>
    <td>$arab</td>
    <td>$history</td>
    <td>$geo</td>
  </tr>
";


}
 };
?>
 </table>
</body>
</html>

5 个答案:

答案 0 :(得分:3)

您不能使用未初始化的变量。在您的情况下$ss$sql2中使用它构建查询时可能未定义。这会导致SQL语句无效,因为=运算符之后没有任何内容。

请改为尝试:

require_once "conf.php";
if (!isset($_POST["ss"])) {
    echo "please write your search words";
} else {
    $ss = $_POST["ss"];
    $query = "SELECT * FROM student WHERE snum = '".mysql_real_escape_string($ss)."'";
    $result = mysql_query($query) or die(mysql_error());
    if (mysql_num_rows($result) == 0) {
        echo  "not found anything like ".htmlspecialchars($ss);
    } else {
        while ($data=mysql_fetch_array($result)) {
            // …
        }
    }
}

答案 1 :(得分:2)

您在退出之前将不存在的变量$ss传递给您的查询:

$sql2=("SELECT * FROM student WHERE snum = $ss"); // <-- problem here
$rs2 = mysql_query($sql2) or die(mysql_error());
$num = mysql_num_rows($rs2);
$ss= $_POST["ss"];

试试这个:

require_once "conf.php";

$ss= $_POST["ss"];

if (empty($ss))
{ echo "please write your search words";}
else if ($num < 1 )   {
   echo  "not found any like ";

}else {
$sql=("SELECT * FROM student WHERE snum = $ss ");
$rs = mysql_query($sql) or die(mysql_error());

// and more code...

答案 2 :(得分:2)

我认为$ ss = $ _POST [“ss”]; 应该去

$ sql2 =(“SELECT * FROM student WHERE snum = $ ss”);

答案 3 :(得分:1)

$ss是一个字符串吗?你有这个吗?

$sql2=("SELECT * FROM student WHERE snum = '$ss'");

答案 4 :(得分:1)

说真的吗?

首先:php是一种简单的编程语言。它按照你给出的顺序执行你给它的任何东西。这就是当您尝试使用它时,尝试在查询中使用的$ ss变量不存在的原因。您应该在使用之前指定它的值。

现在,让我们开始成为一名屁股。 $_POST['ss']由您的用户提供。不要相信它。绝不相信用户输入!他们希望控制您的服务器,以便他们找到您并绑架您索要赎金。 因此,不要在查询中使用它而不检查其值。想象一下,如果你的用户发送$ _POST ['ss'] ='1 OR 1'; 处理此类事情的最佳方法是使用mysqliPDO的参数化查询。

相关问题