mysql查询字符串中的错误

时间:2014-05-14 02:18:39

标签: php mysql

<form action = "index.php" method = "post">
username : <input type = "text" name = "uname" /><br>
password : <input type = "text" name = "pass" /><br>
submit : <input type = "submit" name = "submit" value = "submit" />
</form>

<?php
if(isset($_SESSION['id'])){echo $_SESSION['id'];}
if(isset($_POST['submit'])){
if ($_POST['submit'] == 'submit'){

$uname = $_POST['uname'];
$pass = $_POST['pass'];
$db = "davidedwardcakes";
$connect = mysql_connect('localhost', 'root', 'wtfiwwu');
$db_connect = mysql_selectdb($db, $connect);
if(!$db_connect){echo 'no';}

$query = "SELECT * FROM `users` WHERE uname ='$uname' AND pass = '$pass'";
$result = mysql_query($query, $connect);
if(mysql_num_rows($result) > 0){//echo 'index failed'; var_dump($result);}
while($row = mysql_fetch_array($result)){echo $row['uname']
 . "<br>";

session_start();
echo '<a href = "test.php">peruse</a>';
$_SESSION['id'] = $row['id'];}}

else{echo 'lol'; var_dump($query);}}

每当我想登录时,我都会收到错误消息:     string&#39; SELECT * FROM users WHERE uname =&#39; brown&#39; AND pass =&#39; kenji&#39;&#39; (长度= 61) 意思是我的$查询有问​​题。如果我从$ query中删除$ pass查询,它可以正常工作,但在包含它时不会。请有人帮忙。

1 个答案:

答案 0 :(得分:5)

让我至少将您的代码转换为 MySQLi MySQL 已被弃用。

<?php

/* ESTABLISH CONNECTION */

$connect=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase"); /* REPLACE NECESSARY DATA */

if(mysqli_connect_errno()){

echo "Error".mysqli_connect_error();
}

/* REPLACE THE NECESSARY POST DATA BELOW AND PRACTICE ESCAPING STRINGS BEFORE USING IT INTO A QUERY TO AVOID SOME SQL INJECTIONS */
$uname=mysqli_real_escape_string($connect,$_POST['username']);
$pass=mysqli_real_escape_string($connect,$_POST['password']);

$query = "SELECT * FROM `users` WHERE uname ='$uname' AND pass ='$pass'";
$result = mysqli_query($connect,$query); /* EXECUTE QUERY */

if(mysqli_num_rows($result)==0){ 
echo 'login failed';
var_dump($result);
}

else {
     while($row = mysqli_fetch_array($result)){
     echo $row['uname'];
     } /* END OF WHILE LOOP */
echo 'Successfully Logged-in.';
var_dump($query);
} /* END OF ELSE */

?>