Echo all variable from while loop - php

I hava a while loop that throught to databases records. Like this:
$query = mysql_query("SELECT * FROM table");
while($articles = mysql_fetch_array($query)){
// something happen here
}
How can I echo each $articles out of the while loop ? So I don't want to have something like
while(...){
echo $articles['article_name'];
}
How can I save all the $articles['article_name'] into an array an echo them back ?

How about this:
$articleList = array();
while(...){
$articleList[] = $articles['article_name'];
}
That will put everything in the array $articleList for you.

You can do something like:
$articles = array();
while ($art = mysql_fetch_array($query)) {
$articles[] = $art;
}
print_r($articles);

$i=0; $articles = array();
$query = mysql_query("SELECT * FROM table");
while($articles[] = mysql_fetch_array($query)){
echo $articles['article_name'][$i];
$i++;
}

$query = mysql_query("SELECT * FROM table");
while($articles = mysql_fetch_array($query)){
$names[] = $articles['article_name'];
}
echo 'array of names are :';
print_r($names);

Related

Form json using php json_encode failed

By using below code
$data = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$data['title'] = $row['title'];
$data['name'] = $row['name'];
}
}
echo json_encode($data);
I got 1 result, I can get full result if I do $data[] = $row['title'], but I want to make the result like this
{'title' : ['title 1','title 2'], 'name':['John','Amy']}
You are overwriting the title in each loop iteration. You need to accumulate all the titles and then set it in your data array.
$data = array();
$sql = "SELECT title FROM mainlist";
$result = $db->query($sql);
$titles = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
}
}
$data['title'] = $titles;
echo json_encode($data);
The easiest away is probably this:
$rows = array();
$sql = "SELECT * FROM list";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
}
echo json_encode($rows);
you could achieve by using group_concat on each of the columns in your query. That way you do not need to loop the result again and add column etc...
$sql = "SELECT group_concat(title) as title,group_concat(name) as name FROM list";
$result = $db->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
Try this:
$titles = array();
$names = array();
$sql = "SELECT title,name FROM mainlist";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$titles[] = $row['title'];
$names[] = $row['name'];
}
}
echo json_encode(array("title" => $titles, "name" => $names));
UPDATE
Updated my code to let you manage an undefined number of columns as result
$out = array();
$sql = "SELECT * FROM wp_cineteca";
$result = $db->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
$keys = array_keys($row);
for ($i = 0; $i < count($row); $i++) {
$out[$keys[$i]][] = $row[$i];
}
}
}
echo json_encode($out);

PHP Iterate through a MySQL result a certain amount of times

At the moment I have this code looping through the whole results of a query:
$result = mysqli_query($con, $sql);
$data = array();
while($row = mysqli_fetch_array($result)) {
$name = $row ['name'];
$desc = $row ['description'];
$cat = $row ['category'];
$price = $row ['price'];
$quantity = $row ['quantity'];
$id = $row ['productID'];
$image = $row ['image'];
$arr = array();
$arr ["id"] = $id;
$arr ["name"] = $name;
$arr ["desc"] = $desc;
$arr ["cat"] = $cat;
$arr ["price"] = $price;
$arr ["quantity"] = $quantity;
$arr ["image"] = $image;
array_push($data, $arr);
}
echo json_encode($data);
I want to change this to only loop through a set amount of results. I have a variable further up the code called $amount which is the amount of results I would like.
I hear I should use mysql_result() and a for loop to count to $amount, but I'm not sure how my existing code will work with that set up! Suggestions please.
EDIT:
#Styphon Pointed out that I don't actually need to change my iteration code for this to be solved. Just needed to add a LIMIT to my SQL query.
$sql = "rest of query...
LIMIT $amount"; //This will limit it to whatever is $amount. Just make sure to have it on the end of your query.
$result = mysqli_query($con, $sql);
$data = array();
while($row = mysqli_fetch_array($result)) {
$arr = array();
$arr["id"] = $row['productID'];
$arr["name"] = $row['name'];
$arr["desc"] = $row['description'];
$arr["cat"] = $row['category'];
$arr["price"] = $row['price'];
$arr["quantity"] = $row['quantity'];
$arr["image"] = $row['image'];
array_push($data, $arr);
}
echo json_encode($data);
Solution is the same whether you use mysql_ or mysqli_ (but you should use mysqli or even pdo). It goes something along this lines:
$num = 0;
$amount = 10;
while ($f = mysql_fetch_array($q)) {
// your code;
$num++;
if ($num==$amount) break;
}
As you mentioned for loops, with for loop you might do something like this
for ($i=0;$i<$amount;$i++) {
$f = mysql_fetch_array($q);
//your code
}
Obviously you should adjust it to suit your needs.
SELECT * FROM tbl
LIMIT 0, $amount
This will limit your result to $amount.

How to contain a while loop in a variable

I have the following code:
<?php
if(isset($_POST['indexSearchSubmit']))
{
foreach($_POST['industryList'] as $selected)
{
$_POST['industryList'] = $selected;
$locationListResults = $_POST['locationList'];
$results = mysqli_query($con,"SELECT * FROM currentListings WHERE location = '$locationListResults' AND industry = '$selected'");
while($row = mysqli_fetch_array($results))
{
echo $row['industry'];
echo $row['location'];
echo $row['title'];
echo $row['description'];
}
}
mysqli_close($con);
}
?>
Could anyone tell me how I would go about storing the echo part into a variable so I can then display it as and where I want in other parts of the site?
If I remove the echo and instead store $row as a variable when I echo that variable it only outputs once and doesn't run the loop.
You should use mysqli_fetch_all for this. The result will be an array where each element is a row and each row is an associative array with the same keys as row in your example
$data = mysqli_fetch_all($result);
$data[0]["industry"]; //Data in the first row
You can then loop over $data to output it any place on your page.
put in array,
$list = array();
while($row = mysqli_fetch_array($results))
{
$list[] = $row;
}
you may try this
$arrayList = array();
while($row = mysqli_featch_array($results)){
$arrayList[] = $row;
}
print_r($arrayList);
Put all the values in an array
$rows = array();
$x = 0;
while($row = mysqli_fetch_array($results))
{
$rows[$x]['industry'] = $row['industry'];
$rows[$x]['location'] = $row['location'];
$rows[$x]['title'] = $row['title'];
$rows[$x]['description'] = $row['description'];
$x++;
}
return $rows;
Then you can use $rows as an array.
foreach($rows as $v){
echo $v['industry']." ".$v['location']."<br />";
echo $v['title']." ".$v['description']."<br />";
}

json different format

I have a query:
$result = mysql_query("SELECT
Left(Right(Base.inputs.Data_inf,4),3) As 'Datas',
count(Base.Data.Data_ID) As `U_Count`
FROM
Base.Data
WHERE
Base.Data_inputs.info = 'TREE'
GROUP BY ");
$rows = array();
while($r = mysql_fetch_array($result)) {
$row[0] = $r[0];
$row[1] = $r[1];
array_push($rows,$row);
}
print json_encode($rows, JSON_NUMERIC_CHECK);
and the result is:
[["Data1",38],["Data2",13]]
I would like the data look more like:
[{"name":"Data1","data":[38]},{"name":"Data2","data":[13]}]
I was trying to use something like this:
$rows = array();
while($r = mysql_fetch_array($sth)) {
$rows['name'] = $r['Datas'];
while($r = mysql_fetch_array($sth)) {
$rows['data'][] = $r['U_Count'];
}
}
But it doesn't work.
Can anyone help?
THNKS
You can traverse the data and store it as an array.
$rows = array();
while($r = mysql_fetch_array($sth)) {
$rows[] = array('name'=>$r['Datas'],'data'=>array($r['U_Count']));
}
Use mysql_fetch_object() instead of mysql_fetch_array()
while($r = mysql_fetch_object($result)) {
...

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

Categories