如何使用 PHP 获取列中的所有值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5229501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How get all values in a column using PHP?
提问by Gbert90
I've been searching for this everywhere, but still can't find a solution: How do I get all the values from a mySQL column and store them in an array?
我一直在到处寻找这个,但仍然找不到解决方案:如何从 mySQL 列中获取所有值并将它们存储在数组中?
For eg: Table Name: Customers Column names: ID, Name # of rows: 5
例如:表名称:客户列名称:ID,名称行数:5
I want to get an array of all the 5 names in this table. How do I go about doing that? I am using PHP, and I was trying to just:
我想得到这个表中所有 5 个名字的数组。我该怎么做?我正在使用 PHP,我只是想:
SELECT names FROM Customers
and then use the
然后使用
mysql_fetch_array
PHP function to store those values in an array.
PHP 函数将这些值存储在数组中。
采纳答案by DhruvPathak
Note that this answer is outdated!The mysql extension is no longer available out of the box as of PHP7. If you want to use the old mysql functions in PHP7, you will have to compile ext/mysql from PECL.See the other answers for more current solutions.
请注意,此答案已过时!从 PHP7 开始,mysql 扩展不再是开箱即用的。如果你想在 PHP7 中使用旧的 mysql 函数,你必须从 PECL 编译 ext/mysql。有关更多当前解决方案,请参阅其他答案。
This would work, see more documentation here : http://php.net/manual/en/function.mysql-fetch-array.php
这会起作用,请在此处查看更多文档:http: //php.net/manual/en/function.mysql-fetch-array.php
$result = mysql_query("SELECT names FROM Customers");
$storeArray = Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['names'];
}
// now $storeArray will have all the names.
回答by Félix Gagnon-Grenier
Here is a simple way to do this using either PDOor mysqli
$stmt = $pdo->prepare("SELECT Column FROM foo");
// careful, without a LIMIT this can take long if your table is huge
$stmt->execute();
$array = $stmt->fetchAll(PDO::FETCH_COLUMN);
print_r($array);
or, using mysqli
或者,使用 mysqli
$stmt = $mysqli->prepare("SELECT Column FROM foo");
$stmt->execute();
$array = [];
foreach ($stmt->get_result() as $row)
{
$array[] = $row['column'];
}
print_r($array);
Array
(
[0] => 7960
[1] => 7972
[2] => 8028
[3] => 8082
[4] => 8233
)
回答by Krijn Toet
I would use a mysqli connection to connect to the database. Here is an example:
我会使用 mysqli 连接来连接到数据库。下面是一个例子:
$connection = new mysqli("127.0.0.1", "username", "password", "database_name", 3306);
The next step is to select the information. In your case I would do:
下一步是选择信息。在你的情况下,我会这样做:
$query = $connection->query("SELECT `names` FROM `Customers`;");
And finally we make an array from all these names by typing:
最后,我们通过键入以下所有名称创建一个数组:
$array = Array();
while($result = $query->fetch_assoc()){
$array[] = $result['names'];
}
print_r($array);
So what I've done in this code: I selected all names from the table using a mysql query. Next I use a while loop to check if the $query has a next value. If so the while loop continues and adds that value to the array '$array'. Else the loop stops. And finally I print the array using the 'print_r' method so you can see it all works. I hope this was helpful.
所以我在这段代码中做了什么:我使用 mysql 查询从表中选择了所有名称。接下来我使用一个 while 循环来检查 $query 是否有下一个值。如果是这样,while 循环将继续并将该值添加到数组 '$array' 中。否则循环停止。最后我使用 'print_r' 方法打印数组,以便您可以看到一切正常。我希望这可以帮到你。
回答by A J 9
Since mysql_*are deprecated, so here is the solution using mysqli.
由于mysql_*已弃用,因此这里是使用mysqli的解决方案。
$mysqli = new mysqli('host', 'username', 'password', 'database');
if($mysqli->connect_errno>0)
{
die("Connection to MySQL-server failed!");
}
$resultArr = array();//to store results
//to execute query
$executingFetchQuery = $mysqli->query("SELECT `name` FROM customers WHERE 1");
if($executingFetchQuery)
{
while($arr = $executingFetchQuery->fetch_assoc())
{
$resultArr[] = $arr['name'];//storing values into an array
}
}
print_r($resultArr);//print the rows returned by query, containing specified columns
There is another way to do this using PDO
还有另一种方法可以使用PDO做到这一点
$db = new PDO('mysql:host=host_name;dbname=db_name', 'username', 'password'); //to establish a connection
//to fetch records
$fetchD = $db->prepare("SELECT `name` FROM customers WHERE 1");
$fetchD->execute();//executing the query
$resultArr = array();//to store results
while($row = $fetchD->fetch())
{
$resultArr[] = $row['name'];
}
print_r($resultArr);
回答by Manojkiran.A
First things is this is only for advanced developers persons Who all are now beginner to php dont use this function if you are using the huge project in core php use this function
首先,这仅适用于高级开发人员 如果您正在使用核心 php 中的大型项目,请不要使用此功能,如果您现在是 php 的初学者,请使用此功能
function displayAllRecords($serverName, $userName, $password, $databaseName,$sqlQuery='')
{
$databaseConnectionQuery = mysqli_connect($serverName, $userName, $password, $databaseName);
if($databaseConnectionQuery === false)
{
die("ERROR: Could not connect. " . mysqli_connect_error());
return false;
}
$resultQuery = mysqli_query($databaseConnectionQuery,$sqlQuery);
$fetchFields = mysqli_fetch_fields($resultQuery);
$fetchValues = mysqli_fetch_fields($resultQuery);
if (mysqli_num_rows($resultQuery) > 0)
{
echo "<table class='table'>";
echo "<tr>";
foreach ($fetchFields as $fetchedField)
{
echo "<td>";
echo "<b>" . $fetchedField->name . "<b></a>";
echo "</td>";
}
echo "</tr>";
while($totalRows = mysqli_fetch_array($resultQuery))
{
echo "<tr>";
for($eachRecord = 0; $eachRecord < count($fetchValues);$eachRecord++)
{
echo "<td>";
echo $totalRows[$eachRecord];
echo "</td>";
}
echo "<td><a href=''><button>Edit</button></a></td>";
echo "<td><a href=''><button>Delete</button></a></td>";
echo "</tr>";
}
echo "</table>";
}
else
{
echo "No Records Found in";
}
}
All set now Pass the arguments as For Example
现在全部设置 将参数作为 For Example
$queryStatment = "SELECT * From USERS "; $testing = displayAllRecords('localhost','root','root@123','email',$queryStatment); echo $testing;
$queryStatment = "SELECT * From USERS"; $testing = displayAllRecords('localhost','root','root@123','email',$queryStatment); 回声 $testing;
Here
这里
localhost
indicates Name of the host
,
localhost
表示名称host
,
root
indicates the username for database
root
表示用户名 database
root@123
indicates the password for the database
root@123
表示 password for the database
$queryStatment
for generating Query
$queryStatment
为了 generating Query
hope it helps
希望能帮助到你
回答by Parth Chavda
How to put MySQL functions back into PHP 7
Step 1
如何将 MySQL 函数放回 PHP 7
Step 1
First get the mysql extension source which was removed in March:
首先获取三月份删除的mysql扩展源:
https://github.com/php/php-src/tree/PRE_PHP7_EREG_MYSQL_REMOVALS/ext/mysql
https://github.com/php/php-src/tree/PRE_PHP7_EREG_MYSQL_REMOVALS/ext/mysql
Step 2
第2步
Then edit your php.ini
然后编辑你的 php.ini
Somewhere either in the “Extensions” section or “MySQL” section, simply add this line:
在“扩展”部分或“MySQL”部分的某处,只需添加以下行:
extension = /usr/local/lib/php/extensions/no-debug-non-zts-20141001/mysql.so
Step 3
第 3 步
Restart PHP and mysql_* functions should now be working again.
重新启动 PHP 和 mysql_* 函数现在应该可以再次工作了。
Step 4
第四步
Turn off all deprecated warnings including them from mysql_*:
关闭所有已弃用的警告,包括来自 mysql_* 的警告:
error_reporting(E_ALL ^ E_DEPRECATED);
Now Below Code Help You :
现在下面的代码可以帮助您:
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$Data[] = $row['names'];
}
You can also get all values in column using mysql_fetch_assoc
您还可以使用 mysql_fetch_assoc
$result = mysql_query("SELECT names FROM Customers");
$Data= Array();
while ($row = mysql_fetch_assoc($result))
{
$Data[] = $row['names'];
}
This extension was deprecated in PHP 5.5.0, and it was removed in PHP 7.0.0. Instead, the MySQLi or PDO_MySQL extension should be used.
这个扩展在 PHP 5.5.0 中被弃用,在 PHP 7.0.0 中被移除。相反,应使用 MySQLi 或 PDO_MySQL 扩展。
YOU CAN USE MYSQLI ALTERNATIVE OF MYSQL EASY WAY
你可以使用 MYSQLI 替代 MYSQL EASY WAY
*
*
<?php
$con=mysqli_connect("localhost","my_user","my_password","my_db");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="SELECT Lastname,Age FROM Persons ORDER BY Lastname";
$result=mysqli_query($con,$sql);
// Numeric array
$row=mysqli_fetch_array($result,MYSQLI_NUM);
printf ("%s (%s)\n",$row[0],$row[1]);
// Associative array
$row=mysqli_fetch_array($result,MYSQLI_ASSOC);
printf ("%s (%s)\n",$row["Lastname"],$row["Age"]);
// Free result set
mysqli_free_result($result);
mysqli_close($con);
?>