0

我想从数据库中获取记录而不是转换为二维数组。

Example:

$data = array(
        1 => array ('Name', 'Surname','sex','address','web'),
        array('Schwarz', 'Oliver','M','KP','222.dddd'),
        array('Test', 'Peter','F','KK','wwww.fsadfs')
        );

如上例所示,如何格式化数据库中的数据?

4

3 回答 3

0

尝试这样的事情:

$i = 0;

foreach( $results as $result )
{
    $array[$i]['field1'] = $results['field1'];
    $array[$i]['field2'] = $results['field2'];

    $i++;
}

根据您用于访问数据库的库,它可能会略有不同。

于 2013-02-19T15:57:51.170 回答
0

是一个示例,使用 PDO 和在粘贴本身内部创建的内存 SQLite 数据库;必须在线创建数据库使脚本比严格必要的要冗长一些。

于 2013-02-19T15:56:33.767 回答
0

这是您创建函数的答案,返回多个数组

public static function getRecords($query){  // Gets multiple records and    returns associative array
    $db = db::open();
    $result = $db->query($query);
    if(!$result){
        die('There was an error running the query [' . $db->error . ']');
    }
    if($result->num_rows>0){
        $i=0;
        while ($row = $result->fetch_assoc()){
            $recordset[$i] = $row;
            $i++;
            }
        }else{
            $recordset = false;
        }
    db::close($db);
    return ($recordset);
}

你只需像这样传递查询

 $QUERY="select * FROM USERS";


AND CREATE class db to open the connection and also add function in this class and your function is ready 



    class db{
    public static function open(){ // opens the db connection. Specify different databases for local and live server and it will automatically select the correct one

       $servers = array('localhost', '127.0.0.1', 'warrior');
        if(in_array($_SERVER['HTTP_HOST'], $servers)){ //for localhost
            $dbuser = 'root';
            $dbpwd = '';
            $dbname = 'database name';
            $dbserver = 'localhost';
        }
        $db = mysqli_connect($dbserver,$dbuser,$dbpwd,$dbname);
        if ($db->connect_errno > 0){
          echo "Failed to connect to MySQL: " . $db->connect_error;
          }
         return $db;
        }

    public static function close(&$db){
        $db->close();
    } //also add your Get_record function here
}

包含文件并测试它谢谢

于 2017-01-30T08:20:17.037 回答