在PHP中使用MySQL时查询语法错误

时间:2012-03-19 05:34:19

标签: php iphone mysql

iPhone代码

当我使用此代码时,它始终显示错误密码,但我输入的是正确的凭据。

    NSString *post =[NSString stringWithFormat:@"UserName=%@&UserPas   sword=%@",userNameTextField.text, userPasswordTextFiled.text];

    NSString *hostStr = @"http://www.celeritas-solutions.com/emrapp/connect.php";
     = [hostStr stringByAppendingString:post];
    NSData *dataURL =  [NSData dataWithContentsOfURL: [ NSURL URLWithString: hostStr ]];    
    NSString *serverOutput = [[NSString alloc] initWithData:dataURL encoding: NSASCIIStringEncoding];
    if([serverOutput isEqualToString:@"Yes"]){
           UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Congrats" message:@"You are authorized "
                                                          delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
       [alertsuccess show];
           [alertsuccess release];


    } else {
            UIAlertView *alertsuccess = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Username or Password Incorrect"
                                                          delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alertsuccess show];
            [alertsuccess release];

    }

我从数据库获得验证用户名和密码,但它给出了sql语法错误

   You have an error in your SQL syntax; check the manual that corresponds to your   MySQLserver version for the right syntax to use near 'AND UserPassword=' at line 1

  mysql_select_db("emriphone", $con);


  $u=$_GET['UserName'];
  $pw=$_GET['UserPassword'];

   $check ="SELECT UserName,UserPassword from appUsers WHERE UserName=$u AND UserPassword=$pw";

  $login=mysql_query($check,$con) or die(mysql_error());

  if(mysql_num_rows($login)==1){

  $row =mysql_fetch_assoc($login);
  echo 'YES'; exit;
   }

 else{
   echo'NO';exit;
  }

 mysql_connect($con);

5 个答案:

答案 0 :(得分:2)

也许您需要在where子句中围绕用户名和密码参数添加单引号,因为我假设这些是字符串。在MySQL中,您需要将字符串包装在单引号中。

答案 1 :(得分:2)

假设用户名和密码是文本字段,您应该更正如下

$check ="SELECT UserName,UserPassword from appUsers WHERE UserName=$u AND UserPassword=$pw";

$check ="SELECT UserName,UserPassword from appUsers WHERE UserName='$u' AND UserPassword='$pw'";

包含用户名和密码的单引号

答案 2 :(得分:1)

对查询''

中的变量使用单引号

希望这会对你有所帮助。

答案 3 :(得分:1)

 $check ="SELECT UserName,UserPassword from appUsers WHERE UserName=$u AND UserPassword=$pw";

因为您使用的是mysql,请务必使用以下内容清除SQL注入的用户名和密码:

$u = mysql_real_escape_string($_GET['UserName']);
$pw = mysql_real_escape_string($_GET['UserPassword']);

最后的想法;使用POST代替GET登录页面; D呵呵

答案 4 :(得分:0)

保护自己免受sql注入

$query = sprintf("SELECT UserName,UserPassword from appUsers WHERE UserName='%s' AND UserPassword='%s'", mysql_real_escape_string($u),mysql_real_escape_string($pw));