Store Looped MySQL Array as String Variable - php

I have a collection of results from a MySQL query being fetched in a loop.
I need to store them as a single variable with a space in between each result.
$result = mysql_query("SELECT Names FROM table");
while($row = mysql_fetch_array($result)){
echo $row['Names'] . " ";
}
So later, I can call 'echo $Names;' and get the string of names with a space in between.
ex) Clinton Bush Huckabee Romney etc....
Thanks for your help!

$Names = '';
$result = mysql_query("SELECT Names FROM table");
while($row = mysql_fetch_array($result)){
$Names.= $row['Names'] . " ";
}

$result = mysql_query("SELECT Names FROM table");
$names = "";
while($row = mysql_fetch_array($result)){
$names .= $row['Names'] . " ";
}
echo $names;

First of all, please, stop using mysql extention. It's deprecated. Try mysqli or PDO.
$names = array();
$result = mysql_query("SELECT Names FROM table");
while($row = mysql_fetch_array($result)){
$names[] = $row['Names'];
}
echo implode(' ', $names);

I would use an array and then implode it using a space:
$result = mysql_query("SELECT Names FROM table");
$arr = array();
while($row = mysql_fetch_array($result)) $arr[] = $row['Names'];
echo implode(' ', $arr);

Related

convert my result array into string in php

i want to convert my array into string i mean i want to echo only array value
i use this code
$query = "SELECT `message` FROM `appstickers`";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$jsonArray = array();
while($row = $result->fetch_assoc()) {
$jsonArray[]= $row;
}
//echo $string;
echo json_encode($jsonArray);
i get this output
[{"message":"welcome to team with us"},{"message":"this is for light dispatch"}]
but i want this output
[welcome to team with us,this is for light dispatch"]
so please give me proper solution with example
So why are you using json_encode() ?
use implode() instead:
// ... previous code
while($row = $result->fetch_assoc()) {
$jsonArray[]= $row;
}
echo '[' . implode(',', $jsonArray) . ']';
I'm going on a limb here, and assuming your required array is not what you actually want, but you do want this:
$jsonArray = array();
while($row = $result->fetch_assoc()) {
$jsonArray[]= $row['messsage'];
}
echo json_encode($jsonArray);
which will result in
["welcome to team with us", "this is for light dispatch"]
<?php
echo implode(" ",$jsonArray);
?>
Just you need to use implode() function.
$query = "SELECT `message` FROM `appstickers`";
$result = $mysqli->query($query) or die($mysqli->error.__LINE__);
$jsonArray = array();
while($row = $result->fetch_assoc()) {
$jsonArray[]= $row;
}
//echo $string;
$ans = implode(",",$jsonArray);
echo $ans;

How to get all values in a certain column with php

I need to print out all the usernames of my members in my site as a list, but I don't know how to do it. I tried to use 'mysqli_fetch_array' function to fetch names from username column, but I've been failing. So, please assist me on how I can do this in a most efficient way.
This is my code
$sql = "SELECT username FROM users";
$query = mysqli_query($db_con, $sql);
$array = Array;
while($row = mysqli_fetch_array($query)) {
$array = row[];
}
foreach ($names as $array) {
echo $names;
}
Also I want to format the output, like separating each username by " | "
You are quite close..
$sql = "SELECT username FROM users";
$query = mysqli_query($db_con, $sql);
while($row = mysqli_fetch_assoc($query)) {
echo $row['username'].'|';
}
Couple of things, "Array" should be "array()" and you're doubling up, by assigning array values into an array, results are returned in an array already. Code below should work...
$sql = "SELECT username FROM users";
$query = mysqli_query($db_con, $sql);
$array = mysqli_fetch_array($query));
foreach ($array as $name) {
echo $name["username"] . "|";
}
Looks like you also had your foreach loop round the wrong way
no need to use extra foreach, just do this way-
$sql = "SELECT username FROM users";
$query = mysqli_query($db_con, $sql);
$array = array();
while($row = mysqli_fetch_assoc($query)) {
echo $row["username"] . "|";
}
Don't worry it is really very easy
<?php
//All your preceding code
$sql = "SELECT username FROM users";
$query = mysqli_query($db_con, $sql);
?>
<ul>
<?php
while($row = mysqli_fetch_array($query)) {
echo "<li>" . $row['username'] . "</li>";
}
?>
</ul>

remove last character

i noticed that there are a lot of topics like this in stackoverflow, but the ones that i read are with just 1 variable, and i have two and i'm a little confuse.
so this is my code,
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
while($row = mysql_fetch_array($query)){
echo "'".$row['provider_id']."':'".$row['company_name']."',";
}
I am using this to generate javascript code for Jeditable.
I need to take out the last comma, so I can wrap up with the rest of the code...
I like to use an array:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(",",$out);
It looks like you're trying to output some kind of JSON though, so perhaps you could use:
$query = ...;
$out = Array();
while($row = mysql_fetch_assoc($query)) {
$out[$row['provider_id']] = $row['company_name'];
}
echo json_encode($out);
So i usually just stack things like this into an array and then implode:
$parts = array();
while($row = mysql_fetch_array($query)){
$parts[] = "'".$row['provider_id']."':'".$row['company_name']."'";
}
echo implode(',', $parts);
That said it looks like youre outputting the body of a JSON string. If so you shouldnt manually build it you should use json_encode instead.
$data = array();
while($row = mysql_fetch_array($query)){
$data[$row['provider_id']] = $row['company_name'];
}
echo json_encode($data);
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = "";
while($row = mysql_fetch_array($query)){
$result .= "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = rtrim($result, ',');
OR
$query = mysql_query("SELECT Provider.provider_id, provider.company_name FROM Provider");
$result = array;
while($row = mysql_fetch_array($query)){
$result[] = "'".$row['provider_id']."':'".$row['company_name']."',";
}
$result = implode(',' $result);
OR
get count of records (mysql_num_rows($query)) and when you hit last row just do what you want

Store Column Values in Array

I'm trying to store the title(summary) and date(created) of an event in an array. But I think im missing something in my loop.
<?php
$summary = array();
$date = array();
mysql_connect('mysql.server', 'myUsername', 'myPass') or die('Could not connect: ' . mysql_error());
mysql_select_db("mxgsite") or die(mysql_error());
$query_summary = mysql_query('SELECT summary FROM event_info') or die(mysql_error());
$query_date = mysql_query('SELECT created FROM event_details') or die(mysql_error());
$row_summary = mysql_fetch_array($query_summary);
$row_date = mysql_fetch_array($query_date);
$i = 0;
while(($row1 = mysql_fetch_array($query_summary))) {
$row2 = mysql_fetch_array($query_date);
$summary[] = $row['summary'];
$date[] = $row['created'];
echo $summary[$i] . " " . $date[$i] . "<br ?>";
$i++;
}
I know i'm getting values because I can echo out 1 value, but if I want to put all the values in an array and try to echo out that array I keep getting blank values?
It seems to me like you are trying to do too many things here. Since the 2 sets of values are not being stored in a way where they are related/linked to each other, you might as well deal with them in separate while loops. Try something like this:
while ($row = mysql_fetch_array($query_summary)){
$summary[] = $row[0];
}
while ($row = mysql_fetch_array($query_date)){
$date[] = $row[0];
}
If you want to relate the tables, per the comments above, you can try something more like:
$result = mysql_query('SELECT a.eventid, a.summary, b.created
FROM event_info a
join event_details b
on a.eventid = b.eventid');
$events = array();
while ($row = mysql_fetch_array($result)){
$event = array();
foreach ($row as $key=>$value){
$event[$key]=$value;
}
$events[] = $event;
}

How to make a php variable equal to the result of mysql_fetch_array?

$query = mysql_query("SELECT * FROM fruit WHERE color='red' ");
while ($row = mysql_fetch_array($query)) {
echo $row['name']."|" ;// this echo apple|strawberry|cherry
}
How to make a php variable equal to the result of mysql_fetch_array? I need to make a equal like: $newname="apple|strawberry|cherry", so that I can use the new variable $newname for another process. Thanks.
Rather than echo, concatenate:
$newname = '';
while ($row = mysql_fetch_array($query)) {
$newname .= $row['name']."|" ;// this echo apple|strawberry|cherry
}
$newname = rtrim($newname,'|');
$newname .= $row['name']."|" ;
$query = mysql_query("SELECT * FROM fruit WHERE color='red' ");
$newname= '';
while ($row = mysql_fetch_array($query)) {
$newname.= $row['name']."|" ;
}
This gives you a string $newname like you want.
I know everyone else went with string concatenation, but I would personally suggest an array push followed by a join - I haven't benchmarked it, but I believe it would perform slightly better.
while($row = mysql_fetch_array($query)) {
$newname[] = $row['name'];
}
echo join('|', $newname);
i use this in my joomla :
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select('price');
$query->from($db->quoteName('#__google_api'));
$query->where($db->quoteName('id')." = ".$db->quote('1'));
// Reset the query using our newly populated query object.
$db->setQuery($query);
$db->setQuery($query);
$price = $db->loadResult();
Fetches data for a single colume and stores it in $price

Categories