-1

我正在尝试使用 PHP 和 MySQL 创建一个数组,但我总是出错。

我正在使用的代码

function db_listar_usuarios(){
$link=db_connect();
$query = "select * from usuarios" or die("Problemas en el select: " . mysqli_error($link));
$result = $link->query($query);
  while($row = mysqli_fetch_assoc($result)) {   
        echo $row['nombre'] . array(;
        foreach ($row as $col => $val) {
           $col => $val;
        }
        echo "\n\n############\n";
    }
}

我想用这段代码创建的是:

array(
    'john' => array('address' => 'st 123', 'age' => '25', 'surname' => 'doe'),
    'ane' => array('address' => 'av 456', 'age'=> '32', 'surname' => 'smith'),
);

然后像这样使用:

private $contacts = db_listar_usuarios();

先感谢您 :)

4

2 回答 2

1
function db_listar_usuarios(){
$link=db_connect();
$query = "select * from usuarios" or die("Problemas en el select: " . mysqli_error($link));
$result = $link->query($query);
  while($row = mysqli_fetch_assoc($result)) {   
        echo $row['nombre'] . array(; // <- invalid in several ways
        foreach ($row as $col => $val) {
           $col => $val;
        }
        echo "\n\n############\n";
    }
}

尝试:

function db_listar_usuarios(){
    $link = db_connect();
    $query = "select * from usuarios" or die("Problemas en el select: " . mysqli_error($link));
    $result = $link->query($query);
    $myArray = array();
    while($row = mysqli_fetch_assoc($result)) {   
        $myArray[] = $row;
        print_r($myArray); // for debugging
        echo "\n\n############\n";
    }
    return $myArray;
}
于 2013-11-07T17:29:33.453 回答
1
$users = array();
while($row = mysqli_fetch_assoc($result)) {            
    foreach ($row as $col => $val) {
        $users[$col] = $val;
    }
}
print_r($users);
于 2013-11-07T17:30:16.627 回答