php以数组格式从数据库中获取数据

时间:2014-01-16 04:59:11

标签: php sorting arraylist mysqli

我只是php的新手。我有一个数据库,数据库中的数据是这样的

CREATE TABLE IF NOT EXISTS `list` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `data` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;


INSERT INTO `list` (`id`, `data`) VALUES
(1, '5,2,3,4,1');

现在要获取数据我已经使我的php代码像这样

<?php
    $host = 'localhost';
    $username = 'root';
    $password = '';
    $db = 'sortable';

    $link=mysqli_connect($host, $username, $password, $db);

    if (mysqli_connect_errno($link)) {
    echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $query = "SELECT `data` FROM `list`";
    $order = mysqli_query($link, $query);
    print_r($order);
  ?>

这里显示的结果如下

mysqli_result Object ( [current_field] => 0 [field_count] => 1 [lengths] => [num_rows] => 1 [type] => 0 ) 

但是我希望获取值在数组中,并且数组的所需输出将是这样的

   Array([0] => Array([0]=>5,2,3,4,1[data]=>5,2,3,4,1))

有人可以告诉我该怎么做吗?任何帮助和建议都会非常明显。

2 个答案:

答案 0 :(得分:0)

您是否尝试查找找到HERE的php数据库中的mysqli_ *命令?它非常有用。尝试使用mysqli_fetch_array();或者mysqli_fetch_assoc();

使用您的PHP代码的示例可能是:

<?php
$host = 'localhost';
$username = 'root';
$password = '';
$db = 'sortable';

$link=mysqli_connect($host, $username, $password, $db);

if (mysqli_connect_errno($link)) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT `data` FROM `list` WHERE `id` = '1'";
$result = mysqli_query($link, $query);
$data = mysqli_fetch_array($result);
  $numbers = $data['data'];
echo $numbers;
?>

答案 1 :(得分:0)

对于此输出

Array([0] => Array([0]=>5,2,3,4,1)

**Use this**

<?php

    define('HOST', 'localhost');
    define('USER', 'root');
    define('PASS', '');
    define('DBNAME', 'sortable');

    $db = new mysqli(HOST, USER, PASS, DBNAME);

    if ($db->connect_errno) {
    echo "Failed to connect to MySQL: (" 
    . $db->connect_errno . ") " . $db->connect_error;
    }

    $sql = "SELECT `data` FROM `list` WHERE `id` = '1'";
    $result_db = $db->query($sql) or die("Error!");
    $all_result = $result_db->fetch_all();
    print_r($all_result);

    $db->close();
    ?>