<br> every 4th result from sql - php

Simple question of course But I still could not figure it till now :) Im pulling names out of an sql and I want to be like 1 2 3 4,then next Line like 5, 6, 7, 8 Like So
<a>Bob</a>, <a>John</a>, <a>Bob</a>, <a>John</a> <BR>
<a>Bob</a>, <a>Ion</a>, <a>Bob</a>, <a>Pon</a> <BR>
Well thats What I want it To look like But For Now Its One Row Endless with no spaces is what I acheved so far Like So :)
<?PHP
require('connect.php');
$sql="SELECT * FROM profile";
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)){
$name =$row['username'];
$power =$row['power'];
?>
<span class='user-group-<?PHP echo $power; ?>'><?PHP echo $name; ?></span> ,
<?PHP } ?>
Now What Do I need to do to have every forth result + that space :?

Use an $i counter:
require('connect.php');
$sql = "select * from profile";
$result = mysql_query($sql);
// Start at 1
$i = 1;
while($row = mysql_fetch_array($result)){
$name = $row['username'];
$power = $row['power']; ?>
<span class='user-group-<?php echo $power; ?>'><?PHP echo $name; ?></span>
<?php
// When hit 4, add <br />
if($i == 4) {
echo '<br />';
// Reset to 0. $i will then auto-increment
// to 1 when hits $i++
$i = 0;
}
else
// Add comma if not equal to 4.
echo ',';
$i++;
}

Related

Pagination not working Properly after particular count

I am going to create a pagination then
$num_row = mysqli_num_rows($res);
total I have 240 rows then:
if($num_row>5){
$count=0;
$index=1;
while($count < $num_row && $index < 5){ ?>
<button id="<?php echo $count; ?>" class="index_b"><?php echo $index; ?></button>
<?php
$count = $count + 5;
$index++;
}
}
I want first 1 2 3 4 5 then next button so I tried
<div class="next_index_b">
<?php if($num_row > 50){?>
<button class="next_membd_index_button" name="50" ><img src="images/arrow.png" /></button>
<?php } ?>
Now my issue is after 4th pagination number, no number is working.
Don't use mysqli_num_rows()! Ideally, you should pull ONLY the data that you're looking for, and then run 2 separate queries. One to fetch the full count, and one to fetch the items per page:
$db = new PDO(...);
$page = isset($_GET['page']) ? (int) $_GET['page'] : 1;
$offset = ($page-1) * 50;
$count = $db->query("SELECT COUNT(*) FROM table")->fetchColumn();
$trans = $db->prepare("SELECT * FROM table LIMIT :offset, 50");
$trans->bindValue(':offset', $offset, PDO::PARAM_INT);
$trans->execute();
while ($row = $trans->fetchRow()) {
// echo data
}
//Add footer here. Use $page variable and $count to determine how many pages are available.
while($count < $num_row && $index < 5){ ?>
This condition means that when $index equals 5, the loop is stopped
Therefore, the button with 5 will never be shown.
Try using less or equal than instead of less than
if($num_row>5){
$count=0;
$index=1;
while($count < $num_row && $index <= 5){ ?>
<button id="<?php echo $count; ?>" class="index_b"><?php echo $index; ?></button>
<?php
$count = $count + 5;
$index++;
}
}
Or even better, switch to #FrankerZ's solution

How to split a PHP loop in 2 parts?

I have a weather json from where I get a wether forecast for 8 days. My problem is that I want to show the result in a table of 2 rows of 4 days each.
I managed to do it but in a very odd way that was pure begginer's luck during a trial-error-trial attempt :-) I don't even understand quite well why it is splitting the result in 2 rows... but it works!!! The only thing I could not do was to include a "hr" line between the 2 rows, to make the table easier to read.
You can see the result here http://www.meteocaldas.com/previsao_ds.php
With current code I am displaying each day forecasted values inside the same "td" in different lines using "br". I have been reading that it is not correct to use "br" inside "td" so I am not sure that I am doing the righ thing. Wouldn't it be better to use a table with 4 columns (one for each day) and have different rows for each of the values?
Is there any way to rewrite this code to make it more efficient and look less "childish"? :-) Thanks in advance!
<?php
(...)
$decoded = json_decode($rawData, true);
?>
<table>
<?php for($k=0;$k<8;$k++){
$dailyvalue = $decoded['daily']['data'][$k];
$dailyTime = $dailyvalue['time'];
$dailyIcon = $dailyvalue['icon'];
$dailyTempMax = round($dailyvalue['temperatureMax'],0);
$dailyTempMin = round($dailyvalue['temperatureMin'],0);
(...)
?>
<!-- table for 8 day's forecast (2 rows/4 days each) -->
<td>
<?php echo strftime("%a %d",$dailyTime) ?>
<br>
<?php echo '<img src="path/'.$dailyIcon.'.png">' ?>
<br>
<?php echo $dailyTempMin.'º' ?> </span>
<br>
<?php echo $dailyTempMax.'º' ?></span>
<br>
(...)
<?php if ($k == 3) {
echo '</td></tr>';
} ?>
<?php
}
?>
</td></tr><table>
As per your comment-request, here's some sample-pseudo code, based on your code above:
<?php
(...)
$decoded = json_decode($rawData, true);
for($k=0;$k<8;$k++){
$dailyvalue = $decoded['daily']['data'][$k];
$dailyTime[$k] = $dailyvalue['time'];
$dailyIcon[$k] = $dailyvalue['icon'];
$dailyTempMax[$k] = round($dailyvalue['temperatureMax'],0);
$dailyTempMin[$k] = round($dailyvalue['temperatureMin'],0);
}
?>
<table>
<?php
echo "<tr>";
for($k = 0; $k <= 3; $k++){
echo "<td>".strftime("%a %d",$dailyTime[$k])."</td>"; // this will make the "datetime" row
}
echo "</tr><tr>";
for($k = 0; $k <= 3; $k++){
echo "<td><img src=path/".$dailyIcon[$k].".png></td>"; // this will make the "icon" row
}
echo "</tr><tr>";
for($k = 0; $k <= 3; $k++){
echo "<td>".$dailyTempMin[$k]."º</td>"; // this will make the "MinTemp" row
}
echo "</tr><tr>";
for($k = 0; $k <= 3; $k++){
echo "<td>".$dailyTempMax[$k]."º</td>"; // this will make the "MaxTemp" row
}
echo "</tr>";
// put stuff you want between the tables here
echo "<tr>";
for($k = 4; $k <= 7; $k++){
// proceed to do the same as above
Mind you, there are further ways you can reduce the screen clutter (like moving the table-drawing for loops into a function), but this is the general gist of it
Why don't you simply stack two different table on each other ?

PHP MySQL arrange html output three by three, order by first letter of group

This is the code i have by now:
<?php
$sql = DB::query("SELECT name FROM stores ORDER BY name");
foreach ($sql as $row){ $name = $row["name"]; }
// don't know how to get the current letter
$current_letter = '?';
// Set the start at 1
$i = 1;
foreach ($sql as $row){
// If the loop hits 1, add <div>
if($i == 1)
echo '<div class="store-wrapper">'.PHP_EOL;
echo '<div class="store-letter">Store Letter - '. $current_letter .'</div>'.PHP_EOL;
echo '<ul>'.PHP_EOL;
echo $id = "\t<li>".$name.'</li>'.PHP_EOL;
// If the loop hits 3, add </div>
if($i == 3) {
echo '</ul>'.PHP_EOL;
echo '</div>'.PHP_EOL; // end .store-wrapper
// Reset the counter
$i = 0;
}
// Increment up
$i++;
}
?>
Is there something wrong with my code? This is the code output that i am trying to achieve:
<div class="store-wrapper">
<div class="store-letter">Store Letter - A</div>
<ul>
<li>ajhgjgj</li>
<li>abgjkhjh</li>
<li>avbnvnmnm</li>
</ul>
</div>
<div class="store-wrapper">
<div class="store-letter">Store Letter - B</div>
<ul>
<li>bgfghfj</li>
<li>bhgjhgj</li>
<li>bvkjhgkj</li>
</ul>
</div>
<div class="store-wrapper">
<div class="store-letter">Store Letter - C</div>
<ul>
<li>cgfghfj</li>
<li>chgjhgj</li>
<li>cvkjhgkj</li>
</ul>
</div>
Another thing is that i don't really know how to get the first letter of each group.
The problem with the code is that the output does not display as the upper example and the groups don't jumb to the next available letter when maximum 3 <li> are reached.
What i am doing wrong?
You don't need the first foreach loop. It just repeatedly assigns the same variable $name. You can do this in the loop that echoes the DIVs.
You can get the first letter of a string with $name[0].
Rather than testing for $i == 3 to know when to close the UL and DIV, test for $i > 3 to skip printing the names. Otherwise, if a letter has only 1 or 2 names in its group, you'll never close the group.
$current_letter = null;
foreach ($sql as $row) {
$name = $row['name'];
$first_letter = $name[0];
if ($first_letter != $current_letter) {
$i = 1;
if ($current_letter) { // close the previous DIV before starting new one
echo '</ul>'.PHP_EOL;
echo '</div>'.PHP_EOL;
}
$current_letter = $first_letter;
echo '<div class="store-wrapper">'.PHP_EOL;
echo '<div class="store-letter">Store Letter - '. $current_letter .'</div>'.PHP_EOL;
echo '<ul>'.PHP_EOL;
}
if ($i > 3) {
continue;
}
echo "\t<li>".$name.'</li>'.PHP_EOL;
$i++;
}
if ($current_letter) { // close the last DIV
echo '</ul>'.PHP_EOL;
echo '</div>'.PHP_EOL;
}
DEMO
output
1.Without using for loop, you can also use array_column() php function in order to get only 'name' from $sql. For example, $test = array_column($sql,'name');.
2.After that $test[0] will give you first name in the array.
3.To get first character, use substr($test[0], 0, 1)

Get position (number) in which a mysql_query was output for a certain value

I've been having an extremely difficult time trying to find an answer for this. What I want to do is (I think) rather simple, but I can't find any information on it.
Let's say I have a table in my database of fruits, and I'd like to do something like...
<?php
require "../body-parts/config.php";
$result = mysql_query('SELECT * FROM fruits ORDER BY name');
$count = 1;
while ($fruit = mysql_fetch_array($result)) {
echo $count++ . " ";
echo $fruit['name'] . "<br>";
}
?>
Now let's say the output of that is...
1 Apple
2 Cantaloupe
3 Grapes
4 Kiwi
5 Lemon
6 Orange
Now what I would like to do, is grab the number for Kiwi (in this case 4) so that I can use that later... but I don't know how I can do this.
So in short, how is it I grab the number position in which a value was returned? I do not want to echo it out, I simply want to grab it and stick it in a variable so I can use it again.
Any help is appreciated, thank you.
$_kiwi_id = 0;
$result = mysql_query('SELECT * FROM fruits ORDER BY name');
$count = 1;
while ($fruit = mysql_fetch_array($result)) {
echo $count++ . " ";
echo $fruit['name'] . "<br>";
if(strtolower ($fruit['name']) == "kiwi")
$_kiwi_id = $count-1;
}
<?php
require "../body-parts/config.php";
$result = mysql_query('SELECT * FROM fruits ORDER BY name');
$storage = array();
while ($fruit = mysql_fetch_array($result)) {
$storage[] = $fruit['name'] . "<br>";
}
//later some point of time
echo $storage[3]['name'] ; //this will echo "kiwi"
?>
Use an array:
<?php
require "../body-parts/config.php";
$result = mysql_query('SELECT * FROM fruits ORDER BY name');
$count = 1;
$fruits = array();
while ($fruit = mysql_fetch_array($result)) {
$fruits[$count++] = $fruit['name'];
}
echo $fruits[4]; // prints Kiwi
?>

Constructing HTML to output a set of numbers 5 per line

I am realy stuck with part of my php code! I have a range of numbers from 1 to 40 say that I pull from a table in my database and out put onto the screen using a while loop! with these numbers I am using a submit button which i will replace with a image button later on! Just now i can only get them in one line using a table but I want to get them into groups of say 5 or so colums and then go to next line print the next 5 or so colums! I have been trying for loops but they print out 1111, 2222, 3333, 4444, etc. in diffrent lines which is not what i want! I want,
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
etc
Please help me i have been baffeld with this for ages this is my code so far!
<?
$q3 = "SELECT * FROM tblgame";
$r3 = mysql_query($q3);
while($row2 = mysql_fetch_array($r3))
{
$game_cost = $row2['game_cost'];
echo "<p>Game ID: ".$row2['game_id'];
echo "<br>Game Day: ".$game_day;
echo "<br>Next Game Date: ".$row2['game_date_day']."/".$row2['game_date_month']."/".$row2['game_date_year'];
$fyear = $row2['game_date_year'];
$fmonth = $row2['game_date_month'];
$fday = $row2['game_date_day'];
$tmonth = $date_month;
$tyear = $date_year;
$tday = $date_day;
$days_between = abs((mktime ( 0, 0, 0, $fmonth, $fday, $fyear) - mktime ( 0, 0, 0, $tmonth, $tday, $tyear))/(60*60*24));
echo "<br>Days till next draw: ". $days_between;
echo "<br />Game Cost: £".$row2['game_cost']."</p>";
?>
<table>
<tr>
<?
$q4 = "SELECT * FROM tblnewgameitem WHERE game_id = $row2[game_id] ORDER BY 'game_number' ";
$r4 = mysql_query($q4);
$n1 = mysql_num_rows($r4);
$i=0;
while($row3 = mysql_fetch_array($r4))
{
?>
<td>
<?
if($row3['user_email'] == "")
{
?>
<form action="buyanumber.php" method="POST">
<input type="hidden" name="game_id" value="<?echo $row2['game_id'];?>">
<input type="hidden" name="num" value="<? echo $row3['game_number']; ?>">
<input type="submit" value="<?echo $row3['game_number'];?>" name="submit">
</form>
<?
}
else
{
$n = $n + 1;
echo " ".$row3['game_number']." ";
}
?>
</td>
<?
}
?>
</tr>
</table>
Please help me i have been stuck on this problem for a good number of days and its driving me loopy lol!
Thank you
Stephen
nested for-loops is the key:
$list=array();
while($row2 = mysql_fetch_array($r3)) $list[] = $row2;
$countList = count($list);
$cols = 5;
$rows = ceil($countList / $maxPerRow);
for ($i=0; $i<$rows; $i++) {
echo 'opening stuff per row... <tr> or something';
for ($j=0; $j<$rows; $j++) {
echo 'your stuff per item... might be somthing like <td>s';
}
echo 'closing stuff per row... </tr> or something';
}
something like this
I'm assuming that the 'real' problem lays somewhere between <table> and </table> and that you want to put the values returned by the fourth query (for some reason mapped to $row3) in a table with 5 columns.
Using the PHP modulo operator ('%'), you could do something like this:
<?php
$r4 = <your mysql_query>
$i = 0;
while ($row3 = mysql_fetch_array($r4)) {
if ($i % 5 == 0) { // true for 0, 5, 10, ...
echo "<tr>";
}
echo "<td>";
// what you want to put between your <td> tags comes here
echo "</td>";
if (($i+1) % 5 == 0) { // true for 4, 9, 14, ...
echo "</tr>";
}
$i++;
}
// if the number of rows is not a multiple of 5, we must clean up after ourselves:
if ($i % 5 != 0) {
echo "<td colspan=\"" + (5-($i % 5)) + "\"> </td></tr>";
}
?>
I haven't tested the code myself.
For the sake of clearity, please consider using proper indentation and consistent variable naming in your code. Also note that using a proper title and less exclamation marks in your question would improve the clearity of it.

Categories