检查用户是否存在

时间:2012-12-26 13:38:04

标签: php jquery mysql cordova pdo

  

可能重复:
  Phonegap - Load Values from Database based on a user ID

我正在创建一个需要用户注册的Phonegap应用程序。我这样做是通过一个PHP脚本充当MySQL数据库的Web服务并使用AJAX POST / Get方法。

出于某种原因,LogCat总是给我"There was an error"(属于帖子的错误功能)。

更新: 从MySQL的日志中我得到这个错误:
PHP致命错误:在非对象上调用成员函数bindValue() 它指向这一行:$username = $_POST['username'];

以下是我的JS代码的片段:

var u = $("#username").val();    
var p = $("#password").val();

var userRegData = $('#registration').serialize();

$.ajax({
  type: 'POST',
  data: userRegData,
  dataType: 'JSONp',
  url: 'http://www.somedomain.com/php/userregistration.php',
  success: function(data){   
      if(response==1){
          // User can be saved
      } else {
          // User exsts already 
      }
  },
  error: function(e){
      console.log('There was an error');
      $.mobile.loading ('hide'); 
  }
}); 
return false;

这是我的PHP代码片段。我正在使用PDO。

$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$username = $_POST['username'];
$password = $_POST['password'];
$query->bindValue(':username', $username, PDO::PARAM_STR);
$query->bindValue(':password', $password, PDO::PARAM_STR);

try {

$db->beginTransaction();

$db->query("SELECT `user`.`Username` FROM `user` WHERE `user`.`Username` = :username LIMIT 1");
try {
    if ( $query->rowCount() > 0 ) {
        $response=1;
        echo $response;
    }
    else {
        $response=0;
        $db->query("INSERT INTO `user` (`user`.`Username`, `user`.`Password`) VALUES :username, :password");
        echo $response; 
        $db->commit();  
    }
} catch (PDOException $e) {
    die ($e->getMessage());
}


} catch (PDOException $e) {
    $db->rollBack();
    die ($e->getMessage());
}

4 个答案:

答案 0 :(得分:1)

应该是

您的 HTML页面

<html>
    <body>
        <script>
            function checkIfUserCanBeSaved(){
                var userRegData = $('#registration').serialize();

                $.ajax({
                  type: 'POST',
                  data: userRegData,
                  url: 'http://www.somedomain.com/php/userregistration.php',
                  success: function(data){   
                      if(response==1){
                          alert('user found');
                      } else {
                          alert('user saved')
                      }
                  },
                  error: function(e){
                      console.log('There was an error');
                      $.mobile.loading ('hide');
                  }
                });
                return false;
            }
        </script>
        <form id="registration">
            <input type="text" name="username">
            <input type="text" name="password">
            <input type="button" onclick="checkIfUserCanBeSaved()" value="submit">
        </form>
    </body>
</html>

您的 PHP页面

$db = new PDO('mysql:host=' . $config['db']['host'] . ';dbname=' . $config['db']['dbname'], $config['db']['username'], $config['db']['password']);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$username = $_POST['username'];
$password = $_POST['password'];


try {

$db->beginTransaction();

try {

     $query = $db->prepare("SELECT user.Username FROM user WHERE user.Username = :username LIMIT 1");
     $query->bindValue(':username', $username, PDO::PARAM_STR);
     $query->execute();

    if ( $query->rowCount() > 0 ) {
        $response=1;
        echo $response;
    }
    else {
        $response=0;
        $query = $db->prepare("INSERT INTO user ( username, password ) VALUES ( :username, :password )" );
        $query->bindValue(':username', $username, PDO::PARAM_STR);
        $query->bindValue(':password', $password, PDO::PARAM_STR);
        $query->execute();
        echo $response; 
        $db->commit();  
    }
} catch (PDOException $e) {
    die ($e->getMessage());
}


} catch (PDOException $e) {
    $db->rollBack();
    die ($e->getMessage());
}

答案 1 :(得分:1)

这里有两个基本问题:您不了解JSONP的限制,并且您正在错误地使用PDO。

PDO

有一些PDO使用模式。 (为了清晰和代码重用,您可以抽象这些模式,但从根本上说,您必须按此顺序使用对象。)

简单查询

// 1. Get a database handle
$dh = new PDO($DSN, $USERNAME, $PASSWORD, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));

// 2. Issue a string query, no bindings!
$cursor = $dh->query('SELECT 1');

// 3. read results. There are many ways to do this:
// 3a. Iteration
foreach ($cursor as $row) {
    //...
}

// 3b. *fetch*
// You can use any one of multiple fetch modes:
// http://php.net/manual/en/pdostatement.fetch.php
while ($row = $cursor->fetch()) {
    //...
}

// 3c. *fetchAll*
//     *fetchAll* can also do some aggregation across all rows:
//     http://php.net/manual/en/pdostatement.fetchall.php
$results = $cursor->fetchAll();

// 3d. *bindColumn*
$cursor->bindColumn(1, $id, PDO::PARAM_INT);
while ($cursor->fetch(PDO::FETCH_BOUND)) {
    //$id == column 1 for this row.
}

// 4. close your cursor
$cursor->closeCursor();

准备好的陈述

// 1. Get a database handle
$dh = new PDO($DSN, $USERNAME, $PASSWORD, array(PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION));

// 2. Prepare a statement, with bindings
$cursor = $dh->prepare('SELECT id, name FROM mytable WHERE name = :name');

// 3. Bind parameters to the statement. There are three ways to do this:
// 3a. via *execute*:
$cursor->execute(array(':name'=>$_GET['name']));

// 3b. via *bindValue*
$cursor->bindValue(':name', $_GET['name']);

// 3c. via *bindParam*. In this case the cursor receives a *reference*.
$name = 'name1';
$cursor->bindParam(':name', $name); // name sent to DB is 'name1'
$name = 'name2'; // name sent to DB is now 'name2'!
$name = 'name3'; // now it's 'name3'!

// 4. Execute the statement
$cursor->execute();

// 5. Read the results
//    You can use any of the methods shown above.

foreach ($cursor as $row) { // Iteration
    // ...
}

// 6. Don't forget to close your cursor!
//    You can execute() it again if you want, but you must close it first.

$cursor->closeCursor();

JSONP

您的代码还有许多其他问题,似乎归结为您不清楚浏览器和服务器之间通过电线传输的内容。

JSONP是一种在浏览器中克服跨域请求限制的技术。它的工作原理是使用网址和script查询参数向当前页面添加callback=元素。服务器使用JSON准备响应,然后围绕JSON包装回调字符串,将回复转换为函数调用。

示例:

        function doSomething(response){             response.name ==='bob';             response.callback ==='doSomething';         }          

在服务器上:

header('Content-Type: text/javascript;charset=utf-8'); // NOT application/json!
echo $_GET['callback'], '(', $json_encode($_GET), ')';

回到浏览器,它返回的脚本是:

doSomething({"name":"bob","callback","doSomething"})

正如您所看到的,JSONP基本上是一个黑客攻击。它不使用XMLHttpRequest。 jQuery在$.ajax()函数中做了一些伪造它的东西,但仍有一些限制它无法逃脱:

  • 唯一可行的方法是GET(无POST),因为这是script src=所做的。
  • 将数据传递到服务器的唯一方法是通过查询字符串。
  • 您的回复“回调”必须可从全局范围访问。
  • 这是一个巨大的安全漏洞。您必须完全信任终端服务器 ,因为它可以输出它想要的任何脚本

如果可能,请使用CORS代替JSONP。

建议的解决方案

这是一种未经测试的,建议您做自己想做的事情。

一些注意事项:

  • 注册网址为http://example.org/register。它总是返回JSON,即使是错误(你可以改变它)。它还会发出CORS标头,因此您可以使用其他域中的XHR对其进行POST。
  • 服务器代码有一点抽象:
    • serviceRegisterRequest()是执行URL操作的主要功能。它说明了如何使用PDO进行适当的异常处理。它返回HTTP响应的抽象。
    • userExists()createUser()显示了如何使用PDO预处理语句。
    • createUser()说明正确使用crypt() method加密密码。 (不要存储明文密码!)
    • emitResponse()显示了如何设置CORS标头以及如何生成JSON输出。

在浏览器上http://example.COM/register

<!DOCTYPE html>
<html>
<head>
<title>test registration</title>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head>
<body>
    <form id="theform">
        <input name="u">
        <input name="p" type="password">
    </form>
    <script>
        $('#theform').submit(function(e){
            $.ajax({
                url: 'http://example.org/register',
                type: 'POST',
                data: $(e.target).serialize()
            }).done(function(response){
                console.log('SUCCESS: ');
                console.log(response);
            }).fail(function(jqXHR, textStatus){
                console.log('FAILURE: ');
                if (jqXHR.responseText) {
                    console.log(JSON.parse(jqXHR.responseText));
                }
            });
        });
    </script>
</body>

在服务器上:

function userExists($dbh, $name) {
    $ps = $dbh->prepare('SELECT id, Username FROM user WHERE Username = ?');
    $ps->execute(array($name));
    $user = $ps->fetch(PDO::FETCH_ASSOC);
    $ps->closeCursor();
    return $user;
}

function createUser($dbh, $name, $pass, $salt) {
    $ps = $dbh->prepare('INSERT INTO user (Username, Password) VALUES (?,?)';
    $crypt_pass = crypt($pass, $salt);
    $ps->execute(array($name, $crypt_pass));
    $user_id = $dbh->lastInsertId();
    $ps->closeCursor();
    return array('id'=>$user_id, 'name'=>$name);
}

function serviceRegisterRequest($method, $data, $salt, $DBSETTINGS) {

if ($method==='POST') {
    $dbh = new PDO($DBSETTINGS['dsn'],$DBSETTINGS['username'],$DBSETTINGS['password']);
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $response = array('status'=>200,'header'=>array(),'body'=>array());

    $dbh->beginTransaction(); // if using MySQL, make sure you are using InnoDB tables!
    try {
       $user = userExists($dbh, $data['u']);
       if ($user) {
          $response['status'] = 409; // conflict
          $response['body'] = array(
            'error' => 'User exists',
            'data'  => $user,
          );
       } else {
          $user = createUser($dbh, $data['u'], $data['p'], $salt);
          $response['status'] = 201; //created
          $response['header'][] = "Location: http://example.org/users/{$user['id']}";
          $response['body'] = array(
             'success' => 'User created',
             'data'    => $user,
          );
       }
       $dbh->commit();
    } catch (PDOException $e) {
       $dbh->rollBack();
       $response['status'] = 500;
       $response['body'] = array(
          'error' => 'Database error',
          'data'  => $e->errorInfo(),
       );
    } catch (Exception $e) {
       $dbh->rollBack();
       throw $e;  // rethrow errors we don't know about
    }
    return $response;

}

}


function emitResponse($response) {
    // restrict allowed origins further if you can
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST');
    foreach ($response['header'] as $header) {
        header($header);
    }
    header('Content-Type: application/json', true, $response['status']);
    $output = json_encode($response['body']);
    header('Content-Length: '.strlen($output));
    echo $output;
    exit();
}

$DBSETTINGS = array(
    'dsn'=>'mysql:...',
    'username' => 'USERNAME',
    'password' => 'PASSWORD',
);
$salt = '$6$rounds=5000$MyCr4zyR2nd0m5tr1n9$';

$response = serviceRegisterRequest($_SERVER['REQUEST_METHOD'], $_POST, $salt, $DBSETTINGS);
emitResponse($response);

答案 2 :(得分:0)

serialize方法只是将变量转换为JSON数组,我假设您没有给出输入名称。所以你应该把你的html中的名字放在这样的东西:

<form id="registration">
    <input type="text" name="username" ... 
    <input type="password" name="password" ...

现在,当您运行代码时,userRegData将类似于:

username=value_in_username_input&password=value_in_password_input

答案 3 :(得分:0)

这应该更有帮助,你还需要修改你的sql。问题是您使用两种不同的查询方法。绑定参数需要使用Prepare语句。

$username = $_POST['username'];
$password = $_POST['password'];
//new query
$query = $db->prepare("SELECT `user`.`Username` FROM `user` WHERE `user`.`Username` = :username LIMIT 1");
// since you're only using one argument, the password in the prior query I did not bind this here.
$query->bindParam(':username' PDO::PARAM_STR);

try {

$db->execute();