1

How can I add data to an associative array? Using jQuery I would like to retrieve data according to a key.

 if(isset($_POST["user_name"]))
 {  
$sql = "SELECT * FROM users WHERE user_name='".$_POST["user_name"]."' AND user_password='".$_POST["user_password"]."'";

$result = mysql_query($sql) or die(mysql_error());

$jsonresult = array();

  while($row = mysql_fetch_array($result))
  {
    
    $jsonresult["user_auth"] = 1;
    $jsonresult["user_id"] = $row['user_id'];
    $jsonresult["user_name"] = $row['user_name'];
    
    $_SESSION["user_auth"] = 1;
    $_SESSION["user_id"] = $row['user_id'];
    $_SESSION["user_name"] = $row['user_name'];
  }

  echo json_encode($jsonresult);
  mysql_close();
  }

My problem is here :

$jsonresult["user_auth"] = 1;
$jsonresult["user_id"] = $row['user_id'];
$jsonresult["user_name"] = $row['user_name'];

There remains only the last row from the database. Why?

2
  • how many rows you expect to be returned by this query? Commented Sep 19, 2011 at 17:56
  • 1
    Are you storing passwords in plain text? EEK!!!! Commented Sep 19, 2011 at 18:02

8 Answers 8

3

Well, you're overwriting the value instead of adding a new one. Instead, construct an array for each result, and add those arrays to $jsonresult.

Also, make sure to avoid SQL Injection vulnerabilities:

$sql = "SELECT * FROM users WHERE user_name='".
       mysql_real_escape_string($_POST["user_name"]) . "' AND " .
       "user_password='". mysql_real_escape_string($_POST["user_password"]) ."'";
$result = mysql_query($sql) or die(mysql_error());
// Or better yet, use PDO and prepared statements

$jsonresult = array();
while (($row = mysql_fetch_array($result)) !== false) {
  $rowresult = array();
  $rowresult["user_auth"] = 1;
  $rowresult["user_id"] = $row['user_id'];
  $rowresult["user_name"] = $row['user_name'];
  $jsonresult[] = $rowresult; // Or array_push($jsonresult, $rowresult);
  // $_SESSION stuff
}
Sign up to request clarification or add additional context in comments.

Comments

2

Edit Firstly, I think you are expecting only one result, so no need for a loop.

Secondly, how many users do you have in your database? Are you sure it's being set each time, or is it residual from the previous run? Try this modification:

$jsonresult = array();
$_SESSION["user_auth"] = -1;
$_SESSION["user_id"] = "not";
$_SESSION["user_name"] = "set";

  while($row = mysql_fetch_array($result))
  {

    $jsonresult["user_auth"] = 1;
    $jsonresult["user_id"] = $row['user_id'];
    $jsonresult["user_name"] = $row['user_name'];

    $_SESSION["user_auth"] = 1;
    $_SESSION["user_id"] = $row['user_id'];
    $_SESSION["user_name"] = $row['user_name'];
  }

and see if you get "not" and "set"

Comments

1

Use MYSQL_ASSOC flag

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $jsonresult[$row['user_id']]["user_auth"] = 1;
    $jsonresult[$row['user_id']]["user_id"] = $row['user_id'];
    $jsonresult[$row['user_id']]["user_name"] = $row['user_name'];

    $_SESSION[$row['user_id']]["user_auth"] = 1;
    $_SESSION[$row['user_id']]["user_id"] = $row['user_id'];
    $_SESSION[$row['user_id']]["user_name"] = $row['user_name'];
}

Or even mysql_fetch_assoc in place of mysql_fetch_array, without any flags.

EDIT: As your function looks like basic autentification function, I would change it to something like this:

$_SESSION["user_auth"] = 0;
$jsonresult = array('user_auth'=>0);
if(isset($_POST["user_name"]) && isset($_POST["user_password"])) {
    $input = array(
        'username'=>htmlspecialchars($_POST["user_name"], ENT_QUOTES),
        'password'=>htmlspecialchars($_POST["user_password"], ENT_QUOTES)
    );
    $query = sprintf("SELECT * FROM users WHERE user_name='%s'", $input['username']);
    $result = mysql_query($query);
    if (mysql_num_rows($result) > 0) {
        $data = mysql_fetch_assoc($result);
        mysql_close();
        if ($data['user_password'] == $input['password']) {
            $jsonresult["user_auth"] = 1;
            $jsonresult["user_id"] = $data['user_id'];
            $jsonresult["user_name"] = $data['user_name'];

            $_SESSION["user_auth"] = 1;
            $_SESSION["user_id"] = $data['user_id'];
            $_SESSION["user_name"] = $data['user_name'];
        }
    }
}
echo json_encode($jsonresult);

1 Comment

mysql_fetch_array without any flags will do fine too.
0

You have to use a key for every row:

$i = 0;
while($row = mysql_fetch_array($result))
{

$jsonresult[$i]["user_auth"] = 1;
$jsonresult[$i]["user_id"] = $row['user_id'];
$jsonresult[$i]["user_name"] = $row['user_name'];

$_SESSION[$i]["user_auth"] = 1;
$_SESSION[$i]["user_id"] = $row['user_id'];
$_SESSION[$i]["user_name"] = $row['user_name'];
$i++;
}

echo json_encode($jsonresult);
mysql_close();
}

Comments

0

your code makes no sense to me.
following seems enough

if(isset($_POST["user_name"])) {  
  $name = mysql_real_escape_string($_POST["user_name"]);
  $pass = mysql_real_escape_string($_POST["user_password"]);
  $sql  = "SELECT user_id,user_name FROM users WHERE user_name='$name' AND user_password='$pass'";
  $res  = mysql_query($sql) or trigger_error(mysql_error());
  $row  = mysql_fetch_assoc($result);

  $_SESSION["user_id"]   = $row['user_id'];
  $_SESSION["user_name"] = $row['user_name'];

  echo json_encode($row);
}

Comments

0

Another way would be to change your query to only select the fields you need (make sure you sanitize user input!):

SELECT 1 as user_auth, user_id, user_name FROM...

Initialize the array:

$result = array();

and then use mysql_fetch_assoc:

while(($row = mysql_fetch_assoc($result))) {
    $result[] = $row;
}
$_SESSION['users'] = $result;

 echo json_encode($result);

Update: As @Robert already mentioned, you actually should only get one result, so there is no need for a loop.

Comments

0

Right now, you only have a 1 dimensional array. That means that each time the loop executes, those locations in the array are overwritten by the latest value. You need a two dimensional array (array of arrays), and it is very simple in your case.

Change:

$jsonresult["user_auth"] = 1;
$jsonresult["user_id"] = $row['user_id'];
$jsonresult["user_name"] = $row['user_name'];

To:

$jsonresult[$i]["user_auth"] = 1;
$jsonresult[$i]["user_id"] = $row['user_id'];
$jsonresult[$i]["user_name"] = $row['user_name'];

1 Comment

Since the down voter did not elaborate I will, this was the same issue as mine. It will create a new index for each item, you need to set the index ID (using $i or the likes) or combine them into a temp array and then append it to the array.
-1
$i=0;

while($row = mysql_fetch_array($result))
{

$jsonresult[$i]["user_auth"] = 1;
$jsonresult[$i]["user_id"] = $row['user_id'];
$jsonresult[$i]["user_name"] = $row['user_name'];

$_SESSION[$i]["user_auth"] = 1;
$_SESSION[$i]["user_id"] = $row['user_id'];
$_SESSION[$i]["user_name"] = $row['user_name'];
$i++;
}

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.