Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

php - Populating an HTML table with MySQL data, linked by calendar date

I am using the code below to generate a simple HTML table that displays the next 90 calendar days. Each day is a row in this simple table.

$now = time();
echo "<table>";
for ($i=0;$i<90;$i++)
{
   $thisDate = date("d/m/Y",$now + ($i*86400));
   echo "<tr><td>".$thisDate."</td></tr>
";
}
echo "</table>";

Also, I have a MySQL table with the following fields:

event           varchar(1000)   
datescheduled   date    

How can I make a second column in the aforementioned HTML table, containing "event" from the MySQL table, matched by date?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This can be tackled in numerous ways. Consider this example:

PHP

<?php
$con = mysqli_connect("localhost","dbuser","dbpass","database");
$query = mysqli_query($con, "SELECT * FROM event");

// First build the array of events, put the dates in keys, then the values as events
$events = array();
while($result = mysqli_fetch_assoc($query)) {
    $events[$result['datescheduled']] = $result['event'];
}

?>

// Structure should be something like this:
Array
(
    [2014-05-02] => Day of lorem
    [2014-06-02] => Day of ipsum
    [2014-07-02] => Day of days
)

HTML

<!-- the compare selected values on the current loop, check its keys -->

<?php $now = time(); ?>
<table border="1" cellpadding="10">
<?php for($i=0;$i<90;$i++): ?>
    <?php $thisDate = date("Y-m-d", $now + ($i*86400)); ?>
    <tr>
        <td><?php echo $thisDate; ?></td>
        <td><?php echo array_key_exists($thisDate, $events) ? $events[$thisDate] : ''; ?></td>
</tr>
<?php endfor; ?>
</table>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...