4

如何在 mysql 中通过所需的列名设置 sql 结果索引值?例如

表名:国家

+-----------+----------------+--------------------+
|   id      |     code       |   name             |
+-----------+----------------+--------------------+
|    1      |       88       |   Bangladesh       |
+-----------+----------------+--------------------+
|    2      |      966       |   Saudi Arabia     |
+-----------+----------------+--------------------+
|    3      |      967       |   Yemen            |
+-----------+----------------+--------------------+
|    4      |      963       |   Syria            |
+-----------+----------------+--------------------+
|    5      |      249       |   Sudan            |
+-----------+----------------+--------------------+

创建表查询如下:

CREATE TABLE `country` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `code` int(20) NOT NULL,
  `name` varchar(50) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=latin1;

并将数据插入表如下:

insert  into `country`(`id`,`code`,`name`) values (1,88,'Bangladesh'),
(2,966,'Saudi Arabia'),(3,967,'Yemen'),(4,963,'Syria'),(5,249,'Sudan');

结果将显示如下:

如果我执行以下查询和我想要的结果如下:

select code, name from country order by code ;

期望的结果:

[88] => Array
    (
        [code] => 88,
        [name] =>  Bangladesh            
    )

[249] => Array
    (
        [code] => 249,
        [name] =>  Sudan            
    )

[963] => Array
    (
        [code] => 963,
        [name] => Syria
    )

[966] => Array
    (
        [code] => 966,
        [name] => Saudi Arabia
    )

[967] => Array
    (
        [code] => 967,
        [name] => Yemen
    )

我需要的数组键将是直接 SQL 查询的代码。可能吗?

4

3 回答 3

3

PDO使用、它的PDOStatement::fetchAll()方法和使用该功能所需的键的构建非常容易做到这一点array_column(),如以下步骤所述:

  1. 使用 DSN、用户名和密码连接到数据库。
  2. 查询数据库。
  3. 操纵结果。

代码可能如下所示:

const DB_DSN = "mysql:host=mysql.hostname.com;dbname=yourdb;port=3306";
const DB_USERNAME = "username";
const DB_PASSWORD = "P4ssW0rd!";

try
{
    $db = new PDO(DB_DSN, DB_USERNAME, DB_PASSWORD, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
    $results = $db->query("SELECT code, name FROM country ORDER BY code")->fetchAll(PDO::FETCH_ASSOC);
    $results = array_column($results, null, "code");
}
catch ( PDOException $e )
{
    throw new Exception("An error occurred during the interaction with the database (" . DB_DSN . ").", 0, $e);
}

var_dump($results);

这将为您提供您想要的输出。

于 2016-12-23T16:34:04.477 回答
1

这是一个读取结果的简单循环:

$result = mysqli_query($db,$query);

$array = array();
while ($row = mysqli_fetch_assoc($result)) {
    $array[$row['code']] = $row;
}
于 2013-11-06T14:42:26.713 回答
0
    $servername = "localhost";
    $username = "root";
    $password = "root";

    // Create connection
    $conn = mysqli_connect($servername, $username, $password,'test');


    // Check connection
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }else{

       $query = 'SELECT code, name FROM country ORDER BY code';
       $result = mysqli_query($conn,$query);
       $result = mysqli_fetch_all($result,MYSQLI_ASSOC);           
       $result = array_column($result, null, "code");
        echo "<pre>"; print_r($result);
    }
于 2017-03-01T08:22:35.347 回答