Unable to get mysql data in one line

I have this query that should retrieve data from my mysql database and print as a single line. To understand what I'm looking for, the query must select the data and then print it as 1/23/45/67/89/10/11

------------------------------------
id  ussd_string session_id
------------------------------------
1   1       123456  
2   /23     123456
3   /45     123456
4   /67     123456
5   /89     123456
6   /10     123456
7   /11     123456
------------------------------------

PHP:

$query="(SELECT * FROM userleveltracking WHERE session_id = '123456' ORDER BY id ASC LIMIT 7)";
$result=mysql_query($query);
while($rows=mysql_fetch_assoc($result))
{
$newussdString=$rows['ussd_string'];
}
$ussdString = $newussdString;
echo $ussdString;

When I execute the code, it returns only the first value, which is 1. What is the problem with my code.

+4
source share
5 answers

You need echoto loop while. Like you, each time you rewrite a variable, so you only get the last line.

Try:

$query="(SELECT * FROM userleveltracking WHERE session_id = '123456' ORDER BY id ASC LIMIT 7)";
$result=mysql_query($query);
while($rows=mysql_fetch_assoc($result))
{
echo $rows['ussd_string'];
}

or if you need each value later, use an array:

$query="(SELECT * FROM userleveltracking WHERE session_id = '123456' ORDER BY id ASC LIMIT 7)";
$result=mysql_query($query);
while($rows=mysql_fetch_assoc($result))
{
$values[] = $rows['ussd_string'];
}
foreach($values as $value){
    echo $value;
}

or concatenation:

$values = '';
$query="(SELECT * FROM userleveltracking WHERE session_id = '123456' ORDER BY id ASC LIMIT 7)";
$result=mysql_query($query);
while($rows=mysql_fetch_assoc($result))
{
$values .= $rows['ussd_string'];
}
echo $values;
+3
source

try it

   $query="(SELECT * FROM userleveltracking WHERE session_id = '123456' ORDER BY id ASC LIMIT 7)";
$result=mysql_query($query);
$ussdString = "";
while($rows=mysql_fetch_assoc($result))
{
    $newussdString=$rows['ussd_string'];
    $ussdString .= $newussdString;
}
echo $ussdString;

You need to execute lines with .=

http://www.tutorialspoint.com/mysql/mysql-concat-function.htm

+5

, . .

:

$query="(SELECT * FROM userleveltracking WHERE session_id = '123456' ORDER BY id ASC LIMIT 7)"; 

$result=mysql_query($query);

while($rows=mysql_fetch_assoc($result)) 
{ 
   echo $rows['ussd_string']."<br>";
} 

, , .

:

mysqli_* PDO, mysql_* PHP 7

+4

GROUP_CONCAT, PHP:

SELECT GROUP_CONCAT(ussd_string ORDER BY id SEPARATOR '')
FROM userleveltracking 
WHERE session_id = '123456' 
GROUP BY 1
+3

, . , .

$newussdString=$rows['ussd_string'];

.

+1

Source: https://habr.com/ru/post/1626683/


All Articles