Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant retrieve mysql data into a single string

Tags:

php

mysql

I am have this query that is supposed to retrieve data from my mysql database and print is as a single string. To understand what i am looking for, the query is supposed to 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 only returns the first value which is 1. What's the problem with my code.

like image 891
nick Avatar asked Dec 04 '22 01:12

nick


2 Answers

Try this

   $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 concat strings with .=

EDIT You can also concat string in database query http://www.tutorialspoint.com/mysql/mysql-concat-function.htm

like image 93
Radek Adamiec Avatar answered Dec 06 '22 14:12

Radek Adamiec


This return only one value because you are not print the result inside the loop. This will always return you the last record.

You can use like that:

$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>";
} 

Other solution is that you can store the rows data into an array and than use where you need.

Side note:

Please use mysqli_* or PDO because mysql_* is deprecated and not available in PHP 7

like image 34
devpro Avatar answered Dec 06 '22 14:12

devpro