Displaying data from database with php that is meets requirements - php

I am designing an event feed from a calender I made. I'm using the same data from the database but to match specific dates and times.
I only want 4 events to show at once (why I specified length < 4)
Where the database value 'showFeed' is true, it only displays those rows.
and I want it to show by date time, I have odd id's for each value in the database, which might make them out of order.
My current code:
$sql = "SELECT `title`, `time`, `start`, `showFeed` FROM calender WHERE length('column') > '0'";
$result = $dbh->query($sql)->fetchAll(PDO::FETCH_ASSOC);
echo "<div class=\"eventfeed\">";
echo "<ul>";
foreach ($result as $row){
$show = $row['showFeed'];
if ($show == 1 && length.$result < 4){
echo "<li>";
echo $row['title']. "<br />";
echo $row['start'].' '.$row['time'];
echo "</li>";
}
else {
return false;
}
}
echo "</ul>";
echo "</div>";
$dbh = null;
echo json_encode($return);
?>
I'm getting results and no errors from the database, but I'm only seeing one return on $results.
I honestly, do not have a clue where else to go from here. I'm lost.

For 1+.2.+3. modify your query to SELECT title, time, start, showFeed FROM calender WHERE length('column') > '0' and showFeed=1 and time<current_timestamp ORDER BY time DESC LIMIT 0,3 and remove your if (...) statement.

I don't know if this is your actual code, but you should determine the length of an array by doing $result.length instead of the other way around.
Also, you can limit the number of results in your query using 'LIMIT 4' at the end of your query. That way MySQL only returns 4 results and you don't have to worry about that in your code, just print everything.

Related

Nested while loop in PHP is not working for MySQL database queries

All the whole day I'm trying to solve this problem but still no luck.
The scenario is: I am developing a vertical menu which should query groups and items of those groups in a menu respectively, but groups are being populated without its items.
Code was written in the following way:
$data1 = mysql_query(select groupnames from groups where categoryy='Agriculture');
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$data2==mysql_query(select itms from groupitems where categoryy='Agriculture' and groupname='$info1[0]');
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
In the above code, groups are being populated nicely but no items from groupitems table are being populated. If I write Grain (Grain is one of the group of agriculture in my database) instead of groupname=$info1[0] then it works. But it should be got dynamically from the query.
Please help, I'm in trouble.
at last its solved! here's the code:
<?php
include "aPannel/dbconn.php";
$query="select GroupName from categorygroup where categoryy='Agriculture'";
$i=0;
$result=mysql_query($query);
$num=mysql_num_rows($result);
$groupname=mysql_result($result ,$i ,"GroupName");
mysql_close();
if ($num=="0") echo "<p>Sorry, there are no groups to display for this Category.</p>";
else
{
echo "<p>There are currently <strong>$num</strong> groups represented in our database.</p><br>";
while($i < $num)
{
$groupname=mysql_result($result ,$i ,"GroupName");
include("aPannel/dbconn.php");
$query2 = "SELECT subcategory FROM groupsubcategory WHERE groupname='$groupname'"; // count number of items in each group
echo $query2 . "<br/>";
$resultt=mysql_query($query2);
$countt=mysql_num_rows($resultt);
mysql_close();
echo $countt . "subcategories" . "<br/>"; // display number of items
$i++;
}
} // end if results
?>
Your queries are not wrapped around double-quotes (" ") . Always remember that what you pass to mysql_query method is a string argument. And also $data2==.... seems wrong.
So, change the code like this
$data1=mysql_query("select groupnames from groups where categoryy='Agriculture'");
while($info1=mysql_fetch_array($data1))
{
echo $info1[0];
$infoTemp=$info1[0];
$data2=mysql_query("select itms from groupitems where categoryy='Agriculture'
and groupname='$infoTemp'");
while($info2=mysql_fetch_array($data2))
{
echo $info2[0];
}
}
I hope it should work
EDIT: Also are you sure column itms in second query or items ?
EDIT: added temporary variable

Showing database entries on a PHP calendar

I'm creating a web-based booking system where a user can add bookings into a database, and the details stored in the database are (among others) "DateBooked, StartTime, EndTime, Room".
Here's the bit that pulls the relevant info for the day the user has clicked on from the database:
$query="SELECT * FROM bookings WHERE DateBooked = '{$year}-{$selectedmonth}-{$selectedday}'";
$result = mysql_query($query);
$todayarray = mysql_fetch_array($result);
And the PHP:
$roomcount = 4;
$room = 1;
while ($room <= $roomcount)
{
echo "\n<div class=\"roomtimes\">";
echo "\n<table border=1>";
echo "\n<tr><th class=\"titlecell\">Room $room</th></tr>";
$cellnum = 10;
while ( $cellnum < 23 )
{
echo "\n<tr>";
echo "\n<td class=\"linkcell";
if ($selectedtime==$cellnum)
{
echo " selectedcell";
}
echo "\">";
echo "$cellnum:00</td>";
echo "\n</tr>";
$cellnum++;
}
$room++;
echo "\n</table>";
echo "\n</div>";
}
So my question is, how can I add a bit of text saying "BOOKED" inside each table cell if a entry exists for that room and the number in that cell is in between the start time and end time of that booking?
I'm new to this site so let me know if I've done something wrong or you need more information, thanks!
You need to divide the cell content html and insert your "BOOKED" text there. And I suggest you use mysql_fetch_assoc so you get and associative array and it's easier to get the fields. If I'm understanding your code correctly you might be able to use something like this. This example is a replacement for the row that has the link output in it. I've used mysq_fetch_assoc here to get the StartTime and EndTime fields from the database. You might need to change the fields a bit depending in what data format they are.
echo "$cellnum:00";
if ($todayarray['StartTime'] <= $cellnum && $todayarray['EndTime'] >= $cellnum && $todayarray['Room'] == $room) echo 'BOOKED';
echo "</td>";

query to display four random data from database

This is my php code for displaying the data from the database. I am trying to display the random data from table.
<?php
include('connection.php');
$query="SELECT * FROM `banner_ad` ORDER BY RAND() LIMIT 4";
if($query_run=mysql_query($query))
{
$i=4;
$rows=mysql_fetch_array($query_run);
while($rows)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
}
} else {
echo'<font color="red"> Query does not run. </font>';
}
?>
But the problem with this code is:
It is displaying nothing. But whenever I am trying to make a little modification in the above code like:
<?php
include('connection.php');
$query="SELECT * FROM `banner_ad` ORDER BY RAND() LIMIT 4";
if($query_run=mysql_query($query))
{
$i=4;
$rows=mysql_fetch_array($query_run);
while($rows && $i<4)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
$i=$i-1;
}
} else {
echo'<font color="red"> Query does not run. </font>';
}
?>
It is displaying the same single output 4 times. But It has to display the four different output. So, Please tell me where is the bug ... And how am i suppose to display four different random output.
Any help will be appreciated
Thanks in advance
Your first Query is fine, but the while is wrong:
Just look at what you did here:
$rows=mysql_fetch_array($query_run);
while($rows)
{
echo $rows['banner_no'];
echo $rows['banner_name'];
echo "<a href=\"".$rows['Banner_website_url']. "\">";
echo "<img src=\"".$rows['banner_image_url']."\" width=\"100px\" height=\"100px\">";
echo"</a>";
}
this will end in an "infinite Loop" cause $rows will always be set.
What you need is:
while($rows=mysql_fetch_array($query_run))
this will cause myslq_fetch_array to return a new line everytime the while condition is checked. And if all 4 rows are returned, $rows will be false and the loop is stoped.
And to be complete:
In your second Example you are exactly iterating 4 times over the SAME row, you just fetched one time by calling myslq_fetch_array.
A possible solution to that will be to fetch the row again INSIDE the while-loop:
$i=4;
while ($i>0){
$rows = mysql_fetch_array(...);
$i--;
}
However you should prefer the first solution, because then you dont need to take care that the result count matches your iterator variable.
sidenode: Call it $row without the 's', because you always just getting ONE row back.
Try constructing while loop like so
while(($rows=mysql_fetch_array($query_run)) !== false)
Using ORDER BY RAND() is not the best practice because the random value must be generated for every single row. Better way would be to randomly generate primary keys (e.g. ID) in PHP and then select according to them.
$random_id = rand(1,4);
$query="SELECT * FROM `banner_ad` WHERE id = $random_id";
Will select exactly one random row. Similar whould be selecting multiple rows using IN statement.
More info you can find here.
$query_run=mysql_query($query);
if(!$query_run)
{
echo'<span style="color:red">Query did not run.</span>';//font tag is ancient
}
else
{
if(mysql_num_rows($query_run) > 0)
{
while($row = mysql_fetch_assoc($query_run))
{
echo $rows['banner_no'];
echo $rows['banner_name'];
// more...
}
}
}

Displaying results after MySQL JOIN query with PHP

$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[]=$row;
}
echo $rows[0][1].$rows[0][0];
/* for($i=0;$i<=10;$i++)
{
echo $rows[i][1].$rows[i][0];
}
*/
This script is supposed to show the last 10 messages in a chat.What I'm doing is getting the Name of the user from the users table and the text from the message table and I want to display them in my chat window.Right now I have only 4 messages recorded and don't know how this affects the whole script I should implement a check for this too, but the bigger problem is that when i use echo $rows[0][1].$rows[0][0]; the info is displayed correctly, but when I try to make a loop so I can show tha last 10 (I tried the commented one) then nothing is displayed.I thought at least when I use this loop I'll see the 4 recorded messages but what really happen is a blank window.Obvously I have the info recorded in $rows[] and can echo it, but don't understand why this loop don't work at all.I'll appreciate if someone can help me with this and with the check if the messages are less then 10.
Thanks.
Leron
P.S
Here is the edited script, thanks to all of you, I need the array because otherwise the most recent message is shown at the top which is not an opiton when I use it for diplaying chat masseges.
for($i=10;$i>=0;$i--)
{
if($rows[$i][1]!="" || $rows[$i][0]!="")
{
echo $rows[$i][1].' : '.$rows[$i][0];
echo "</br>";
}
}
Your FOR loop was running 11 times even if only 10 records. The second clause should be a < instead of <=. Plus the $ was missing on the i variable.
For example sake, you don't really need to make an array from the rows, and you can refer to the fields by name:
while($row = mysql_fetch_array($result))
{
echo $row['name'] . ' says: ' . $row['message'] . '<BR>';
}
why not just do
while($row = mysql_fetch_array($result))
{
echo $row[1]." ".$row[0];
}
Your query, auto limits it to the last 10, this will then show anything from 0 to 10 which get returned.
PS I added a space between username and message for readability
You need $ symbols on your i variable:
for($i=0;$i<10;$i++)
{
echo $rows[$i][1].$rows[$i][0];
}
A more robust solution would be like this:
$sql = "SELECT messages.text, users.name FROM messages INNER JOIN users ON messages.user_id=users.id ORDER BY messages.ms_id DESC LIMIT 10";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
echo $row[1].$row[0];
}

How do I loop through results and display day of the week once at every change in day using php and mysql?

with my current query and loop:
$sched = mysql_query("SELECT *
FROM `shows`
ORDER BY `shows`.`show_time` ASC")
or die(mysql_error());
echo "<ul>";
while($row = mysql_fetch_array($sched)){
echo "<li><a href=\"#$row[id]\">";
echo $row['title'];
echo "</li>";
}
echo "</ul>";
This works great for displaying my results like this:
Name of show 1
Name of show 2
Name of show 3
However, I want to add an item to the list at the beginning of every change in day so it would display as follows:
Monday
Name of show 1
Name of show 2
Tuesday
Name of show 3
Wednesday
Name of show 4
I can't quite wrap my brain around the loop needed to do this. It might be helpful to know that the field 'show_time' is a datetime type, so it has the information for both time and day of week.
Thanks.
Simple tweak:
echo "<ul>";
$curDay='';
while($row = mysql_fetch_array($sched)){
$d=date('l',strtotime($row['show_time']));
if($d!=$curDay){
echo '<li>'.$d.'</li>';
}
$curDay=$d;
echo '<li><a href="#',$row['id'],'">',$row['title'],"</li>";
}
echo "</ul>";
Initialize $curDay, and then each time through the loop, check to see if the particular day is different than the last time through the loop (or different from the initial value)
The best way to do this is to keep a flag in your loop, and compare to the previous value.
Eg.
$previousDay = '';
while($row = mysql_fetch_assoc()) {
if ($previousDay != date('l', $row['show_time'])) {
echo '<h2>' . $date('l', $row['show_time']) . '</h2>';
}
...
$previousDay = date('l', $row['show_time']);
}
Adjust your query to sort by show_time first.
"SELECT * FROM `shows` ORDER BY `show_time`, `shows` ASC"
Then keep track of the current day as Shad suggests, parsing show_time to determine the day.

Categories