Jenan
Jenan

Reputation: 3320

Add to array in loop

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?

Upvotes: 1

Views: 7657

Answers (8)

Chris
Chris

Reputation: 1579

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

Upvotes: 0

Deele
Deele

Reputation: 3684

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

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816364

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.

Upvotes: 0

Your Common Sense
Your Common Sense

Reputation: 157839

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

Upvotes: 0

Rahul Kanodia
Rahul Kanodia

Reputation: 105

$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++;
}

Upvotes: -1

Bluewind
Bluewind

Reputation: 1064

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

Upvotes: 0

phihag
phihag

Reputation: 287815

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
}

Upvotes: 3

Robert Martin
Robert Martin

Reputation: 17157

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"

Upvotes: 2

Related Questions