0

I'm trying to make it easy for me to request json output using jquery from php/mysql. Right now I'm using the below. Can anyone recommend a better way??

/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();
    }
?>

I get back a clean {'username':'false'} or {'username':'true'} which works for what I need; but is there a better way in PHP to do this?

Wow - amazing answers! I dumped my old db class and replaced it with:

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

Then in my do.php script I made this change:

<?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);
      }
    }
  }
?>

and my jquery is:

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
    }
  });
}
3
  • 1
    $db->disconnectDB(); is unreachable. Commented Oct 10, 2012 at 4:09
  • 1
    Where is the DB class? Commented Oct 10, 2012 at 4:10
  • 1
    Please fix the SQL injection vulnerability - see stackoverflow.com/questions/60174/… (and preferably switch to using mysqli_* or pdo instead of the obsolete mysql_* functions). Commented Oct 10, 2012 at 4:16

4 Answers 4

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

This can be written so much easier by using $_GET superglobal:

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

Inside checkUserName():

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

You should escape $v properly:

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

Better yet, learn PDO / mysqli and use prepared statements.

$db->disconnectDB();

Unless you're using persistent connections, you don't need this statements. If you do, you should keep the return value inside a variable first and only return after the disconnect.

Sign up to request clarification or add additional context in comments.

Comments

1

I don't know what's your DB class, but this looks prettier.

<?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));

?>

Comments

0

By your way, If you want to process the json data in jquery you can do like this

$.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");

1 Comment

I have the jquery down using $.getJSON()
0

If you want a fix just replace your checkUsername function with this one:

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');

}

Or a simplier way:

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);
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.