I have a database with the following fields:
eventname (the name of the event - text)
datestart (the start date of the event - e.g. ../../..)
dateend (the end date of the event - e.g. ../../..)
I need to create a table with 3 columns, and however many rows depending on how many events there are.
Here is the code I'm using at them moment to store the database data in an array:
$allevents = mysql_query("SELECT * FROM Events ORDER BY datestart ASC");
while($event = mysql_fetch_array($allevents)){
As I said, I then need to to display the data in a table.
I'd really appreciate some help as to how to achieve this, as I'm very new to PHP.
You will want to use a foreach loop to cycle through your array and echo your html content.
you can try this :
First : Create the function for convert dates, here this code :
function convDate($str_date, $format = "d-m-Y")
{
// Ubah string ke date
$date = new DateTime($str_date);
// Kembalikan niilai dengan date_format
return $date->format($format);
}
Finaly.. you can retrieve the query with dates formatted
while($event = mysql_fetch_array($allevents)){
echo $event['eventname'] . '-' . convDate($event['datestart'], 'd/m/Y') . '-' .
convDate($event['dateend'], 'd/m/Y');
}
Are you familiar with Alex Garret's FREE ten-minute tutorials on TheNewBoston or (his own site) phpAcademy.org?
These may help you greatly:
200 PHP videos at TheNewBoston.com
PHP tutorials at phpAcademy.org
Basically:
$allevents = mysql_query("SELECT * FROM Events ORDER BY datestart ASC");
$out = '<table><tr><td>Name</td><td>Address</td></tr>';
while($event = mysql_fetch_array($allevents)){
$name = $event['name'];
$addr = $event['addr'];
$out .= '<tr>';
$out .= '<td>' .$name. '</td>';
$out .= '<td>' .$addr. '</td>';
$out .= '</tr>';
}
$out .= '</table>';
echo $out;
Related
I have got one piece of code which gives me a list of all the column names for a specific table. Can i use this list as my $row['VARIABLE'] instead of specifying every row?
The current output of the table names can be seen here this is the second paragraph of text, the first ones are my table names (USERS, ADMIN_LOGIN)
I am working on making a small script which will list all the table contents of a table but it is likely the table will change often so i want a script which can auto generate the table of contents without me having to manually re-enter it all as i have done in the second piece of code below?
Thanks guys
<?php
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
echo $table['name'] . '<br />';
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
echo "ID = ". $row['ID'] . "\n";
echo "USERNAME = ". $row['USERNAME'] ."\n";
echo "AGE = ". $row['AGE'] ."\n";
echo "LOCATION = ".$row['LOCATION'] ."\n\n";
echo "ANYTHING_ELSE = ". $row['ANYTHING_ELSE'] . "\n";
echo "EMAIL = ". $row['EMAIL'] ."\n";
echo "PROFILE_APPROVED = ". $row['PROFILE_APPROVED'] ."\n";
echo "NUMBER_OF_BATTLES = ".$row['NUMBER_OF_BATTLES'] ."\n\n";
echo "TOTAL_WINS = ".$row['TOTAL_WINS'] ."\n\n";
}
?>
Yes, you can use variables for the index values of an array. For example,
$row = array('col_name' => 'column value');
$index = 'col_name';
echo $row[$index]; // Equivalent to $row['col_name']. Prints "column value"
You should be able to accomplish what you want pretty easily using the above logic. Basically just store the column names from the first query into an array, then loop through that array to get the column names each time you print a row.
Give this a try:
// Display all sqlite column names for chosen table
$db = new SQLite3('data.db');
$tablesquery = $db->query("PRAGMA table_info(USERS)");
$columns = array();
while ($table = $tablesquery->fetchArray(SQLITE3_ASSOC)) {
$columns[] = $table['name'];
}
// Display * from USERS
$db = new SQLite3('data.db');
$results = $db->query('SELECT * FROM USERS');
while ($row = $results->fetchArray()) {
foreach ($columns as $col)
echo $col . " = " . $row[$col] . "\n";
}
I use the following in order to get a list of columns names in the order they are defined in the table. I use it to populate an insert/select when preserving data.
sel columnname
from dbc.columns
where databasename='databasename'
and tablename='tablename'
order by columnid;
I'm running a query on three columns; one column contains text, the other two contain numbers. I do a calculation on these numbers to get a new number called $average. I then spit out the result to an html table. The rows in the table are sorted in the order they come out of the database. I'm trying to sort the table so that the data is displayed from highest $average to lowest (while still be correctly associated with the correct text value from the first column).
I've tried some asort and foreach stuff, but I've only succeeded in making a mess of errors.
Any ideas as how I go about this?
Thanks.
This is the current state of play:
/ db query
if (!$result = mysqli_query($link,"SELECT quiz_name,
quiz_attempts,
cumulative_score
FROM scoredata")) {
echo("There was a problem: " . mysqli_error($link));
exit();
}
...
// got results?
if(mysqli_num_rows($result) >= 1) {
$output = "";
$output .= "<table>\n";
$output .= "<tr><th>Quiz name</th> <th>Played</th> <th>Avg. score</th></tr>\n";
while($row = mysqli_fetch_array($result)) {
$output .= "<tr><td>".str_replace('_', ' ', $row['quiz_name']) . "</td>";
$output .= "<td>" . $row['quiz_attempts'] . "</td>";
// calculate average score
$average = $row['cumulative_score']/$row['quiz_attempts'];
$output .= "<td>" . round($average,2) . "</td></tr>";
}
$output .= "</table>\n";
echo $output;
}
...
You can do calculation and sorting in your query:
SELECT
quiz_name,
quiz_attempts,
cumulative_score,
(cumulative_score/quiz_attempts) as score_avg
FROM scoredata
ORDER BY score_avg DESC
You can
let the db do the sorting (as suggested by other posters)
sort the data yourself (as you are trying to do)
let the user sort the data via JavaScript functions. My favourite is
http://www.javascripttoolbox.com/lib/table/
Make this your query
SELECT quiz_name,
quiz_attempts,
cumulative_score,
cumulative_score / quiz_attempts as avg_score
FROM scoredata
ORDER BY avg_score
I have written a calendar implementation, which is working, but displays only one set of data, I'm trying to make it appear all of the data in my select query:
$events = '';
$query = mysql_query('SELECT event_id, event_type, time, date, location, home_or_away, team_id FROM event WHERE date = "'.$deets.'"');
$num_rows = mysql_num_rows($query);
if($num_rows > 0) {
$events .= '<div id="eventsControl"><button onMouseDown="overlay()">Close</button><br /><br /><b> ' . $deets . '</b><br /><br /></div>';
while($row = mysql_fetch_array($query)){
I know it has to do with something with this, but I don't know exactly what code to imply to get 'event_type', 'time' and etc
$desc = $row['event_id'] ;
$events .= '<div id="eventsBody">' . $desc . '<br /> <hr><br /></div>';
}
}
echo $events;
?>
You can use your columns as keys in the array. So to have time, use $row['time'] and so on.
For showing multiple data, try concatenating
$desc = $row['time'] .$row['event_type']
You mean something like
$time = $row['time']
etc?
I'm not sure I've got your point
not sure what you are trying to do but if you are trying to display all columns, you can use a foreach loop
while($row = mysql_fetch_array($query)){
foreach($row as $key=>$value)
{
echo("<b>$key</b>$value<br/>");
}
}
This is for a timetable and what it does is displays the previous day's timetable and who has booked each slot (this is for a radio station.)
At the moment it displays who has booked each slot in chronological order however I would like it to say the time next to each result. The query outputs 24 rows (which is from Midnight to 23:00) and next to each slot I would like it to say (00:00, 01:00, 02:00, 03:00... 21:00, 22:00 so on so forth.)
This is my current code:
<?php
include("../config.php");
#// Timetable Clearup Variabls
$yesterday = strtotime('yesterday');
$yesterdow = date('l',$yesterday);
echo "<table width=\"580px\" class=\"board\" border=\>";
$order = "SELECT * FROM timetable WHERE day = '$yesterdow'";
$result = mysql_query($order);
// Error checking
if (!$result) {
// output error, take other action
}
else {
while ($row=mysql_fetch_array($result)){
// Append all results onto an array
$rowset[] = $row;
}
}
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td></tr>";
}
?>
Can you help?
I think we're all looking too hard at a VERY simple problem. You are already using SELECT * in your query, so you're already fetching all three columns from your table. So now, all you need to do is add another cell to each row of your table.
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td><td>" . htmlspecialchars($row['time']) . "</td></tr>";
And to make sure you are fetching your rows in the correct order, you should add an ORDER BY to your query:
SELECT * FROM timetable WHERE day = '$yesterdow' ORDER BY time
If you don't specify an ORDER BY clause, you have no guarantee that you will get the results in any particular order.
And one last thing, you are looping through the rows twice, unnecessarily. Get rid of the foreach loop and put the echo directly inside the while loop.
try this:
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . htmlspecialchars($row['time'])"</td></tr>";
I'm having some problems with the php script below that I'm currently working on. What I am trying to do is make a list with 5 events that are being shown ordered by date.
In my database I have a table with events. Each event has a date (DATETIME), an id and a name. What the php needs to do is check the table with events and filter the ones that have already passed. If an event has already passed, it's not shown. If it still has to happen, it's shown.
Now the problem is that in the do while loop, the script doesn't seem to go to a next row when it has had a run.
For example: if the database table has 10 events in it, it will show 10 times the event that's on the first row of the table when testing.
I need to know what I'm doing wrong, or if there is a way to make the row increase after each run of the loop.
<?php
$test_query_kalender = "SELECT * FROM kalender ORDER BY datum ASC";
$test_result_kalender = mysql_query($test_query_kalender);
$rij_kalender = mysql_fetch_assoc($test_result_kalender);
$vandaag_unix = time();
$datum_unix = strtotime($rij_kalender['datum']);
$i = 0; //this variable is used to insure that only 5 items are being shown on the page
do{
if($datum_unix >= $vandaag_unix) //checks if the date of the event has already passed
{
//if the date has not passed, the event will be shown
echo "<p>" . date("d-m-Y", $datum_unix) . " " . $rij_kalender['naam'] . "</p>";
$i++;
}
else
{ //if it has already passed then it should put nothing, but for testing I put a line in it
echo "<p>" . $rij_kalender['naam'] . "</p>";
}
} while(($i <= 4) && ($rij_kalender = mysql_fetch_assoc($test_result_kalender)));
echo "<p>While loop finished</p>"; //just some checking
?>
Your code loads the date once and then compares it to today each time. Move
$datum_unix = strtotime($rij_kalender['datum']);
into the loop, before the date check.
Try this:
<?php
$test_query_kalender = "SELECT * FROM kalender ORDER BY datum ASC";
$test_result_kalender = mysql_query($test_query_kalender);
$rij_kalender = mysql_fetch_assoc($test_result_kalender);
$vandaag_unix = time();
$datum_unix = strtotime($rij_kalender['datum']);
$i = 0; //this variable is used to insure that only 5 items are being shown on the page
while($rij_kalender = mysql_fetch_assoc($test_result_kalender))
{
$datum_unix = strtotime($rij_kalender['datum']);
if($datum_unix >= $vandaag_unix) //checks if the date of the event has already passed
{
//if the date has not passed, the event will be shown
echo "<p>" . date("d-m-Y", $datum_unix) . " " . $rij_kalender['naam'] . "</p>";
$i++;
}
else
{
//if it has already passed then it should put nothing, but for testing I put a line in it
echo "<p>" . $rij_kalender['naam'] . "</p>";
}
if ($i == 5) break;
}
echo "<p>While loop finished</p>"; //just some checking
?>