从mysql查询中获取php数组的结果

时间:2016-07-27 17:01:14

标签: php mysql arrays

我的数据库包含表user - >字段 - > usernameuserid

    $user = (" SELECT userid,username FROM user ");
    while ($row = @mysql_fetch_assoc( $user) )
    {
   $getalluser[] = $row;
    }

我试着像这样得到数组:

$users = array(
 0=>array(
  "Mark",
  "http://localhost/test/image.php?u=1",
  "Mark"
 ),
 1=>array(
  "Anandu",
  "http://localhost/test/image.php?u=2",
  "anandu"
 ),
  2=>array(
  "jeena",
  "http://localhost/test/image.php?u=3",
  "jeena"
 )
);

注意:

Mark,Anandu,jeena - >用户名和u=1,u=2,u=3 - >用户ID

1 个答案:

答案 0 :(得分:0)

我安装了PHP7,因此我无法使用您正在使用的mysql_xxx函数(不推荐使用它们)。我必须使用mysqli_xxx函数来测试下一个代码:

<?php
$cnx = mysqli_connect( "localhost", "root", "pass", "databasename" );
$data = mysqli_query( $cnx, "SELECT userid,username FROM user" );
$getalluser = array();
while ( $row = mysqli_fetch_array( $data ) )
  $getalluser[] = array( $row[ "username" ],
                         "http://localhost/test/image.php?u=" . $row[ "userid" ],
                         $row[ "username" ] );
var_dump( $getalluser );
?>

while之前创建一个空数组。在while数组中填充了数组,这些数组每个包含3个项目:用户名为第一项和第三项,URL为第二项。第二个项目最后连接了userid