简体   繁体   中英

MySQL Select…Where Clause Returns Syntax Error

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:

<?php
$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\n", mysqli_error($con));
    exit();
}

echo "<table border='1'>
<tr>
<th>Character</th>
<th>Player</th>
</tr>";

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'</td>';
    echo '</tr>';
}
echo '</table>';

mysqli_close($con);
?>

change this line

$character = $_POST[character];

to

$character = $_POST['character'];

and you should be throught

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.

使用查询为

"SELECT * FROM charlist WHERE Character ='$character'"

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM