0

我试图让我可以轻松地使用来自 php/mysql 的 jquery 请求 json 输出。现在我正在使用下面的。谁能推荐一个更好的方法??

/do.php?username=bob

<?php
    $str = $_SERVER['QUERY_STRING'];
    if($str != ''){
        if(preg_match("/username/",$str)){
            parse_str($str);
            $json = json_encode(checkUserName($username));
            echo $json;
        }
    }
    function checkUserName($v){
        $db = new DB();
        $db->connectDB();

        $findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
        $countUser = mysql_fetch_row($findUsername);
        if($countUser[0] < 1){
            return array('username' => 'false');
        }else{
            return array('username' => 'true');
        }

        $db->disconnectDB();
    }
?>

我得到了一个干净的 {'username':'false'} 或 {'username':'true'} ,它可以满足我的需要;但是PHP中有更好的方法来做到这一点吗?

哇 - 惊人的答案!我转储了我的旧数据库类并将其替换为:

<?php
  function db_connect(){
    $dbh = new PDO("mysql:host=localhost;dbname=thisdb", "dbuser", "dbpass");
    return ($dbh);
  }
?>

然后在我的 do.php 脚本中我做了这个改变:

<?php
  if(isset($_GET['username'])){
    header('content-type: application/json; charset=UTF-8');
    echo json_encode(checkUserName($_GET['username']));
  }

  function checkUserName($v){
    $dbh = db_connect();
    $sql = sprintf("SELECT COUNT(*) FROM user WHERE username = '%s'", addslashes($v));
    if($count = $dbh->query($sql)){
      if($count->fetchColumn() > 0){
        return array('username'=>true);
      }else{
        return array('username'=>false);
      }
    }
  }
?>

我的jQuery是:

function checkUserName(str){
  $.getJSON('actions/do.php?username=' + str, function(data){
    var json = data;
    if(json.username == true){
      // allowed to save username
    }else{
      // not allowed to save username
    }
  });
}
4

4 回答 4

1
$str = $_SERVER['QUERY_STRING'];
if($str != ''){
    if(preg_match("/username/",$str)){
        parse_str($str);
        $json = json_encode(checkUserName($username));
        echo $json;
    }
}

使用$_GET超全局可以更容易地编写它:

if (isset($_GET['username'])) {
    echo json_encode(checkUserName($_GET['username']));
}

内部checkUserName()

$findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");

您应该正确逃脱$v

$sql = sprintf("SELECT COUNT(*) FROM user WHERE username = '%s'", mysql_real_escape_string($v));
$findUsername = mysql_query($sql);

更好的是,学习 PDO / mysqli 并使用准备好的语句。

$db->disconnectDB();

除非您使用持久连接,否则您不需要此语句。如果这样做,则应首先将返回值保留在变量中,并且仅在断开连接后才返回。

于 2012-10-10T04:15:40.130 回答
1

我不知道你的数据库类是什么,但这看起来更漂亮。

<?php

function checkUserName($v){
    $db = new DB();
    $db->connectDB();

    $findUsername = mysql_query("SELECT COUNT(*) FROM user WHERE username = '$v'");
    $countUser = mysql_fetch_row($findUsername);
    $db->disconnectDB(); // no code after "return" will do effect

    return ($countUser[0] != 0); // returning a BOOL true is better than a string "true"
}

// use addslashes to prevent sql injection, and use isset to handle $_GET variables.
$username = isset($_GET['username']) ? addslashes($_GET['username']) : '';

// the above line is equal to:
//  if(isset($_GET['username'])){
//      $username = addslashes($_GET['username']);
//  }else{
//      $username = '';
//  }

echo json_encode(checkUserName($username));

?>
于 2012-10-10T04:16:26.790 回答
0

顺便说一句,如果你想处理 json 数据,jquery你可以这样做

$.ajax({
            type:"POST",
            data:'username=bob',
            url: "do.php",
            success: function(jsonData){
                var jsonArray = eval('(' + jsonData + ')');

                if(jsonArray.username == 'true'){
                    // some action here
                }else if((jsonArray.username == 'false')){
                    // someother action hera
                }



            }
        },"json");
于 2012-10-10T04:27:06.970 回答
0

如果您想要修复,只需将您的 checkUsername 函数替换为以下函数:

function checkUserName($v){
  $db = new DB();
  $db->connectDB();  

  $findUsername = mysql_query("SELECT username FROM user WHERE username = '$v' LIMIT 1");

  if(mysql_num_rows($findUsername))
    return array('username' => mysql_result($findUsername,0));
  else
    return array('username' => 'false');

}

或者更简单的方法:

if(isset($_GET['username'])){

     $db = new DB();
     $db->connectDB();

     $query = mysql_query(sprintf("SELECT username FROM user 
                            WHERE username='%s'",
                            mysql_real_escape_string($_GET['username'])
                         );

     if(mysql_num_rows($query))
        $json = array('username'=>mysql_result($query,0));
     else
        $json = array('username'=>false);

     header('content-type:application/json');
     echo json_encode($json);
  }
于 2012-10-10T04:16:27.323 回答