Concatenate All Rows From One Column With MYSQL [duplicate] - php

This question already has answers here:
SQL, How to Concatenate results?
(7 answers)
Closed 7 years ago.
I am trying to do something that I thought would be very simple but it's driving me crazy.
I have the following data:
ID --- Name
1 --- Joe
2 --- Bob
3 --- Jim
4 --- Mike
I want to be able to show the results of this from MYSQL as:
"Joe", "Bob", "Jim", "Mike"
I tried CONCATENATE tutorials, but they all seem to be for merging like ID's.
$sql = "SELECT names, CONCAT_WS('', 'names') as namelist FROM peoplenames";
$result = $conn->query($sql);
echo $row["namelist"];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$names = $row["nameslist"];
echo $names;
}
}
If I echo outside the loop I only get the most recent result.
Any ideas?

The problem is that you are overwriting the contents of $names each time round the loop.
Change your code like this
$sql = "SELECT names FROM peoplenames";
$result = $conn->query($sql);
$names = NULL;
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$names .= sprintf('"%s",',$row['names']);
}
// output amalgamated date
rtrim($names, ',');
echo $names;
}

Change your query to SELECT names FROM peoplenames and use PHP concat for a string:
$names = "";
while($row = $result->fetch_assoc()) {
$names .= '"' . $row["names"] . '",';
}
echo $names;

Related

PHP: print all the items of an array [duplicate]

This question already has answers here:
MySQL Results as comma separated list
(4 answers)
Comma separated string of selected values in MySQL
(10 answers)
Just need a comma separated list from PHP/MySQL query [duplicate]
(5 answers)
Closed 2 years ago.
My goal: insert into a variable an array of items coming from a query and then print it
steps:
launch the query
do something with php
print the variable $report = 'this is your list: $list';
tried this:
$myquery = mysqli_query($dbconnection, "SELECT ...");
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, "; /* here I've the full list*/
}
$report = 'this is your list:' .$my_array. '.';
echo "$report"; /*I've only one item and not all the list*/
Your first echo is called several times because it is in the loop.
In every iteration you are replacing your content of $my_array.
Instead, try to attach it:
$my_array[] = $row['field'];
For more information see https://www.php.net/manual/de/language.types.array.php
This is normal.
Your while loop doing a "step" for each row found with your query.
You assigned $my_array as the "column" with the name field.
So at the end of the while loop, you'll get only the last column field of the last row.
Instead, try this
$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, ";
$myWholeList .= '$my_array '; // HERE
}
$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE
I've done a string concatenation, but you can do it with array and print_r() function. Have a look on this thread to see how to append data to an array.
mysqli_fetch_array while loop columns
EDIT:
Based on #isabella 's comment, she wants to display 7 items of array.
Two way :
Use print_r() or var_dump() which is the best to display an array (without taking care about rendering)
Add to $myWholeList variable each item.
e.g.
$myquery = mysqli_query($dbconnection, "SELECT ...");
$myWholeList = ''; // HERE
while($row = mysqli_fetch_assoc($myquery)) {
$my_array = $row['field'];
echo "$my_array, ";
// HERE
foreach($row as $field) {
$myWholeList .= $field . ' ';
}
$myWholeList .= '<br>'; // NEW LINE
}
$report = 'this is your list:' .$my_array. '.';
echo "$myWholeList"; // HERE

How do I get a value outside the loop using PHP [duplicate]

This question already has answers here:
How to get comma separated values from database [duplicate]
(3 answers)
Converting MySQL results into comma separated values
(4 answers)
Can I concatenate multiple MySQL rows into one field?
(16 answers)
Closed 3 years ago.
I'm creating a small website using PHP, which is generally a site for showcasing the hospital, and I modified the code given in this example:
https://www.w3schools.com/php/php_mysql_select.asp
<?php
$query = "SELECT * FROM emp WHERE type = 'woman' ";
$result = mysqli_query($db, $query);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$cat = $row["cat"] . ',';
echo $cat;
////<---- echo on while (Loop)
}
}
The expected output would be as follows:
Output: 35,36
But I changed the code with the link above and it is as follows:
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$cat = $row["cat"] . ',';
}
echo $cat;
///// <---- echo Out of While (Loop)
}
Output: 35
My expecting output would be 35, 36 outside of "while" using "echo".
What code do you recommend to output "35,36" the same code above?
You can try the below code to achive your requirement
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result)) {
$data[] = $row["cat"];
}
}
echo implode(",",$data);

calling PHP multi dimensional arrays outside of foreach loop

I have an app that records months and years by one CSV entry, i.e. db column named answer1 is jan,2008 and column answer2 is feb,2013. I want to use a specific month (jan) in html but it only gives me the last array data.
<?php
foreach ($row as $colName => $colValue )
{
if($colName === answer1 || $colName === answer2)
{
//break apart date data
$myArray = explode(',', $colValue);
echo '<div id=" ' .$colName . $myArray[0] . ' ">test</div> ';//this works
};
};
?>
I'd like something like this in another php block later in the doc.
<?php echo '<div id=" '.$colName[answer2] . $myArray[0] . ' ">test</div> ';?>
This is probably a lot easier. We're exploding (or pulling two substrings) from the original columns in MySQL before we get to PHP. Then you can use them however you would like:
$query = "SELECT SUBSTRING_INDEX(answer1,',',1) as a1_month,
SUBSTRING_INDEX(answer1,',',-1) as a1_year,
SUBSTRING_INDEX(answer2,',',1) as a2_month,
SUBSTRING_INDEX(answer2,',',-1) as a2_year from my_table";
$result = mysqli_query($query);
$answers = array();
$x = 0;
while ($row = mysqli_fetch_array($result)){
$answers[$x]['answer1_year'] = $row['a1_year'];
$answers[$x]['answer1_month'] = $row['a1_month'];
$answers[$x]['answer2_year'] = $row['a2_year'];
$answers[$x]['answer2_month'] = $row['a2_month'];
$x++;
}
print_r($answers);
If for some reason you still want the concatenated strings you can do this:
$answer1 = $answers[0]['answer1_month'].','.$answers[0]['answer1_year'];
$answer2 = $answers[0]['answer2_month'].','.$answers[0]['answer2_year'];

mysqli_fetch_array while loop columns [duplicate]

This question already has answers here:
get array of rows with mysqli result
(2 answers)
Closed 2 months ago.
Should be pretty basic, but I can't get it to work. I have this code to iterate over a mysqli query:
while($row = mysqli_fetch_array($result)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
It works and returns:
Variable #1: (Array, 3 elements) ↵
0 (String): "4testtest" (9 characters)
1 (String): "1Hello world!Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!" (99 characters)
2 (String): "2Sample PageThis is an example page. It's different from a blog post because it will stay in one place and will show up in
your site navigation (in most themes)." (161 characters)
The problem is that it puts all three colums into one column, so I can't access them seperatly.
This for example:
0 (String): "4testtest" (9 characters)
Should be seperated into 4, test, test
When I do this:
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row['post_id'];
$posts['post_title'] = $row['post_title'];
$posts['type'] = $row['type'];
$posts['author'] = $row['author'];
}
It only outputs 1 row instead of all three …
Any help is greatly appreciated!
Get all the values from MySQL:
$post = array();
while($row = mysqli_fetch_array($result))
{
$posts[] = $row;
}
Then, to get each value:
<?php
foreach ($posts as $row)
{
foreach ($row as $element)
{
echo $element."<br>";
}
}
?>
To echo the values. Or get each element from the $post variable
This one was your solution.
$x = 0;
while($row = mysqli_fetch_array($result)) {
$posts[$x]['post_id'] = $row['post_id'];
$posts[$x]['post_title'] = $row['post_title'];
$posts[$x]['type'] = $row['type'];
$posts[$x]['author'] = $row['author'];
$x++;
}
I think this would be a more simpler way of outputting your results.
Sorry for using my own data should be easy to replace .
$query = "SELECT * FROM category ";
$result = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc($result))
{
$cat_id = $row['cat_id'];
$cat_title = $row['cat_title'];
echo $cat_id . " " . $cat_title ."<br>";
}
This would output :
-ID Title
-1 Gary
-2 John
-3 Michaels
Both will works perfectly in mysqli_fetch_array in while loops
while($row = mysqli_fetch_array($result,MYSQLI_BOTH)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
(OR)
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)) {
$posts[] = $row['post_id'].$row['post_title'].$row['content'];
}
mysqli_fetch_array() - has second argument $resulttype.
MYSQLI_ASSOC: Fetch associative array
MYSQLI_NUM: Fetch numeric array
MYSQLI_BOTH: Fetch both associative and numeric array.
Try this :
$i = 0;
while($row = mysqli_fetch_array($result)) {
$posts['post_id'] = $row[$i]['post_id'];
$posts['post_title'] = $row[$i]['post_title'];
$posts['type'] = $row[$i]['type'];
$posts['author'] = $row[$i]['author'];
}
$i++;
}
print_r($posts);
Try this...
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {

MySQL query limit part of query

I have a mysql query:
$result = mysql_query("SELECT * FROM $table WHERE cat = 'category'");
while($row = mysql_fetch_array($result)) {
echo '
<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>
'.$row['title'].'
';
}
This query will generally select between 2 and 5 different rows and display them in a list.
I want the first echoed line to only appear once and the second line should appear between 2 and 5 depending on the data in my db.
I am sure there is a simple way to do this, I've tried GROUP BY mag but this will eliminate the remaining 1-4 pieces of data I wish to display.
Not sure I understand your question, as the following solution seems too simple!
$row = mysql_fetch_array($result);
echo '<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>
'.$row['title'].'';
while ($row = mysql_fetch_array($result)) {
echo ''.$row['title'].'';
}
May be this is a solution to your problem ?
$lines = '';
unset($hgroup);
$result = mysql_query("SELECT * FROM $table WHERE cat = 'category'");
while($row = mysql_fetch_array($result)) {
if (!isset($hgroup)) {
$hgroup = '<hgroup><h3>'.$row['mag'].'</h3><h4>'.$row['date'].'</h4></hgroup>';
}
$lines += '
'.$row['title'].'
';
}
echo $hgroup.$lines;

Categories