PHP使mySQL查询显示为数组

时间:2014-04-03 18:24:27

标签: php

我有这个数组:

$urls = array(
    0 => array('url' => 'phpclasses.org', 'keyword' => 'phpclass'),
    1 => array('url' => 'phpclasses.org', 'keyword' => 'php'),
    2 => array('url' => 'php.com', 'keyword' => 'php')
);

我的问题是我想将上面的数据替换为我从数据库中获取的数据。

我有一个包含以下字段的表:

id(auto), url and keyword.

然后我连接到数据库:

$con=mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

$result = mysqli_query($con,"SELECT * FROM my_table");

我的问题是如何创建一个mysqli查询来获取上面数组格式的数据?

2 个答案:

答案 0 :(得分:1)

以下代码复制了您的数组,数组的索引是数据库中的id字段,其他值在数组内部。

<?php
$con = mysqli_connect("localhost","root","","my_db");
// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}

$result = mysqli_query($con, "SELECT * FROM my_table");

$urls = array();

while ($row = mysqli_fetch_array($result)) {
  $urls[$row['id']] = array('url' => $row['url'], 'keyword' => $row['keyword']);
}

var_dump($urls);
?>

答案 1 :(得分:0)

试试这个

<?php
mysql_connect("localhost", "username", "password");
mysql_select_db("DATABASE");

$urls = array();

$query = mysql_query("SELECT * FROM YOUR_TABLE");

while($row = mysql_fetch_array($query)) {
$urls[] = array('url' => $row['url'], 'keyword' => $row['keyword']);
}

var_dump($urls);
?>

使用您的代码:

<?php
$con=mysqli_connect("localhost","root","","my_db");
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }
$result = mysqli_query($con,"SELECT * FROM my_table");

$urls = array();

while($row = mysql_fetch_array($result)) {
$urls[] = array('url' => $row['from_id'], 'keyword' => $row['to_id']);
}

var_dump($urls);
?>

如果答案有帮助,请投票。