MySQL column values to array. Wrong values as a result - php

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!

Related

PHP Count Showing 2 Elements in Array, For Loop Loops 4 Times

I have an array that I want to loop through. Using:
echo count($places);
I get a value of 2. Similar print_r the array gives 2 items.
However, when i run a for loop it seems to go through 4 iterations. This can be seen by adding echo $i to the loop, which produces an output of 0,1,2,3.
This is my code:
function enrichfromDB($places) {
$con = mysqli_connect("localhost","user","password","db1");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
echo count($places);
print_r($places);
for ($i=0 ; $i<count($places) ; $i++) {
echo $i;
$name = $places[$i]['name'];
$gettag = "SELECT Tag FROM PlaceTags WHERE Name = '$name'";
$data = mysqli_query($con,$gettag);
while($row = mysqli_fetch_assoc($data)) {
$tags[] = $row['Tag'];
}
$places[$i]['category_labels'][0][] = $tags[$i];
}
return $places;
}
count($places)
has a value of 2.
However, with the row of
$places[$i]['category_labels'][0][] = $tags[$i];
you are creating new elements inside your places array. Initially you had two elements, but some of the indexes you are using are not existent in the array, so they are created. Take a closer look at your array to solve your problem.

storing entire elements which are fetch in a sql query

Actually I am very new to PHP.
My code goes here:
<?php
$mysql = mysql_connect('localhost','Susi','susi');
mysql_select_db('mydb', $mysql);
$rs = mysql_query("show tables;");
$nonTable = array('table_1','table_2');
while ($tabs = mysql_fetch_assoc($rs)) {
foreach ($tabs as $tables) {
echo $tables.'<br />';
}
}
?>
In this case $rs stores the entire table of the database "mydb" .
There is another array $nontable which contains some tables which are already in Table list of "mydb" database.
I want to pass those table names to the while loop excluding the tables in "$nontable" array.
I tried
array_diff($rs,$nontable)
but it provided NULL result.
I will be very happy if somebody helps me out...
Thanks in advance...
Do you mean:
while ($tabs = mysql_fetch_assoc($rs)) {
foreach ($tabs as $tables) {
if(!in_array($tables, $nonTable)) {
echo $tables."<br />";
}
}
}
Your $rs does not contain any result... It contains the resource id
hence it outputs you NULL for array difference.
Your variable $tabs which you are iterating in while loop, is the
associative array with value
Now if you want those tables names which are NOT in $nontable array
then you have to do this
while ($tabs = mysql_fetch_assoc($rs)) {
foreach ($tabs as $tables) {
if(!in_array($tables, $nonTable)) {
echo $tables."<br />";
}
}
}
You can't do array_diff($rs,$nontable) because $rs is not an array, so you need to do it in such way:
<?php
$mysql = mysql_connect('localhost','Susi','susi');
mysql_select_db('mydb', $mysql);
$rs = mysql_query("show tables;");
$nonTable = array('table_1','table_2');
while ($tabs = mysql_fetch_array($rs)) {
$diff = array_diff($tabs, $nontable)
foreach ($diff as $tables) {
echo $tables.'<br />';
}
}
EDITED: also you need to use mysql_fetch_array instead of mysql_fetch_assoc
As #Sudhir said, you can use in_array() function in PHP. This function search your expected item through an array and will return True if it can find it. So using the code that #Sudhir suggested, will work for you as you want.
To know more about in_array() function, see http://php.net/manual/en/function.in-array.php

PHP For Loop Printing An Array

This might seem like a really easy question but it has got me stumped lol. I am trying to print the rows received from the database. I want to store the rows inside an array and then print them using a for loop. I know that the query works however when I try to print the array elements it only prints the word array. I have tired doing it with a foreach loop and a simple for loop. If anyone can point me in the right direction would be a life saver.
Printing Php Code
<?php
$type = "FREE";
$free = getTerms($type);
echo "<p>";
for($j = 0; $j < count($free); $j++)
{
echo "start".$free[$j]."end";
}
echo "</p>";
?>
geting the rows from the database
function getTerms($type)
{
$terms = array();
$connection = mysql_open();
$query = "select terms from terms_and_con where accountType='$type' && currentTerms='YES'";
$results = mysql_query($query, $connection) or show_error("signUp.php", "", "");
while($row = mysql_fetch_array($results))
{
$terms[] = $row;
}
mysql_close($connection) or show_error("signUp.php", "", "");
return $terms;
}
Each entry in the $free array is itself an array (from $row).
Try
echo 'start', $free[$j]['terms'], 'end';
Alternatively, you may find a foreach loop more semantically appropriate
foreach ($free as $row) {
echo 'start', $row['terms'], 'end';
}
Edit: I'd advise using mysql_fetch_assoc() instead of mysql_fetch_array() if you're only going to use associative entries from $row.
the thing is function mysql_fetch_array ( as the name suggests) returns an ( in your case both associative and number) array. so $row is actually array(0 => VALUE, 'terms' => 'VALUE')
So what you are trying to echo is actually an array.
Simple fix:
replace:
$terms[] = $row;
with:
$terms[] = $row[0];

How to retrieve and display an array with objects from php cell using a loop?

In a Flex project, I have an array with objects in it. I want to save this array in a cell on a mysql table along with some other basic info like title, and an id.
EDIT: just clarifying since i seem to be getting responses explaining how to echo all the rows... I'm trying to echo the contents of an array that was serialized and placed in a single cell. This array has objects in it.
So, I have this code here to serialize the array, and insert it along with the other info into my DB:
function submitLogDbObj($array,$id,$title)
{
$title=mysql_real_escape_string($title);
return mysql_query("INSERT INTO logs (text,id,title) VALUES ('".serialize($array)."','$id','$title')");
}
Then for a test i'm trying to make a loop that will display the log in a way that looks like a conversation...
an object in my array would look something like:
[1]
icon = ""
msg = "this is a test"
name = "Them: "
systemMsg = 0
[2]
icon = ""
msg = "yep it sure is"
name = "You: "
systemMsg = 0
So here's what i've got so far, but its not working! How can I make a loop that will take that array from the DB, unserialize it and then echo the convo in a way that looks like a chat log?
Thanks!
<?php
include_once("dbinfo.php");
$id= $_GET['id'];
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
or die(mysql_error());
$row = mysql_fetch_array($result);
if($result)
{
$log = unserialize($row['text']);
echo 'starting loop!';
echo "<ul>";
/* im not sure how to represent the length of an array in php thats why i just have $log.length */
for ($i = 1; $i <=$log.length; $i++)
{
echo "<div id='logbox'>";
echo "<li>";
$name=$log[$i]['name'];
$msg=$log[$i]['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
echo "<br />";
}
echo "</ul>";
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Well, there're a few things which could be better here:
The length of an array is found through count( $array ) or sizeof( $array )
$value . $otherValue means concatenate those two values. Since length is undefined in this context, $log.length means "$log.length".
The best way to loop through an array is foreach( $set as $val) or foreach( $set as $key => $val )
The preferred method of iterating through a SQL result is the while loop: while($row = mysql_fetch_array($result)){ or do... while (see below). Unless you specifically and consciously only want one, then it would be best to use that. And if you do only want one, then put a Limit in the query.
Serialized arrays in databases has a redundant flavor. Are you sure that this is what you want?
Your serialized array, before it is inserted, should also be run through mysql_real_escape_string.
br really shouldn't be needed if you're surrounding something in its own div.
Indent properly or the kitten of death will come for you.
The improved code:
$row = mysql_fetch_array($result);
// row could be empty if there were no results
if($row)
{
// we've already grabbed the first value, so we need
// to invert while into do... while.
do
{
$log = unserialize($row['text']);
echo "<ul>";
foreach( $log as $line )
{
// Are you sure this should be outside of the li?
echo "<div id='logbox'>";
echo "<li>";
$name=$line['name'];
$msg=$line['msg'];
echo "$name - $msg";
echo "</li>";
echo "</div>";
}
echo "</ul>";
}
while( $row = mysql_fetch_array($result) );
echo 'finished loop!';
}
else
{
echo "Looks like this chat log has been deleted. Sorry!";
}
Firstly, get into the habit of indenting your code properly, it will save you a lot of frustration when looking for errors.
You don't need to know the length of the array, you can just use a while loop: (coding from the hip here so let me know if you get errors)
$result = mysql_query("......") or die("Query failed");
//Keep going while $row isn't FALSE
//mysql_fetch_array returns false when there are no more rows
while($row = mysql_fetch_array($result)){
//You can close PHP tags here and insert the
//variables in the HTML, it often looks neater
//and your editor can colour code HTML, helping
//you to find problems
?>
<div>
<li><?php echo $row['name'] ?></li>
<li><?php echo $row['msg'] ?></li>
</div>
<?php
}
See the "fetch array while loop" of this tutorial for more examples.
$result = mysql_query("SELECT text,title FROM logs WHERE id='$id'")
echo "<ul>";
while ($row = mysql_fetch_assoc($results)) {
$name = $row['name'];
$msg = $row['msg'];
//display data how ever you want
}
echo "</ul>";

How get all values in a column using 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);
?>

Categories