PHP Loop, Add a comma after every loop except the last - php

I've got a query that loops through some product names and puts them down on the page. As part of the loop, it adds a comma to the end, so it looks like this:
Products: Shirts, Pants, Ties, Jackets,
Notice that I'm getting a comma after the last product. Also, they are all links, so I can't use some strreplace fx or similar:
Here's my code:
<?php
$product_query = mysql_query("select * from products_table);
$row_product_query = mysql_fetch_assoc($product_query);
$totalRows_product_query = mysql_num_rows($product_query);
?>
<strong>Products: </strong>
<?php if ($totalRows_product_query > 0) { ?>
<?php do { ?>
<span><?php echo $row_product_query['products_name']; ?></span>
<strong>, </strong>
<?php } while ($row_product_query = mysql_fetch_assoc($product_query)); ?>
<?php } ?><br />
What do I need to do to make that last comma not appear?
Thanks in advance as always.

using the php implode function
<?php
$str = "";
$product_query = mysql_query("select * from products_table");
$row_product_query = mysql_fetch_assoc($product_query);
$totalRows_product_query = mysql_num_rows($product_query);
$cnt = 0;
?>
<strong>Products: </strong>
<?php if ($totalRows_product_query > 0) { ?>
<?php do {
$arr[$cnt] = '<span>'.$row_product_query['products_name'].'</span>';
$cnt++;
<?php } while ($row_product_query = mysql_fetch_assoc($product_query)); ?>
<?php }
echo implode("<strong>,</strong>",$arr);
?><br />

Fix how they are being stored/entered into the database?
otherwise,
<?php echo str_replace(",", "", $row_product_query['products_name']); ?>
should work

As #tucker said, you could use the implode function. Implode Function. You would use it with an array like so
$a_string = implode(",",$the_result_array);
This would give you your desired results.

Related

Split query in several positions

I have a website where I need to split a result query that gives me all my groups because I want to handle all the groups individualy.
This is my code ( result 6 is the query i make to obtain all the group names). But the problem is that all the result appear in the same position -> [0] zero.
This is an image of the problem
<?php while ($row = mysqli_fetch_array($result6)){ ?>
<tr>
<?php if(strlen($row['groupname'])>0){ ?>
<?php $groups = $row['groupname'];
$dividedGroups= (explode(",",$groups));
print_r($dividedGroups)
?>
</br>
<?php } ?>
</tr>
<?php } ?>
I guess more data is needed, but as far as I can tell you are ending with an array of arrays.
After this line:
$dividedGroups= (explode(",",$groups));
Try to add this two lines in order to transform it to a simple array:
$dividedGroups= array_map("array_shift",$dividedGroups);
$dividedGroups= array_map("array_values",$dividedGroups);
You don't need to split by comma as each row represent a group:
<?php
while ($row = mysqli_fetch_array($result6)) {
if(strlen($row['groupname'])>0) {
?>
<tr>
<td>
<?php echo $row['groupname']; ?>
</td>
</tr>
<?php
}
}
?>
Or, if the row is not a group you can group it by groupname before displaying:
$results = [];
while ($row = mysqli_fetch_array($result6)) {
$results[$row['groupname']] = isset($results[$row['groupname']])
? array_merge($results[$row['groupname']], [$row])
: [$row];
}
print_r($results);

Php while codes show just 1 row

I'm using these codes.
$blog = mysql_query("SELECT * FROM blog ORDER BY id");
while($sutun = mysql_fetch_array($blog)) {
$fake = $sutun["date"];
echo "$fake";
}
When i use echo"$fake"; I can see all of my rows. But when I use <?php echo "$fake" ?> , It shows just 1 row for me.
I want to all of my rows while I'm using <?php echo "$fake" ?>.
Beacuse The echo"$fake"; in with in a loop it will echo at every iteration thats why you can see all your rows but <?php echo"$fake"; ?> executed when the loop is done so only the last row will be echoed;
You should seperate your logic like
<?php
$blog = mysql_query("SELECT * FROM blog ORDER BY id");
while($sutun = mysql_fetch_array($blog)) {
$fake = $sutun["date"];
?>
<?php
echo $fake;
}

PHP passing Array

I have two php page.
In the first I have looping checkbox array :
<td><input type="checkbox" name="cek[]" value=" <?php echo "$kodeinventarisit" ?>"></td>`
Then i submit form from page one to page two :
<?php
include 'koneksi.php';
$cek = $_POST['cek'];
$jumlah_dipilih = count($cek);
for($x=0;$x<$jumlah_dipilih;$x++){
$jojo = $cek[$x];
$coba = "select * from msstok where kodeinventarisit = '$jojo' ";
$cobaquery = mysql_query($coba);
$hasil = mysql_fetch_array($cobaquery);
$jenis = $hasil['jenis'];
?>
<input name="kode" type="text" id="license" value="<?php echo htmlentities($jenis) ; ?>" readonly="readonly" />
<?php
echo "$jojo";
}
?>
The problem is in the sql query return nothing, I try echo "$jojo" and it's print the value but in the text field is empty..
Does anyone have suggestions on how to fix this?
Thank You Very Much
1
What you are doing is bad.
Load your data before your loop and loop every result to print them.
2
Protect your sql request from injection.
Connect
$db = new mysqli("","root","","");
Prepare your request
$sql = "select * from msstok where kodeinventarisit = ? ";
$res = $db->prepare($sql);
$res->bind_param("sssd",$jojo);
Get results
$res->execute();
Documentation : http://php.net/manual/fr/book.mysql.php
If you want to pass the array you need to check if arrive in you second page.
<pre>
print_r($_POST['cek']);
</pre>
Now, if arrive here, you can read the values like this:
<?php
// If is array(), then you can go to loop
if(is_array($_POST['cek']))
{
// Run the loop
foreach($_POST['cek'] as $value)
{
// Show values per line
echo $value. "<br/>";
}
}
?>
You can read only 1 value of your array
<?php echo $_POST['cek'][0]; ?>
<?php echo $_POST['cek'][1]; ?>
<?php echo $_POST['cek'][2]; ?>
Conclusion
You can't pass array to SQL in query. If you want to use it, this is the only way with implode.
$coba = "SELECT * FROM msstok WHERE kodeinventarisit IN (".implode(',', $jojo).")";
$records = mysql_query($coba, $connection);
while ($row = mysql_fetch_array($records)) {
echo "Name: " . $rows['name'] . "<br />"; // replace the name for column you want
}

Creating a table with PHP foreach function

I'm in a class called database programming. We got a data set and and put it into our servers. Now I have to use a jquery plugin to help visualize that data. I am using Graph Us plugin and trying to use the "Fill In" option.
My professor helped me create this function:
<?php
include 'connect.php';
$country_query = "SELECT DISTINCT Country FROM FemaleMaleRatioNew";
$result = mysqli_query($sql_link, $country_query);
$new_row = array();
while ($row = mysqli_fetch_assoc($result)) {
$country = $row['Country'];
$query = sprintf("SELECT Year, Value FROM FemaleMaleRatioNew WHERE Country = '%s'", $country);
$country_result = mysqli_query($sql_link, $query);
while ($country_row = mysqli_fetch_assoc($country_result) ) {
$new_row[$country][] = array('year' => $country_row['Year'],
'value'=> $country_row['Value']
);
}
}
//print_r($new_row);
?>
the print_r($new_row); is only there to make sure it works and it does, it prints out the array when activated.
He then guided me to create the table like this:
<body>
<table id="demo">
<?php foreach($new_row as $row):?>
<tr>
<td><?=$row['year'];?></td>
<td><?=$row['country'];?></td>
</tr>
<?php endforeach;?>
</table>
<script type="text/javascript">
$(document).ready(function() {
// Here we're "graphing up" only the cells with the "data" class
$('#demo td').graphup({
// Define any options here
colorMap: 'heatmap',
painter: 'fill',
// ...
});
});
</script>
</body>
What else do I need to do to get the table to work? I can't seem to figure it out. All it does is come out blank.
I'm sorry if this question isn't worded correctly or if I have not been clear on anything please let me know.
You have multiple rows for each country in your $new_row variable. You have to iterate over countries first and then over the individual rows of data:
<?php foreach($new_row as $country => $rows): ?>
<?php foreach($rows as $row): ?>
<tr>
<td><?=$country;?></td>
<td><?=$row['Year'];?></td>
<td><?=$row['Value'];?></td>
</tr>
<?php endforeach;?>
<?php endforeach;?>
Also please note that you need colon ':' not semicolon ';' after the foreach statement. This syntax (which is less known) is described here: http://php.net/manual/en/control-structures.alternative-syntax.php
If you want to display some sort of aggregate (for example sum) per country and you want to calculate it in PHP (as opposed to MySQL) you can do it like this:
<?php foreach($new_row as $country => $rows):
$sum = 0;
foreach($rows as $row):
$sum += $row['Value'];
endforeach;
?>
<tr>
<td><?=$country;?></td>
<td><?=$sum;?></td>
</tr>
<?php endforeach;?>
You should be using a single JOINed query to do this stuff, but you may not have gotten that in class yet. Since it's homework, I won't give you the flat-out answer, but here's the pseudo-code:
$countries = SELECT DISTINCT Country FROM YourTable;
while($country_row = fetch_row($countries)) {
echo $country_row['Country'];
echo <table>;
$status = SELECT Year, Value FROM YourTable WHERE Country=$country_row['Country'];
while($stats_row = fetch_row($status) {
echo <tr><td>$stats_row['Year']</td><td>$stats_row['Value']}</td>
}
echo </table>
}

formatting mysql data for ouptut into a table

Following on from a question earlier today this answer was given to read the data into an array and separate it to print vehicle type and then some data for each vehicle.
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
This is almost perfect for what I want to do but I need to print out two columns from the database ie ford and mondeo before going into the second foreach loop. I've tried print $rows['model'] and all the other combinations I can think of but that doesn't work. Any help much appreciated
I'm a bit confused by your question but the SELECT * in the SQL statement means that every column from the database should be present as a key=>value pair in the $row array. So if you needed another "column," output here into an HTML list element <li>, you just echo (note: not "print") that column name as an array key. So if you needed the type of the car column found in a column with the name "model" you'd do this:
<?php
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<li><?php echo $vehicleData['model'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>
EDIT: I'm still unclear on your question, but if every car has the same vehicleType, and you're just looking to grab that once before looping through all the results, I'm guessing this will do it:
<?php
// Set up a SQL query to grab one row
$query_to_grab_only_vehicle_type = "SELECT vehicleType FROM apparatus WHERE 1 LIMIT 0,1";
// Fetch that row and turn it into an array
$vehicle_type_array = mysql_fetch_array(mysql_query($query_to_grab_only_vehicle_type));
// Initialize a variable with the array value that came from the vehicleType column
$vehicle_type = $vehicle_type_array['vehicleType'];
// You could uncomment and use the following to echo out the variable
// echo "Vehicle type: $vehicle_type";
$sql = "SELECT * FROM apparatus ORDER BY vehicleType";
$getSQL = mysql_query($sql);
// transform the result set:
$data = array();
while ($row = mysql_fetch_assoc($getSQL)) {
$data[$row['vehicleType']][] = $row;
}
?>
<?php foreach ($data as $type => $rows): ?>
<h2><?php echo $type?></h2>
<ul>
<?php foreach ($rows as $vehicleData):?>
<li><?php echo $vehicleData['name'];?></li>
<li><?php echo $vehicleData['model'];?></li>
<?php endforeach ?>
</ul>
<?php endforeach ?>

Categories