在循环中添加到数组

发布于 2024-12-05 09:19:41 字数 850 浏览 2 评论 0原文

如何将数据添加到关联数组?我想使用 jQuery 根据键检索数据。

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

我的问题是:

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

数据库中只剩下最后一行。为什么?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

灯角 2024-12-12 09:19:41

好吧,您正在覆盖该值而不是添加新值。相反,为每个结果构造一个数组,并将这些数组添加到$jsonresult

另外,请确保避免 SQL 注入漏洞

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

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
}
三生池水覆流年 2024-12-12 09:19:41

编辑 首先,我认为您只期望一个结果,因此不需要循环。

其次,您的数据库中有多少用户?您确定它每次都被设置,还是上次运行的残留?尝试这个修改:

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

看看你是否得到“not”和“set”

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"

枉心 2024-12-12 09:19:41

使用 MYSQL_ASSOC 标志

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

,甚至用 mysql_fetch_assoc 代替 mysql_fetch_array,不带任何标志。

编辑:由于您的函数看起来像基本的身份验证函数,我会将其更改为如下所示:

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

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);
寻找一个思念的角度 2024-12-12 09:19:41

您必须为每一行使用一个键:

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

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();
}
年少掌心 2024-12-12 09:19:41

你的代码对我来说毫无意义。
以下似乎足够了

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 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);
}
傾旎 2024-12-12 09:19:41

另一种方法是更改​​查询以仅选择所需的字段(确保清理用户输入!):

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

初始化数组:

$result = array();

然后使用 mysql_fetch_assoc :

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

 echo json_encode($result);

更新:正如@Robert 已经提到的,你实际上应该只得到一个结果,所以不需要循环。

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.

风追烟花雨 2024-12-12 09:19:41

现在,您只有一个一维数组。这意味着每次执行循环时,数组中的这些位置都会被最新值覆盖。您需要一个二维数组(数组的数组),对于您的情况来说非常简单。

更改:

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

至:

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

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'];
桃酥萝莉 2024-12-12 09:19:41
$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++;
}
$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++;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文