remove last character - php

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

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;

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.

Echo all variable from while loop

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);

Store Looped MySQL Array as String Variable

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);

Categories