繁体   English   中英

PHP获取记录converbaet到二维数组

[英]Php get records converbaet to two dimensional array

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

Example:

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

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

是一个示例,使用PDO和在粘贴本身内部创建的内存SQLite数据库。 不必内联创建数据库会使脚本比严格必要的更加冗长。

尝试这样的事情:

$i = 0;

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

    $i++;
}

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

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

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
}

包含文件并对其进行测试,谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM