Grouping WHILE loop results - php

At the moment I'm using a WHERE loop to display 2 columns of information in my database. Here's the code:
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
/*These if & while statements decide whether or not the information should be displayed. If no results are returned from the query above then an alternative message is shown.*/
if (mysql_num_rows($result2) > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"] . "<br/><br/>";
}
}
else {
echo "Error";
}
This outputs the following:
08:00:00-12:30:00
13:30:00-16:30:00
09:00:00-17:00:00
18:00:00-20:00:00
09:00:00-17:00:00
18:00:00-20:00:00
08:00:00-17:00:00
18:00:00-20:00:00
09:00:00-17:00:00
18:00:00-20:00:00
Now, what I need to do is group every 2 lines that are turned so instead it would look like:
08:00:00-12:30:00 13:30:00-16:30:00
09:00:00-17:00:00 18:00:00-20:00:00
09:00:00-17:00:00 18:00:00-20:00:00
08:00:00-17:00:00 18:00:00-20:00:00
09:00:00-17:00:00 18:00:00-20:00:00
Is this possible? Thanks for any help
edit: Thanks for all the answers everyone...I used Shakti's answer as it was the first one I saw but by the looks of it everyone's are pretty similar.

if(mysql_num_rows($result2) > 0)
{
$count=0;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC))
{
echo $row["open"] . "-" . $row["close"] ;
if ($count % 2 !=0 )
{
echo "<br/><br/>";
}
$count++;
}
}

try this:
$lines = 1;
if(mysql_num_rows($result2) > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"];
echo (($lines%2 == 0)?"<br/><br/>":'');
$lines++;
}
} else {
echo "Error";
}

if(mysql_num_rows($result2) > 0){
$counter = 0;
while($row = mysql_fetch_array($result2, MYSQL_ASSOC)){
echo $row["open"] . "-" . $row["close"] . " ";
if(++$counter % 2 == 0){
echo "<br/><br/>";
$counter = 0;
}
}
}

if($result2) {
$printTimes = function($r) {echo $row["open"] . "-" . $row["close"];};
$newLine = false;
while ($row = mysql_fetch_assoc($result2))
{
$printTimes($row);
echo $newLine ? '<br /><br />' : ' ';
$newLine = !$newLine;
}
}

My version of code.
$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
if(mysql_num_rows($result2) > 0) {
while (true) {
$row1 = mysql_fetch_array($result2, MYSQL_ASSOC);
$row2 = mysql_fetch_array($result2, MYSQL_ASSOC);
if (!($row1 and $row2)) break;
echo $row1["open"] . "-" . $row1["close"] . " ";
echo $row2["open"] . "-" . $row2["close"] . "<br/><br/>";
}
} else {
echo "Error";
}

$i=1;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
if ($i == 1) {
echo $row["open"] . "-" . $row["close"];
$i++;
} else {
echo $row["open"] . "-" . $row["close"] . "<br /><br />";
$i=1;
}

Output <br/><br/> only on every other iteration of the loop. (BTW, a <p> or <ul> or <div> would be more semantic.)
$counter = 0;
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
echo $row["open"] . "-" . $row["close"] . " ";
// Break line after every two items
$counter = ($counter + 1) % 2;
if ($counter == 0)
echo "<br/><br/>";
}

$sql2 = sprintf($rawsql2, mysql_real_escape_string($id));
$result2 = mysql_query($sql2);
/*These if & while statements decide whether or not the information should be displayed. If no results are returned from the query above then an alternative message is shown.*/
int row_count=mysql_num_rows($result2)
if(row_count > 0) {
while ($row = mysql_fetch_array($result2, MYSQL_ASSOC)) {
row_count--;
echo $row["open"] . "-" . $row["close"] ;
if(row_count > 0 && ($row = mysql_fetch_array($result2, MYSQL_ASSOC)){
row_count--;
echo $row["open"] . "-" . $row["close"] ;
}
"<br/><br/>"
}
} else {
echo "Error";
}
should do it, u may need to catch if there is an odd number

Related

How to display "no results found" on mysqli_fetch_assoc?

I am trying to display a message when the search finds 0 results. I have tried several different ways to do it but nothing works; I always get a blank page or manage to display the message even when search finds results.
The code:
$post = $_POST;
if (isset($post['Kohderyhmä']) &&
isset($post['Näytön_aste']) &&
isset($post['Vaikutusten_vahvuus']) &&
isset($post['Käyttökelpoisuus']))
{
$Kohderyhmä = $post['Kohderyhmä'];
$Näytön_aste = $post['Näytön_aste'];
$Vaikutusten_vahvuus = $post['Vaikutusten_vahvuus'];
$Käyttökelpoisuus = $post['Käyttökelpoisuus'];
}
else
{
echo '<!-- Virhe -->'; /*die ('<h2>Ei hakutermiä syötetty. Avaa haku</h2>');*/
}
$count = 0;
$and = "";
$query = "";
if (!empty($Kohderyhmä) && $Kohderyhmä !="Kaikki" ) {
if ($count > 0) {
$and = " AND ";
}
$count++;
$query = $query.$and."`Kohderyhmä` LIKE '%".$Kohderyhmä."%'";
}
if (!empty($Näytön_aste) && $Näytön_aste !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Näytön aste` LIKE '%".$Näytön_aste."%'";
}
if (!empty($Vaikutusten_vahvuus) && $Vaikutusten_vahvuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Vaikutusten vahvuus` LIKE '%".$Vaikutusten_vahvuus."%'";
}
if (!empty($Käyttökelpoisuus) && $Käyttökelpoisuus !="Kaikki" ) {
if ($count > 0) { $and = " AND "; }
$count++;
$query = $query.$and."`Käyttökelpoisuus` LIKE '%".$Käyttökelpoisuus ."%'";
}
if ($count > 0) {
$query = "SELECT * FROM `tietokanta` WHERE ".$query;
} else {
$query = "SELECT * FROM `tietokanta`";
}
//echo $query;
if ($results = $conn->query($query)) {
while ($row = $results->fetch_assoc()) {
echo '<h3>' . $row['Nimi'] . '</h3>';
echo $row['Kokonaisarvio'] ."<br /><br />";
echo $row['Kuvaus'] ."<br /><br />";
}
} else {
echo '<h2>Haku ei tuottanut yhtään tulosta. Muuta hakuehtoja ja hae uudestaan.</h2>';
}
I have tried to find tutorials and other tips from the internet and php.net pages but I can't find a working solution.
That is quite strange because this question is asked every week. Not to mention you can read on mysqli_query's manual page that this function's return value is always positive, no matter whether it was found anything or not
Change your code to this
if ($results = $conn->query($query)->fetch_all(MYSQLI_ASSOC)) {
foreach ($results as $row) {
echo '<h3>' . $row['Nimi'] . '</h3>';
echo $row['Kokonaisarvio'] ."<br /><br />";
echo $row['Kuvaus'] ."<br /><br />";
}
} else {
echo '<h2>Haku ei tuottanut yhtään tulosta. Muuta hakuehtoja ja hae uudestaan.</h2>';
}
Try this following code
$results = $conn->query($query);
if ($results->num_rows >= 1){
while ($row = $results->fetch_assoc()) {
echo '<h3>' . $row['Nimi'] . '</h3>';
echo $row['Kokonaisarvio'] ."<br /><br />";
echo $row['Kuvaus'] ."<br /><br />";
}
}
else{
echo '<h2>Haku ei tuottanut yhtään tulosta. Muuta hakuehtoja ja hae uudestaan.</h2>';
}

Populate multiple tables with data from mysql

I'm trying to populate multiple tables from mysql, ordering them by an id. I'm not sure how to do this and can't find much on it on here.
At the moment I am populating just one table from mysql but I've added a new column to my mysql table, which would be the specific id for each table - not sure how to loop this though.
In the predictions table I have a column called 'accid' . I'd like this column to group together a set of results with the same 'accid' and insert into an html table. How do I do this?
Here's what I have at the moment:
$result = mysql_query("SELECT results.home_team, results.away_team, results.home_id,
results.away_id, results.ht_score, results.ft_score, predictions.draw,
predictions.winningid
FROM results
LEFT JOIN predictions ON results.match_id = predictions.matchid
WHERE userid='".$_SESSION['id']."' ORDER BY home_team");
$num_rows = mysql_num_rows($result);
if($num_rows) {
$wonBet = true; #ADDED
$notlong = false;
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
if(!$row["ht_score"]) {
$halftime = "-";
} else {
$halftime = $row["ht_score"];
}
if(!$row["ft_score"]) {
$fulltime = "-";
} else {
$fulltime = $row["ft_score"];
}
echo "<td>" . $row["home_team"] . "</td>" . "<td>" . " vs " . "</td>" . "<td>" . $row["away_team"] . "</td>" . "<td>" . $halftime . "</td>" . "<td>" . $fulltime . "</td>";
$value = $fulltime;
$apart = explode('-',$value);
if($apart[0] > $apart[1] && $row["home_id"]==$row["winningid"]) {
$hometeamwin = "Win";
} else if($apart[0] < $apart[1] && $row["away_id"]==$row["winningid"]) {
$hometeamwin = "Win";
} else if($apart[0] == $apart[1] && !$row["winningid"]) {
$hometeamwin = "Win";
} else {
$hometeamwin = "lose";
#ADDED
}
if($fulltime!=$row["ft_score"]) {
$hometeamwin = "";
}
if($hometeamwin == "lose"){ #ADDED
$wonBet = false; #ADDED
}
if($hometeamwin == ""){ #ADDED
$notlong = true; #ADDED
}
echo "<td>" . $hometeamwin . "</td>";
echo "</tr>";
}
echo '</table>';
To use the same query results more than once, fetch them into an array. Then you can loop as many times as you want over the same results.
Oh - and switch to PDO / MySQLi. .. and use prepared statements..
$data = array();
$result = mysql_query("SELECT results.home_team, results.away_team, results.home_id,
results.away_id, results.ht_score, results.ft_score, predictions.draw,
predictions.winningid
FROM results
LEFT JOIN predictions ON results.match_id = predictions.matchid
WHERE userid='".$_SESSION['id']."' ORDER BY home_team");
while($dbrow = mysql_fetch_assoc($result)) {
$data[] = $dbrow;
}
foreach($data as $row) {
//Table
}
foreach($data as $row) {
//Table 2
}
Some ideas about splitting by accid
while($dbrow = mysql_fetch_assoc($result)) {
$accid = $dbrow['accid'];
$data[$accid][] = $dbrow;
}
foreach($data as $accid -> rows) {
//Table Header
foreach($rows as $row) {
//Table Row
}
//Table Footer
}

Displaying data from database in table

I am trying to display data in table form with 3 columns. Each should have a main category with some drop down lists. I get all the information to display but all is in one column and the drop down information does not display with the correct heading.
echo "<table>";
while ($row = mysql_fetch_array($result)) {
$count = 1;
if ($count = 1) {
$sCatID = ($row['CatID']);
echo "<tr valign='top'><td><b><a href='#" . $sCatID . "'>" . $sCatID . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM test_prefixSubCat WHERE CatID=$sCatID");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='#'>" . $sSub . "</a><br>";
echo "</td>";
}
$count = 2;
} elseif ($count = 2) {
$sCatID = ($row['CatID']);
echo "<td><b><a href='.$sCatID.'>" . $sCatID . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM test_prefixSubCat WHERE CatID=$sCatID");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='#'>" . $row2['Sub'] . "</a><br>";
echo "</td>";
}
$count = 3;
} elseif ($count = 3) {
$sCatID = ($row['CatID']);
echo "<td><b><a href='.$sCatID.'>" . $sCatID . "</a></b><br>";
// column 1 categories
$result2 = mysql_query("SELECT * FROM test_prefixSubCat WHERE CatID=$sCatID");
// sub-cats
while ($row2 = mysql_fetch_array($result2)) {
$sSub = ($row2['CatID']);
$sSubID = ($row2['SubID']);
echo "<dd><a href='.$sSub.'>" . $sSub . "</a><br>";
echo "</td></tr>";
}
$count = 1;
}
}
if ($count = 2) {
echo "<td> </td><td> </td></tr>";
} elseif ($count = 3) {
echo "<td> </td></tr>";
}
echo "</table>";
It doesn't seem to close the rows and table correctly... And it is also putting some of the drop down items before it displays the first heading.
If i display it in only one column it is working fine.
You should use == instead of single = in your if statements. Else it would execute everytime as that condition is always true.

PHP doesn't echo text for last row

I'm trying to write a relatively simple twitter query in php with result like this:
from:TravisBenjamin3 OR from:AshleyElisaG OR from:tncvaan ...
This code works accept it doesn't echo the second OR, also I don't want to display an OR on the last row.
$counter = 0;
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < count($row)) {
echo " OR";
}
}
Some help would be greatly appreciated. Thanks,
<?php
$tweets = array();
while($row = mysql_fetch_array($result)) {
$tweets[] = $row['twitter'];
}
if(count($tweets) > 0) {
echo "from:" . implode(" OR from:", $tweets);
}
?>
$rowCount = mysql_num_rows($result);
while($row = mysql_fetch_array($result)){
$counter++;
echo " from:";
echo $row['twitter'];
if ($counter < $rowCount) {
echo " OR";
}
}
$count = mysql_num_rows($result);
for($r = 0; $r < $count; $r++)
{
$row = mysql_fetch_array($result));
echo " from:";
echo $row['twitter'];
if ($r < ($count - 1))
{
echo " OR";
}
}
Or, even easier:
$search = "";
while($row = mysql_fetch_array($result))
{
$search .= " from:" . $row['twitter'] . " OR";
}
// Cut the last " OR"
$search = substr($search, 0, strlen($search) - 3);
echo $search;
Which is actually a poor man's implementation for implode() suggested by Aaron W..

help with php search

How would I do let the user know if there wasnt any rows found?
And if it finds (for example) 26 rows I want it to print that it found 26 hits (Your search for "hey" gave 26 results)
$name = mysql_real_escape_string($_POST['player_name']);
$q = mysql_query("SELECT * FROM players WHERE name LIKE '%$name%'");
while ($row = mysql_fetch_array($q)) {
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
Use mysql_num_rows:
$rowCount = mysql_num_rows($q);
if ($rowCount === 0)
{
echo 'Found nothing!';
}
else
{
echo "Found $rowCount rows!";
while ($row = mysql_fetch_array($q))
{
$name = $row['name'];
echo "<ul>\n";
echo "<li>" . "" .$name . " </li>\n";
echo "</ul>";
}
}
Check out mysql_num_rows
mysql_num_rows
$numberOfResults = mysql_num_rows($q);

Categories