How get all values in a column using PHP? - php

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?
For eg:
Table Name: Customers
Column names: ID, Name
# of rows: 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:
SELECT names FROM Customers
and then use the
mysql_fetch_array
PHP function to store those values in an array.

Here is a simple way to do this using either PDO or 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
$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
)

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.
This would work, see more documentation here :
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.

I would use a mysqli connection to connect to the database. Here is an example:
$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.

Since mysql_* are deprecated, so here is the solution using 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
$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);

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
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
$queryStatment = "SELECT * From USERS ";
$testing = displayAllRecords('localhost','root','root#123','email',$queryStatment);
echo $testing;
Here
localhost indicates Name of the host,
root indicates the username for database
root#123 indicates the password for the database
$queryStatment for generating Query
hope it helps

PHP 5 >= 5.5.0, PHP 7
Use array_column on the result array
$column = array_column($result, 'names');

How to put MySQL functions back into PHP 7
Step 1
First get the mysql extension source which was removed in March:
https://github.com/php/php-src/tree/PRE_PHP7_EREG_MYSQL_REMOVALS/ext/mysql
Step 2
Then edit your php.ini
Somewhere either in the “Extensions” section or “MySQL” section, simply add this line:
extension = /usr/local/lib/php/extensions/no-debug-non-zts-20141001/mysql.so
Step 3
Restart PHP and mysql_* functions should now be working again.
Step 4
Turn off all deprecated warnings including them from 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
$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.
Reference
YOU CAN USE MYSQLI ALTERNATIVE OF 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);
?>

Related

Struggling to output PHP array as unordered HTML list

Apologies as this is probably very basic. I have created a SELECT query and have (I think) stored the data retrieved as an array.
By myself I have been able to use printf to output selected items from the array but I want to output the values in a more structured way, as an unordered list in HTML. It's going to be a list of links. anchor corresponds to the link name column in my MySQL table and link corresponds to the url column, to be output as, e.g
<li>anchor</li>
This is as far as I have got. I know I need a for loop but the demos I've copied keep failing.
Very grateful for any pointers from kind people. Backend is new to me.
<?php
$server = "localhost";
$username = "blah";
$password = "blahblah";
$database = "blah_db";
$conn = mysqli_connect($server, $username, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$result = mysqli_query($conn, "SELECT anchor, link FROM footerLinks");
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
printf("Anchor: %s Link: %s ", $row[0], $row[1]);
}
mysqli_free_result($result);
?>
There is not much to change in your code. Add <ul> and </ul> around the while loop. Change the pattern to <li>%s</li>. And swap $row[0], $row[1] to $row[1], $row[0]:
$result = mysqli_query($conn, "SELECT anchor, link FROM footerLinks");
echo '<ul>';
while ($row = mysqli_fetch_array($result, MYSQLI_NUM)) {
printf('<li>%s</li>', $row[1], $row[0]);
}
echo '</ul>';
I would though use MYSQLI_ASSOC instead of MYSQLI_NUM (which is considered bad practice), and also use the object oriented style for mysqli functions:
$result = $conn->query("SELECT anchor, link FROM footerLinks");
echo '<ul>';
while ($row = $result->fetch_assoc()) {
printf('<li>%s</li>', $row['link'], $row['anchor']);
}
echo '</ul>';

MySQL/PHP - Getting differents rows

Alright, so I have a database, each with an ID, a name and a textvalue.
I wish to be able to print each of a specific row individually. When I use
$result = mysql_query("SELECT * FROM mytable", $db);
$row = mysql_fetch_array($result);
echo $row['text'];
I am only able to print the first row, as it doesn't select any specifics. The problem is, I'm not sure how to use the WHERE ID='X', as I want the first one to print the first column, the second to print the second column and so forth (there are a total of 13 lines). I want to echo them on different places on the page, so just calling everything at once is not what I'm looking for.
The way things are now, I'll have to use the code above for each time I want to print it, and manually edit the WHERE ID='1' on the first print, the second to WHERE ID='2' and so on, which is rather a pain in the ass.
Any suggestions is appreciated.
Keep calling mysql_fetch_array until it returns null:
while($row = mysql_fetch_array($result ))
{
echo $row['text'] . '<br/>';
}
This is shown in the documentation, which also will tell you this:
Warning
This extension is deprecated as of PHP 5.5.0, and will be removed in the future. Instead, the MySQLi or PDO_MySQL extension should be used. See also MySQL: choosing an API guide and related FAQ for more information. Alternatives to this function include:
Here's an example using a more object-oriented approach:
1) setup a PDO object like this:
$dbhost = '127.0.0.1';
$dbuser = 'yourDbUsername';
$dbpass = 'yourDbPassword';
$dbname = 'databaseName';
$dsn = 'mysql:host=' . $dbhost . ';dbname=' . $dbname;
$dbAdapter = new PDO($dsn,$dbuser,$dbpass);
$dbAdapter->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
$dbAdapter->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
2) use PDO objects to run queries and fetch result sets:
$sql = 'SELECT * FROM mytable';
$statementObject = $dbAdapter->query($sql);
$resultSet = $statementObject->fetchAll();
3) iterate over the resulting array:
foreach($resultSet as $row){
echo $row['text'] . "<br />";
}
This is how to iterate through all records.
$result = mysql_query("SELECT text FROM mytable", $db);
while ( $row = mysql_fetch_array($result) ) {
echo $row['text'];
}
$i = 1;
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
while ($row = mysql_fetch_array($result, MYSQL_NUM)) {
echo $i . ' - ' . $row[0] . '<br/>';
$i++
}
If you want 4 variables with the text to use in differents part of your code then use:
$result = mysql_query("SELECT text FROM mytable WHERE ID > 0 AND ID < 5", $db);
$var1 = mysql_fetch_array($result, MYSQL_NUM);
echo $var1[0];
$var2 = mysql_fetch_array($result, MYSQL_NUM);
echo $var2[0];
$var3 = mysql_fetch_array($result, MYSQL_NUM);
echo $var3[0];
$var4 = mysql_fetch_array($result, MYSQL_NUM);
echo $var4[0];

Setting PHP variables from Database Using MYSQL

Looking to select multiple values from the database and echo with PHP. (Newbie)
For instance:
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 4
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 5
SELECT sponser, contract, script FROM Copy WHERE day = '11092014' and time = 6
How would I set the variables.. something along the lines of this using MYSQLi for multiple variables?
$sqlStremail = "SELECT subcheckr
FROM login
WHERE username = '$u'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$variable = $row["subcheckr"];
Truly appreciate any help.
Yes. Though if your query returns multiple rows, you'll need to use:
while ($row = mysqli_fetch_assoc($result))
{
//do something here
}
you need to make a loop for , foreach or a while loop
ex
while ($row = mysqli_fetch_assoc($result))
{
}
This should do it. First you need to connect, then you build your query. If query fails display an error so you know what went wrong. Then build your data array and use it.
$db = mysql_connect("localhost", "mysql_user", "mysql_password");
$sqlStremail = "SELECT `subcheckr`
FROM `login`
WHERE `username` = '".$u."'"; //needs to be concatenated
$result = mysql_query($sqlStremail, $db);
if(!$result) {
echo "query failed:". mysql_error();
exit;
}
$data = array();
while ($row = mysql_fetch_assoc($result)) {
$data = $row;
}
echo $data['sponsor'];
echo $data['contact'];
echo $data['script'];
//etc

MySQL column values to array. Wrong values as a result

Trying to get all the values from a single column.
After all simply trying to print all the values to check if everything is OK. Unfortunately all the values I get printed are the same - "Array" (without quotes).
I am quite new working with MySQL. Here is my code:
$sql_connect = mysql_connect("localhost","db_user_name","db_password") ;
if (!$sql_connect) {
die("Database connection failed: " . mysql_error());
}
mysql_select_db("db_name") or die ("no database");
$result = mysql_query("SELECT column_name FROM table_name");
$video_IDs = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$video_IDs[] = $row[$key];
}
then, I print the $video_IDs array
$test = 1 ;
while (each($video_IDs)) {
echo "{$test} - {$video_IDs}<br />" ;
$test++ ;
}
mysql_close($sql_connect);
As a result i get printed all 10 values as 10 row are in my table. But all the values are "Array" (without quotes).
My result:
1 - Array
2 - Array
3 - Array
4 - Array
5 - Array
6 - Array
7 - Array
8 - Array
9 - Array
10 - Array
Looking forward to get any suggestions.
There is no native way to echo an array without using a loop or recursion or accessing a specific element of said array. You're using the each function improperly as well since it returns a key/value pair as a result (and you're not capturing that result for the loop.) You should do something like this instead:
$test = 1 ;
foreach ($video_IDs as $v) {
echo "{$test} - {$v}<br />";
$test++;
}
If you must use each, here's a slight change to your original code so that the key/value pair is stored in $v over every iteration
$test = 1 ;
while ($v = each($video_IDs)) {
echo "{$test} - {".$v['value']."}<br />" ;
$test++ ;
}
If you're just trying to display the array without any specific formatting, use var_dump or print_r
It is also necessary to note that you're using a depreciated function (mysql_*) and you should use MySQLi or PDO for your SQL queries.
If $video_IDs is an array, you need to use print_r or loop through each element. The code below will output the data you are
$test = 1 ;
foreach( $video_IDs as $key => $value) {
if( is_array($value) ){
echo "$test $key =>";
print_r($value);
echo "<br/>";
}else{
echo "$test $key => $value <br/>";
}
$test++ ;
}
if you want to print array content then use print_r(array_name)
Best way to see the content is
echo "<pre>";
print_r(array_name);
echo "</pre>";
Solution found
Thank you for suggestions and pointing the depreciated function (mysql_*). I have changed the connection to MySQL DB functions and everything else and now i have a proper results.
$link = mysqli_connect('localhost', 'username', 'password', 'db_name');
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT column_name FROM table_name";
$result = mysqli_query($link,$query);
while ($video_IDs = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$rows[] = $video_IDs ;
}
foreach($rows as $video_IDs)
{
echo $video_IDs['column_name']."<br />";
}
Thank you all for comments!

Simple php mysql query returns only one of two columns

I'm a PHP and MySQL newbie trying to write a simple query against a table consisting of 2 columns: one with a text string and the second with a date string. The code below returns the first column (the text string) but not the second date string:
<?php
$link = mysql_connect('localhost', 'myuser', 'mypassword');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('archive')or die("cannot select db");
$string = $_POST['keywords'];
$search_query = "SELECT text, date_written FROM archive_table WHERE text LIKE '%$string%'";
$result = mysql_query($search_query,$link);
$rows = mysql_num_rows($result);
if ($rows == 0) {
echo "sorry, I haven’t written about ".$string." yet.";
}
$count = 0;
while ($count < $rows) {
echo mysql_result($result, $count);
echo "\n\n";
$count = $count + 1;
}
mysql_close($link);
?>
I've tried the following code to replace "echo mysql_result($result, $count);", but it returns nothing at all:
echo mysql_result($result['text'], $result['date_written'], $count);
I'm hoping it's a fairly simple syntax blunder that is easily fixed. Thanks in advance!
Don't use the mysql_* functions, as they're deprecated and not safe. Use either MySQLi or PDO
You also need to fetch your results:
$query = "blah"
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)) {
echo "{$row['text']}, {$row['date_written]}";
}
I'm pretty sure this
echo mysql_result($result['haiku_text'], $result['date_written'], $count);
should be
echo mysql_result($result['text'], $result['date_written'], $count);
You have a prefix in front of the text field but it doesn't have one when you select it.

Categories