2013-08-17 01:35

MySQL Select ... Where子句返回语法错误

I've been racking my brain with this problem, and after searching Google and Stack Overflow a hundred times each I've decided to just ask about it outright.

I'm trying to make a page that uses PHP and MySQL to search a database as the user types in a keyword. I've used several tutorials on the subject, and they all appeared upfront and simple, but have not given any prediction for the trouble I've been having.

When I use "SELECT * FROM charlist", it returns all rows, as it should. But when I use "SELECT * FROM charlist WHERE Character ='" . $character . "'", I get the following error:

Error: 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 '= 'X'' at line 1

X is whatever the user typed in, and blank if nothing is typed in.

What am I doing wrong?

Here is the full code:

$con = mysqli_connect("xxxx", "xxxxxxxx", "xxxxxxx", "xxxxxxxxxx");
if (!$con)
  die('Could not connect: ' . mysqli_error($con));
$character = $_POST[character];
mysqli_select_db($con, "xxxxxxxx");

$sql = "SELECT * FROM charlist WHERE Character = '" . $character . "'";

$result = mysqli_query($con,$sql);
if (!$result) {
    printf("Error: %s
", mysqli_error($con));

echo "<table border='1'>

while($row = mysqli_fetch_array($result))
    echo '<tr style="border-color:#';
    echo $row[Color];
    echo ';">';
    echo '<td style="border-style:solid;border-width:3px;"><a href="';
    echo $row[url];
    echo '">';
    echo $row[Character];
    echo '</a></td>';
    echo '<td>';
    echo $row[Player];
    echo '</tr>';
echo '</table>';

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答


  • dongqiao3833 dongqiao3833 8年前

    Turning on PHP error reporting would have helped:

    $character = $_POST[character];
    //       -----------^--------^

    should be:

    $character = $_POST['character'];

    Also, inserting a variable directly into your query is a very bad practice and makes your site vulnerable to SQL injection. Always treat user input with care!

    $sql = mysqli_real_escape_string($con, $sql);

    Hope this helps!

    点赞 评论 复制链接分享
  • dtv7174 dtv7174 8年前

    change this line

    $character = $_POST[character];


    $character = $_POST['character'];

    and you should be throught

    点赞 评论 复制链接分享
  • dongpu1331 dongpu1331 8年前

    use the query as

    "SELECT * FROM charlist WHERE Character ='$character'"
    点赞 评论 复制链接分享
  • dsuw85815 dsuw85815 8年前

    Try escaping $character using:

    $sql = "SELECT * FROM charlist WHERE Character = '" . mysqli_real_escape_string($character) . "'";

    In case there are quotes in the character name breaking the query.

    点赞 评论 复制链接分享