如何从MySQL获取和组合数据,然后在PHP中插入到数组中
This question is quite specific for my needs, hence I can't find the best way to do this.
What I would like to do is fetch name
and surname
from the table people
and combine both into an array to end up with such results:
"Bob Jones","Tony Wright",
.. etc.
I'm using PDO for this. Here is what I have:
$attrs = array(PDO::ATTR_PERSISTENT => true);
// connect to PDO
$pdo = new PDO("mysql:host=localhost;dbname=new", "root", "root", $attrs);
// the following tells PDO we want it to throw Exceptions for every error.
// this is far more useful than the default mode of throwing php errors
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn = $pdo->prepare("SELECT name, surname FROM people");
$conn->execute();
$results = $conn->fetchAll();
foreach($results as $row){
$fullName = $row['name'] . "," . $row['surname'];
print_r($fullName);
}
I have tried a few things, I'm just stuck with this code at minute. Any help, or suggestions is much appreciated.
这个问题非常符合我的需求,因此我找不到最佳方法。 p>
我想要做的是从表 我正在使用PDO。 这就是我所拥有的: p>
我尝试了一些事情,我只是卡住了 这个代码在分钟。 任何帮助或建议都非常感谢。 p>
div> people code>中获取
name code>和
surname code>并将它们组合成一个 数组最终得到这样的结果: p>
“Bob Jones”,“Tony Wright”, code>等等。 p>
$ attrs = array(PDO :: ATTR_PERSISTENT => true);
//连接到PDO
$ pdo = new PDO(“mysql:host = localhost; dbname = new”,“root”,“root”,$ attrs);
//以下告诉PDO我们希望它为每个错误抛出异常。
// 这比抛出php错误的默认模式更有用
$ pdo-> setAttribute(PDO :: ATTR_ERRMODE,PDO :: ERRMODE_EXCEPTION);
$ conn = $ pdo-> prepare(“SELECT name” ,姓氏来自人们“);
$ conn-> execute();
$ results = $ conn-> fetchAll();
foreach($ results as $ row){
$ fullName = $ row ['name']。 “,”。 $ row ['surname'];
print_r($ fullName);
}
code> pre>
$arr = array();
foreach($results as $row) {
$arr[] = "{$row['name']},{$row['surname']}";
}
echo implode($arr);
Once you’ve fetched the rows from the database, you need to loop over the result set and assign the combined name to a new array:
<?php
// result set from database
$results = $conn->fetchAll();
// create an empty array to store our names
$names = array();
// loop over result set and add entry to $names array
foreach ($results as $result) {
$names[] = $row['name'] . ' ' . $row['surname'];
}
print_r($names);
$fullname =array();
foreach($results as $row){
$fullName = $row['name'] . " " . $row['surname'];
}
print_r($fullname);
You can also resolve this problem in SQL, so foreach would not be needed any more.
Just replace
SELECT name, surname FROM people
with
SELECT CONCAT_WS(' ', name, surname) FROM people