在执行基本SELECT时,SQL语法中存在错误

时间:2012-04-20 12:35:48

标签: php mysql mysql-error-1064

我正在尝试在MySQL数据库中搜索用户特定的网站活动,为此,我创建了一个表单和进程来搜索统计信息表并返回每个记录都带有与查询匹配的用户ID。但是我一直收到这条消息而不确定原因:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL     server version for the right syntax to use near '@hotmail.com' at line 1

这是我正在使用的表格

<form method='get' action='searchuser.php'  id='searchuser'>
<input type='text' input name='txtSearch' id='txtSearch'>
    <input type='submit' name='submit' value='Search'>
</form>";

这是流程文件

<?php
require_once( "Functions.php" );
$header = makeHeader();

$con= connect();


$user = $_GET['txtSearch'];

$query = "SELECT * FROM statistics WHERE userID = $user";
$result=mysql_query($query) or die (mysql_error());

echo"<table border='1'><th>User</th><th>IP</th>
    <th>Date</th><th>Page visited</th><th>Page from</th>";

while($row = mysql_fetch_assoc($result))
{
$username = $row['userID'];
$ip =  $row['ipAddress'];
$date = $row['dateOfVisit'];
$pagev = $row['pageVisited'];
$pagef = $row['pageFrom'];

echo "<tr><td>".$row->UserID."</td><td>".$row->ipAddress."</td><td>".$row->dateOfVisit."</td><td>".
    $row->pageVisited."</td><td>".$row->pageFrom . "<br/>\n"."</td></tr>";
    }
IF (mysql_num_rows($queryresult) == "") 
            {
                Echo "<p>Sorry there were no results for your         search<p> <br /><br /> <p><A HREF='javascript:javascript:history.go(-1)'>Click here to go back to previous page</A></p>";
            } 


$footer = makeFooter();

?>

2 个答案:

答案 0 :(得分:3)

SQL问题出在

  

userID = $user

将字符串放入sql查询的正确方法是

  • 用引号
  • 分隔
  • 并使用mysql_real_escape_string来逃避可能发生在内部的分隔符。

因此。正确的代码是

  $user =  mysql_real_escape_string($user);
  $query = "SELECT * FROM statistics WHERE userID = '$user'";

答案 1 :(得分:-2)

尝试这个

$user = $_GET['txtSearch'];
$query = "SELECT * FROM statistics WHERE userID = ".$user." ";

这对我有用