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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Jenan
  • 3,408
  • 13
  • 62
  • 105

8 Answers8

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
}
Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
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"

Robert Martin
  • 16,759
  • 15
  • 61
  • 87
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);
Deele
  • 3,728
  • 2
  • 33
  • 51
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();
}
Bluewind
  • 1,054
  • 7
  • 10
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'];
Chris
  • 1,569
  • 2
  • 11
  • 18
  • 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. – Jim Sep 19 '11 at 18:06
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.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
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);
}
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
-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++;
}
Jim
  • 18,673
  • 5
  • 49
  • 65
Rahul Kanodia
  • 105
  • 12