UPDATED PHP
Seems to be something to do with Angle brackets...
My first time coding my own PHP and SQL, but having a bit of trouble, so not even plugged HTML in yet. I'd imagine I'm not escaping something right, or my formatting is miles off... or something REALLY simple.
I'm basically trying to get a list of events working, and many posts on it here, just can't put them all together to get a result.
So I'm looking for
YEAR
MONTH
EVENT
MONTH
EVENT
EVENT
YEAR etc
My HTML looks like this...
<div id="year">
<p class="vert">YEAR</p>
<div id="month">
<h1>MONTH</h1>
<div class="event">
<p>DATE START - DATEEND IF DIFFERENT/AVAILABLE</p>
<div class="eventmain">
<img class="flag" src="./img/defaultflag.png">
<img class="open" src="./img/plus.png">
<img class="close" src="./img/minus.png">
<h2> Event Name </h2>
<div class="eventdetails">
<p>FORMAT</p>
<p>INFO</p>
<p>CONTACT</p>
<p>EMAIL</p>
<p>WEBSITE</p>
</div> <!-- close div event details -->
</div> <!-- close div event main -->
</div> <!-- close div event -->
</div> <!-- close div month -->
</div> <!--close div year-->
With the following DB fields in the DB debate_calendar, table events
event_name, event_startdate, event_enddate, event_flag, event_format, event_info,event_contactinfo, event_email, event_website, event_reg
I have the following PHP
<?php
$server = "localhost:8889";
$user = "root";
$passwd = "root";
$db_name = "debate_calendar";
$table_name = "events";
$conn = mysql_connect($server, $user, $passwd) or die("Couldn't connect to SQL Server on $server");
mysql_select_db($db_name, $conn);
if (!$conn)
{
exit("Failed to Connect to $dbConnection");
}
else
{
echo "Database Connected";
}
$query = "SELECT * FROM `debate_calendar`.`events` WHERE event_date > NOW() ORDER BY event_date DESC";
$result = mysql_query( $query );
$current_month = '';
$current_year = '';
while ($event = mysql_fetch_assoc($result)) {
$year = date('y', $event['event_startdate']);
if($current_year != $year)
{
$current_year = $year;
echo ("<h1>" .$current_year. "</h1>");
}
$month = date('m', $event['event_startdate']);
if($current_month != $month)
{
$current_month = $month;
echo '<h2>' . $current_month . '</h2>';
}
echo '<p>' . $event['event_name'] . '</p>';
}
mysql_close($con);
?>
But all it's generating is...
NOW() ORDER BY event_date DESC"; $result = mysql_query( $query ); $current_month = ''; $current_year = ''; while ($event = mysql_fetch_assoc($result)) { $year = date('y', $event['event_startdate']); if($current_year != $year) { $current_year = $year; echo ("
" .$current_year. "
"); } $month = date('m', $event['event_startdate']); if($current_month != $month) { $current_month = $month; echo '
' . $current_month . '
'; } echo '
' . $event['event_name'] . '
'; } mysql_close($con); ?>
echo <p> Your Database is Connected</p\><br/\>
You forgot to add the quotes ("")
try this:
echo "<p> Your Database is Connected</p\><br/\>";
You didn't quote your last echo before $qry. Also, there are some extra characters in your query that will make it fail. This is how it should look:
SELECT * FROM `debate_calendar`.`events` WHERE event_date > NOW()
ORDER BY event_date DESC
Also, you can get year/month/date parts of any DATE/DATETIME type field directly from SQL if you want:
SELECT year(event_date) AS event_year, month(event_date) AS event_month ...
The answer was a schoolboy error.
I had moved the site from one MAMP install to a fresh one,
where the htaccess hadn't been changed to allow html files to be opened as PHP.
Still lots of errors in the code, but this was the underlying problem
Simple as that!!
Related
I need to group all rows with matching roomcode. When I also group resort, it acts like it disables the grouping of roomcode and only gives me the results of the first row with a roomcode.
How can I group the resort column and still group matching roomcode columns? If I ungroup my resort code the query works correctly, but then I can't create separate divs for differing resorts.
The user is searching a date range, hence having multiple rows with the same roomcode, which fetches my points. This is why I am getting the sum of those points. My current way of grouping each resort for output HTML purposes is breaking that. I don't necessarily have to group the resorts, I just need each room at each resort created within its own DIV set. I have a basic example below.
Ideal HTML output
<div id="results">
<div id="resort resortcode">
<div id="roomresults">
<div id="room1"></div>
<div id="room2"></div>
</div>
</div>
<div id="resort2 resortcode2">
<div id="roomresults2">
<div id="room3"></div>
<div id="room4"></div>
</div>
</div>
</div>
This PHP code will group each set of results by resorts, but jacks up my price.
<?php
include("dbh.php");
mysqli_select_db($con, "checkavail") or die ("no database");
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$occupants = $_POST['occupants'];
$sqlCommand=
"SELECT
MIN(staydate) AS checkin,
MAX(staydate) AS lastnight,
MIN(available) AS available,
ra.resort AS resortcode,
ri.resort,
ri.room,
ri.roomcode,
ri.view,
SUM(ra.points*'20') AS price,
ri.sqfoot,
ri.description,
ri.bedding,
ri.amenities,
ri.sleeps,
ri.sleep_details,
ri.layout_img AS layoutimg,
ri.room_img AS roomimg,
ri.roomimg_thumb
FROM resort_availability AS ra
LEFT JOIN room_info AS ri ON (ra.room = ri.roomcode)
WHERE staydate >= '$checkin' AND staydate = '$checkout'
AND sleeps >= '$occupants'
GROUP BY ri.roomcode
ORDER BY ri.resort, points
";
$result=mysqli_query($con, $sqlCommand) or die(mysqli_error($con));
$data = array();
while($row = $result->fetch_assoc())
{
$itemName = $row["resort"];
$resortCode = $row["resortcode"];
if ( !array_key_exists($itemName, $data)) {
$data[$itemName] = array ();
}
$data[$itemName][] = $row;
}
foreach ($data as $itemName => $rows) {
echo '<div class="resort ' ,$resortCode , '">';
echo '<div class="resort_header"><h1>', $itemName, '</h1></div>';
foreach ($rows as $row){
if ($row['available'] > 0) {
$roomresult = '<div class="room_result roomavailable">';
$available = '<button class="available">BOOK NOW</button>';
$filtavail = 'available';
}
else {
$roomresult = '<div class="room_result roomsoldout" style="">';
$available = '<button class="soldout">SOLD OUT</button>';
$filtavail = 'soldout';
}
echo $roomresult;
echo '<div class="room_thumb"></div>
<div class="room_info"><h4>'
,$row['room'], '-' ,$row['view'] ,
'</h4></div>
<div class="price"><center><h3>','' ,$row['price'],'</h3>' , $available ,'</center></div></div>';
}
echo '</div>';
}
?>
This PHP code gives me accurate results but does not allow me to Create a div with results based on each resort IE, I don't know how to create a Header with the resort name, separating each set of rooms by resort as it is in the first example.
<?php
include("dbh.php");
mysqli_select_db($con, "checkavail") or die ("no database");
$checkin = $_POST['checkin'];
$checkout = $_POST['checkout'];
$occupants = $_POST['occupants'];
$sqlCommand=
"SELECT
MIN(staydate) AS checkin,
MAX(staydate) AS lastnight,
MIN(available) AS available,
ra.resort AS resortcode,
ri.resort AS resort,
ri.room,
ri.roomcode AS roomcode,
ri.view,
SUM(ra.points) AS points,
ri.sqfoot,
ri.description,
ri.bedding,
ri.amenities,
ri.sleeps,
ri.sleep_details,
ri.layout_img AS layoutimg,
ri.room_img AS roomimg,
ri.roomimg_thumb
FROM resort_availability AS ra
LEFT JOIN room_info AS ri ON (ra.room = ri.roomcode)
WHERE staydate >= '$checkin' AND staydate < '$checkout'
AND sleeps >= '$occupants'
GROUP BY ri.resort, roomcode
ORDER BY ri.resort, points
";
$result=mysqli_query($con, $sqlCommand) or die(mysqli_error($con));
while($row = $result->fetch_assoc()) {
$pricecalc = ($row['points'])*20;
$price = number_format($pricecalc, 2);
//RESULTS BOX
if($row['available'] < "1"){
echo '<div id="'.$row['roomcode'].'-'.$row['resortcode'].'"','class="soldout roomresults room'.$row['resortcode'].'">';
}
if($row['available'] > "0"){
echo '<div id="'.$row['roomcode'].'-'.$row['resortcode'].'"','class="available roomresults room'.$row['resortcode'].'">';
}
//IMAGE BOX
echo '<div class="thumbnail"><img height="90" src="',$row['roomimg_thumb'],'">';
echo '</div>';
//ROOM DETAILS
echo '<div class="roomdetails">';
echo '<h4>'.$row['room'].' - '.$row['view'].'</h4>';
echo '<p>Sleeps: '.$row['sleep_details'].'</p>';
echo '<p class="clickfordetails">Click Image For Room Details</p>';
echo '</div>';
//PRICING BOX AND SUBMIT BUTTON
echo '<div class="price">';
echo '<h3>$',$price,'</h3>';
if ($row['available'] < "1"){
echo '<button type="button" class="soldoutbtn">SOLD OUT</button>';
}
if ($row['available'] > "0"){
echo '<button type="button" class="booknowbtn">BOOK NOW</button>';
}
echo '</div,$row>';
echo '</div></div>';
};
?>
Yes group by will give you the 1st record of the same group.
In my understanding , you want to show all the data but place all the records with the same roomcode together.
In that case, please change
GROUP BY ri.roomcode
ORDER BY ri.resort, points
to
ORDER BY ri.roomcode, ri.resort, points
I have read multiple stack overflow answers but still cant find one specific to my needs. Some are outdated. I am using bootstrap and I want to display the first set of records which I am doing by using 'LIMIT 9'. I just have no idea how to get the next 10 records and every 10 records after that to display once the link at the bottom has been clicked. I don't want to open a new page for every 10 records.
`<div class="container-fluid">
<div class="row row-fluid">
<div class="col-xs-12 col-sm-12 col-md-8 offset-md-2 col-lg-8 offset-lg-2">
<h2>List of current Database entries</h2>
<?php
$servername = "localhost";
$username = "xxxxx";
$password = "xxxxxx";
$dbname = "xxxxxxxxx";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, business_name, email, website, phone FROM table LIMIT 0, 9";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table class='table table-striped'>";
echo "<thead>";
echo "<tr>";
echo "<th>ID</th><th>Business Name</th><th>Email</th><th>Website</th><th>Phone</th>";
echo "</tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr>";
echo "<td>"."id : ". $row["id"]."</td>
<td>".$row["business_name"]."</td>
<td>".$row["email"]."</td>
<td>".$row["website"]."</td>
<td>".$row["phone"]."</td>";
echo "</tr>";
}
echo "</tbody>";
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Next 10
</div>
</div>
</div>
That is what I have so far. I would really appreciate some help
This image shows how it looks nowimage of how it looks I dont want people to leave the page for the results. Thank you.
You would usually get a GET/POST parameter specifying current "page".
For example
$page = isset($_GET['page']) ? intval($_GET['page']) : 1; // current page, default is 1
$perPage = 10; // records per one page
$fromLimit = ($page - 1)*$perPage;
$toLimit = $perPage*$page;
$sql = ".... LIMIT $fromLimit, $toLimit";
I have a feeling that you are new to php programming, so be sure to take time and check this:
How to prevent SQL injection
The point is you need a dynamic parameter that you give to a php page so you can dynamically change the content.
Links to your pages would look something like that:
1
2
3
please try to remplace this code:
$sql = "SELECT id, business_name, email, website, phone FROM table LIMIT 0, 9";
to:
if ($_GET['pagenum'] > 0){
$a = (int) filter_var($_GET['pagenum'],FILTER_SANITIZE_NUMBER_INT);
}else{
$a = 0;
}
$Startnumber = ($currectid * 10); $limit_read = ($Limit_number + 10);
$sql = "SELECT id, business_name, email, website, phone FROM table LIMIT ".$Startnumber .", ".$limit_read ;
I am working on creating a drop down button that lets one select the year from a list of options in order to sort through a data table. The code (reproduced below) keeps repeating the last year available, I can't seem to figure out why it is doing this. I am using PHP to pull from a MySql database.
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Select Year</button>
<div id="myDropdown" class="dropdown-content">
<?php
$year = array();
while($subject = mysqli_fetch_assoc($subject_set)) {
$i=0;
$exists = 0;
$n = count($year);
while($i < $n){
if ($subject['year'] == $year[$i]){
$exists = 1;
}
$i++;
}
if($exists == 0){
$year[$n] = $subject['year'];
echo " {$subject['year']} ";
}
}
$subject_set = find_all_subjects();
?>
</div>
</div>
i have made a webpage using html and php that allows users to book appointments, but my slots are every 30 minutes but the way i am currently doing it will not add 30 minutes on to the database
<?php ob_start( ); ?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="Nav.css">
<title>Book Barber</title></head>
<body>
<?php
echo " <div class='navigation'><a href='BarberHomeScreen.php'>Home</a><div class='dropdown'><button class='dropdownButton'>Account<i class='fa fa-caret-down'></i></button><div class='dropdownContent'><a href='MyAccount.php'>My Account</a><a href='SignOut.php'>Sign Out</a></div></div></div>";
?>
<h1>Booking a barber appointment for <?php session_start();echo $_SESSION['customerName'];?></h1>
<form method="POST" action="#">
<input type="date" name="selectDate" />
<input type="submit" name="submitDate"/>
<?php
if(isset($_POST['submitDate'])){
//if the submit button has been pressed, connect to the db
//and search for all the available tables on that selected day
$conn = mysql_connect(localhost, "root", "");
if(!$conn){
die("Could not connect: " . mysql_error());
}
$selectedDb = mysql_select_db('booking', $conn);
if(!$selectedDb){
die("Can't use the selected db: " . mysql_error());
}
//selects all the bookings for the date chosen in the form
$query= "SELECT * FROM booking WHERE BookingDate = '" . $_POST['selectDate'] . "' ORDER BY customerID, BookingTime";
$result = mysql_query($query);
//stop php while table headers outputted
?>
<table border="1">
<tr></tr>
<tr>
<th>Barber</th>
<th>9:00</th>
<th>9:30</th>
<th>10:00</th>
<th>10:30</th>
<th>11:00</th>
<th>11:30</th>
<th>12:00</th>
<th>12:30</th>
<th>13:00</th>
<th>13:30</th>
<th>14:00</th>
<th>14:30</th>
<th>15:00</th>
<th>15:30</th>
<th>16:00</th>
</tr>
<?php //start php again to output the bookings available or not
/*The next bulk of php is outputting the table showing which slots are booked and which are available.
two while loops are needed, the outer one loops through the tables, the inner while loops through
each of the times for the table.
Then while the loops are repeating they check if this booking
is for the current timeslot and table being looked at. If so it puts an X in the td and carries out mysql_fetch_assoc
again to get the next booking from the $result. This continues for each of the slots in the table.
*/
$row = mysql_fetch_assoc($result);
$time = 9;
echo "<tr>";
echo "<td>" . $count . "</td>";
while($time <= 16){//time begins at 9 and stops at 16. Would be better to get this from the db too.
if((Time($row['BookingTime'])==$time)){
echo "<td style='background-color:lightCoral'>X</td>";
$row = mysql_fetch_assoc($result);
}else{
echo "<td style='background-color:lightGreen'><a href='MakeBarberBooking.php?&time=" . $time. "&date=" . $_POST['selectDate'] ."'>Book</a></td>";
}
$time=$time+0.5;
}
echo "</tr>";
}//end while
//end if submit pressed
?>
</table>
</form>
</body>
</html>
<?php
ob_end_flush( );
?>
the system loops through each time slot using the time=time+0.5 but that records the time as 10.5 instead of 10:30 for instance
Besides that ProEvilz already commented about Sql Injection, adding .5 will not magically make it into a date/time format.
Work with the date object (or DateTime class in php5.4+) and for each iteration you use this:
Initial value would be
$currentTime = "09:00";
$nextTime = date("H:i", strtotime($currentTime ." +30 MINUTE"));
$nextTime would be 09:30..
You could use PHP's DatePeriod function.
First create the start and end times. Then create a date interval and loop over the object.
N.B. its worth noting you may need to add the interval to the dtEnds to get the loop to include the last period.
// set format the date string is formatted as
$format = 'Y-m-d H:i:s';
// set the start and end date
$dtStarts = new DateTime();
$dtEnds = new DateTime::createFromFormat($format, '2017-12-01 06:00:00');
// create intervals that we would like to loop over
// i.e. 1 day at a time, or every 45 minutes
$dtInterval = DateInterval::createFromDateString('1 days');
$dtIntraDayInterval = DateInterval::createFromDateString('45 minutes');
// set day period/range
$dpPeriod = new DatePeriod( $dtCalStarts, $dtInterval, $dtCalEnds );
// loop oveer each period in the day
foreach ( $dpPeriod as $dtDay ){
echo "<pre>";
var_dump($dtDay);
echo "</pre>";
}
I'm working on an event scheduler site and I am currently stuck as I'm using a Months table (with id & month as the headers) to group my results by month. Due to this, if I try to schedule an event for January 2016, it successfully puts it into the month I choose as intended, but understandably puts it into 2015.
I'm looking to get some help on extending this beyond the end of the current year and adding functionality for different years.
I would happily use another method than using my current table setup, so any tips or suggestions would be appreciated.
Current code is as follows:
<?php include 'includes/connect.php';
include 'includes/header.php';
$curMonth = date("n"); ?>
<b>Upcoming Trip Information:</b><br><br>
<?php
$res = mysql_query("SELECT * FROM months ORDER BY id");
while ($rows = mysql_fetch_array($res)) {
if($rows['id'] >= $curMonth ){
$monthname = $rows['month']; ?>
<table cellpadding="0" cellspacing="3" width="100%">
<tr>
<td>
<?php
$tid = $_GET['transporter'];
$check = mysql_query("SELECT * FROM trips WHERE monthname(start_date) = '" . $rows['month'] . "' AND tid = '$tid'");
$check = mysql_num_rows($check);
if ($check < 1) {
echo "";
} else { ?> <h2><?php echo $monthname; ?><?php } ?></h2></td></tr> <tr> <?php $cmonth = date('F');
$tid = $_GET['transporter'];
$res1 = mysql_query("SELECT * FROM trips WHERE monthname(start_date) = '$monthname' ORDER BY start_date");
while ($rows = mysql_fetch_array($res1)) {
$trid = $rows['trid'];
$trip_start = $rows['trip_start'];
$trip_end = $rows['trip_end'];
$start_date = $rows['start_date'];
$end_date = $rows['end_date'];
$colour = $rows['colour'];
$stime = strtotime($start_date);
$startt = date("l jS", $stime);
$etime = strtotime($end_date);
$endt = date("l jS", $etime); ?>
<td valign="middle" style="height: 100px; background-color: #4b99ed; text-align: center;">
<div style="font-size: 17px; color: #ffffff;"><?php echo $trip_start; ?> to <?php echo $trip_end; ?></div>
<div style="font-size: 15px; color: #ffffff;"><?php echo $startt; ?> - <?php echo $endt; ?></div>
</td>
<?php } } } ?>
</tr>
</table> <?php include 'includes/footer.php'; ?>
If possible I would like to maintain the results layout..
You could try, instead of using a months table, using the start_date column of your trips table.
Try changing your query:
SELECT trips.*, DATE_FORMAT('%M, %Y', start_date) as `dt`
FROM trips
WHERE tid = '$tid' /* This is bad, please prepare or escape your variables*/
ORDER BY `dt` ASC
You then won't have to do the first query to get all the months and loop through them. If you must have empty containers for each month, try using that query, but loop through a PHP-generated array of months to display.