Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/281.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/80.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 检查用户是否存在_Php_Jquery_Mysql_Cordova_Pdo - Fatal编程技术网

Php 检查用户是否存在

Php 检查用户是否存在,php,jquery,mysql,cordova,pdo,Php,Jquery,Mysql,Cordova,Pdo,可能重复: 我正在创建一个需要用户注册的Phonegap应用程序。我通过一个PHP脚本来实现这一点,该脚本充当MySQL数据库的web服务,并使用AJAX POST/Get方法 出于某种原因,LogCat总是告诉我“有一个错误”(落在帖子的错误函数中) 更新: 从MySQL的日志中,我得到了这个错误: PHP致命错误:对非对象调用成员函数bindValue() 它指向这一行:$username=$\u POST['username'] 以下是我的JS代码片段: var u = $("#user

可能重复:

我正在创建一个需要用户注册的Phonegap应用程序。我通过一个PHP脚本来实现这一点,该脚本充当MySQL数据库的web服务,并使用AJAX POST/Get方法

出于某种原因,LogCat总是告诉我“有一个错误”(落在帖子的错误函数中)

更新: 从MySQL的日志中,我得到了这个错误:
PHP致命错误:对非对象调用成员函数
bindValue()

它指向这一行:
$username=$\u 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());
}

serialize方法只是将变量转换为JSON数组,我假设您没有给出输入的名称。因此,您应该在html中输入如下名称:

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

这应该更有帮助,您还需要修改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();
应该是

您的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>
$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());
}

这里有两个基本问题:您不理解JSONP的局限性,并且错误地使用了PDO

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

简单查询 准备好的发言 JSONP 您的代码还有许多其他问题,这些问题似乎归结为您不清楚在浏览器和服务器之间传输的是什么

JSONP是一种技术,可以绕过浏览器中针对跨域请求的限制。它通过向当前页面添加带有url和
回调=
查询参数的
脚本
元素来工作。服务器使用JSON准备响应,然后将回调字符串包装在JSON周围,将应答转换为函数调用

例如:

功能剂量测定(响应){ response.name==='bob'; response.callback===“doSomething”; }

在服务器上:

header('Content-Type:text/javascript;charset=utf-8');//不是应用程序/json!
echo$_-GET['callback'],'(',$json_-encode($_-GET),');
回到浏览器,它返回的脚本是:

doSomething({"name":"bob","callback","doSomething"})
正如您所看到的,JSONP基本上是一种黑客行为。它不使用XMLHttpRequest。jQuery在其
$.ajax()
函数中做了一些事情来伪造它,但它仍然有一些无法逃避的限制:

  • 唯一可能的方法是GET(无POST),因为
    scriptsrc=
    就是这样做的
  • 向服务器传递数据的唯一方法是通过查询字符串
  • 您的响应“回调”必须可以从全局范围访问
  • 这是一个巨大的安全漏洞。您必须完全信任终端服务器,因为它可以输出所需的任何脚本
如果可能的话,使用JSONP代替JSONP

建议的解决方案 这是一种未经测试的建议方法,可以做你想做的事情

一些注意事项:

  • 注册url为。它总是返回JSON,即使是对于错误也是如此(您可以对此进行更改)。它还发出CORS头,所以您可以使用其他域的XHR发布到它
  • 服务器代码有一点抽象:
    • serviceRegisterRequest()
      是执行URL操作的主要函数。它说明了如何在适当的异常处理中使用PDO。它返回HTTP响应的抽象
    • userExists()
      createUser()
      演示如何使用PDO准备的语句
    • createUser()
      说明了如何正确使用来加密密码。(不要存储明文密码!)
    • emitResponse()
      演示如何设置CORS头以及如何生成JSON输出
在浏览器上:


您应该检查浏览器的XHR(Ajax)控制台,看看后端返回什么。错误必须在后端,而不是前端。另一种调试方法是在后端硬编码POST值,并查看错误是什么。只有在请求失败时才会抛出错误(404403500个错误)。我会检查以确保您的页面实际返回结果;而不是console.log(“有一个错误”);请告诉我们什么是outputfyi,您不需要在所有列前面使用表名。大多数列名也不需要反勾号,除非它们是保留关键字。我已经有了名称,当我尝试alert($('#registration').serialize()时;我得到了你给我的那根绳子。我不确定发生了什么,因为当我按下ok时,什么也没有发生-它转到错误函数而不是成功。序列化形式如下:username=value\u in\u username&password=value\u in\u password&password check=value\u in\u password\u check还有一件事要尝试,你能转储post变量吗?让我们看看输出,因为我在数据库中检查一个值,然后实际插入,这应该被视为JS中的POST还是GET?因为您使用类型为“POST”的Ajax请求,使用$\u POST['username']应该可以。对此类请求使用POST也比Get好,因为某些原因,我在尝试时遇到了parserError:(不确定出了什么问题)我在JS中的Ajax调用是否正确,或者我有什么问题。这是我第一次用这种方式进行Ajax调用并连接数据库。我已经用HTML代码更新了我的答案,让我知道这是否行得通。我需要首先使用SELECT语句检查数据库中是否存在用户,然后如果用户不存在,则触发INSERT语句。这就是为什么我的代码中有两条语句。
// 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();
doSomething({"name":"bob","callback","doSomething"})
<!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>