I try to break my table booking into 3 tables to enable normalization.
Well, I encounter problem when I try to generate 1 bookingID for multiple booking.
I am confuse with looping.
Scenario: customer reserved 2 booths, A01 and A02, (A01 booked from day 1 to day 3, while A02 booked from day 1 to day 2).
System will process the booking, it should generate 2 bookingIDs for A01 and A02, and generate bookingScheduleID for A01_D1, A01_D2, A01_D3 (carry bookingID A01) and A02_D1, A02_D2 (Carry bookingID A02).What should I do to loop and get the following result?
My coding
<?php
include('db.php');
// check array and insert parrentBookingID
// check submitted totalDay
if (isset($_POST['submit']) && isset($_POST['totalDay'])) {
//check day exist or not
$cDay=$_POST['totalDay'];
for ($i=1; $i<=sizeof($cDay); $i++) { //check array size
$temp=0;
foreach ($cDay as $dy) {
$checkDay = $dy;
$checkDay = explode(" ", $checkDay);
echo $checkDay[0]; // boothAlias
echo $checkDay[1]; // boothID
echo $checkDay[2]; // day
$checkDayResult = mysql_query(
"SELECT * FROM bookingDetail WHERE boothID='$checkDay[1]'
and day='$checkDay[2]' and username='$user'"
);
$num_rows_check = mysql_num_rows($checkDayResult);
if ($num_rows_check) {
echo "Exist";
$temp += 1;
} else {
$temp += 0;
}
}
} //FOR LOOP CHECK ARRAY SIZE
echo "temp".$temp;
if ($temp != 0) {
echo "Please try again";
} else {
// insert parentBookingID
$parent = mysql_query(
"INSERT into booking (custNo,eventID,dateBook)
VALUES ('$userID','$event',NOW())"
);
$parentBookID = mysql_insert_id();
// End check array and insert parrentBookingID
// check booth, create bookingDetailID
$booth = $_POST['totalDay'];
//for loop check array size for check repeat booth.
for ($j=1; $j <= sizeof($booth); $j++) {
$current = explode (" ", $booth);
} // end for loop check repeat loop.
// end check booth.
$totalDay = $_POST['totalDay'];
$allBooth = "";
foreach ($totalDay as $d) {
echo $d;
$bookingInfo = $d;
$bookingInfo = explode(" ", $bookingInfo);
echo $bookingInfo[0]; // boothAlias
echo $bookingInfo[1]; // boothID
echo $bookingInfo[2]; // day
$result = mysql_query(
"SELECT * FROM bookingDetail WHERE
boothID='$bookingInfo[1]' and day='$bookingInfo[2]'
and username='$user'"
);
$num_rows = mysql_num_rows($result);
if ($num_rows) {
echo "Exist";
} else {
$str = "INSERT INTO bookingDetail
(username, custNo, eventID, date, day,
boothAlias, boothID, parentBookID) VALUES ('$user',
'$userID','$event',NOW(),'$bookingInfo[2]',
'$bookingInfo[0]','$bookingInfo[1]','$parentBookID');";
$res = mysql_query($str);
if ($res) {
echo 'Success';
} else {
echo 'Failure';
}
$allBooth = substr($allBooth, 0, -2);
echo "<p>Booth(s): <strong>$allBooth</strong>
<strong>$user</strong> <strong>$event</strong>
<strong>$userID</strong></p>\r\n";
}
}
} // close check $temp
header("refresh:5;url=mybooking.php");
echo "<img src='loading16.gif' style='margin-top:8px; float:left'/>";
echo 'You\'ll be redirected in about 5 secs. If not, click
here.';
} else {
echo "You do not make any booking";
header("refresh:5;url=booking2.php");
echo "<img src='loading16.gif' style='margin-top:8px; float:left'/>";
echo 'You\'ll be redirected in about 5 secs. If not, click
here.';
}
Related
I'm working on a program to reserve seats for a show. I have a multidimensional array that is created using $row and $column variables. After making a few initial reservations, I need to pass integers into a function/some code to make further reservations.
I've tried looping through the array to find consecutive available seats (value "avail") but it ignores reserved seats or skips over them. I'll need to later use manhattan distance to reserve the best seats (from row 1, seat 6) first.
function to create the array:
//function to create seating chart data structure
function createChart($row, $column){
//create array for row values
$row_chart = array();
for($r=0; $r < $row; $r++){
$row_number = $r + 1;
$row_chart[$row_number] = array(); // array of cells for row $r
}
//create array for column values
$column_chart = array();
for($c=0; $c < $column; $c++){
$column_number = $c + 1;
//$location = $c_num;
$status = "avail";
foreach($row_chart as $key => $value){
$column_chart[$column_number] = $status; //add arrays of "seats" for each row
}
}
//nest the column array into the row array
foreach($row_chart as $key => $value){
foreach($column_chart as $k => $v){
$seating_chart[$key][$k] = $status;
}
}
//$seating_chart = array_combine($row_chart, $column_chart);
return $seating_chart;
}
function to make initial reservations:
$initial_reservation = "R1C4 R1C6 R2C3 R2C7 R3C9 R3C10";
$initial_reservation = explode(" ", $initial_reservation);
echo "<br> <br>";
print_r($initial_reservation);
$initial_res_length = count($initial_reservation);
echo "<br> <br>";
//echo $initial_res_length;
//split each seat up into integers to mark it reserved in the array
//issue for flexibility: find way to break up string by letters and numbers for larger charts
for($a = 0; $a < $initial_res_length; $a++){
$reso_row = substr($initial_reservation[$a], 1, 1);
//echo $reso_row . "<br>";
$reso_column = substr($initial_reservation[$a], 3, 2);
//echo $reso_column . "<br>";
$working_chart[$reso_row][$reso_column] = "reserved";
}
//echo "<br> <br>";
//echo "<pre>" . print_r($working_chart, 1) . "</pre>";
what I have so far in attempt to make further reservations:
//write some code to find consecutive seats
$seats_needed = 4;
$outer_array_length = count($working_chart);
//echo $outer_array_length;
for($d = 1; $d < $outer_array_length + 1; $d++){
for($e = 1; $e < $seats_needed + 1; $e++){
//issue: run through $seats_needed amount of times and executes the code block
//needed: check if $seats_needed amount of seats in available first then run reservation code
if($working_chart[$d][$e] === "avail"){
$working_chart[$d][$e] = "new reservation";
}
else{
echo "Sorry, not possible.";
}
}
break;
}
echo "<br> <br>";
echo "<pre>" . print_r($working_chart, 1) . "</pre>";
I'd like to be able to find a number of available seats ($seats_needed) first, and then loop through to reserve them.
I have initialized the $working_chart with :
$working_chart = createChart(10, 11);
I have written the attempt to make further reservations :
foreach(array_keys($working_chart) as $d ){
$maxColumn = count($working_chart[$d]) - $seats_needed + 1;
for($e = 1; $e <= $maxColumn ; $e++){
if(["avail"] === array_unique(array_slice($working_chart[$d], $e - 1 , $seats_needed))){
$working_chart[$d] = array_replace($working_chart[$d], array_fill($e, $seats_needed, "new reservation"));
break 2;
}
else{
echo "Sorry, not possible.";
}
}
}
I hope it can help you...
I created a script to monitor several sensor value's, wich reads them out of a MySQL database , does some calculations om them and then displays the data/plots a graph. The script works as designed however the execution is very slow (avg 60+ seconds).
The Database table consist out of about 500K records, with 20 entry's added every 5 minutes. So either my code is very inefficient or the large table is the cause. I however cannot see how i can improve the code allot, so any help on that is welcome. I did not include the graph class code because removing the graphs does not have any effect on script execution time.
Below i pasted the code for review. Thanks in advance for any tips!
Index.php
<html>
</head>
<style>
form
{
float:left;
}
p {
font-family: Verdana;
font-size: 12;
border: 0;
}
<?php
require_once('template.css');
?>
</style>
</head>
<body>
<?php
//Connect to MySQL DB
require_once('config.inc.php');
require_once('functions.inc.php');
$mysqli = new MySQLi("$dbhost", "$dbuser", "$dbpass", "$db");
require_once ('F:\wamp\www\winlog\phpgraphlib\phpgraphlib.php');
//interval selection forms
echo "<table><tr><td><p><b>Energieverbruik Volta in KW.</b><br>Kies Interval: </p>";
echo "<form name=\"interval\" action=\"\" method=\"post\"><input type=\"hidden\" name=\"interval\" value=\"300\"><input type=\"submit\" value=\"5 Min\"></form>";
echo "<form name=\"interval\" action=\"\" method=\"post\"><input type=\"hidden\" name=\"interval\" value=\"3600\"><input type=\"submit\" value=\"1 Uur\"></form>";
echo "<form name=\"interval\" action=\"\" method=\"post\"><input type=\"hidden\" name=\"interval\" value=\"86400\"><input type=\"submit\" value=\"24 Uur\"></form>";
echo "<form name=\"interval\" action=\"\" method=\"post\"><input type=\"hidden\" name=\"interval\" value=\"604800\"><input type=\"submit\" value=\"1 Week\"></form>";
echo "<form name=\"interval\" action=\"\" method=\"post\"><input type=\"hidden\" name=\"interval\" value=\"2419200\"><input type=\"submit\" value=\"1 Maand\"></form>";
echo "</td></tr></table>";
// $needles[] = "9679"; //Meeting Totaal
// $needles[] = "9680"; //Voeding A-FEED
// $needles[] = "9839"; //Voeding B-FEED
// $needles[] = "9840"; //Koeling
// $needles[] = "9841"; //INPUT UPS1
// $needles[] = "9843"; //VOEDING SDB ALG
// $needles[] = "9844"; //VERDEELKAST V01.UDB
$sensors = GetSensorIDs("1");
//Set interval from form of standard if not set
if(!isset($_POST['interval'])){
$interval = 86400;
$max = 1200;
}
else{
$interval = $_POST['interval'];
}
if($interval == 3600){
$max = 50;
}
if($interval == 86400){
$max = 1200;
}
if($interval == 604800){
$max = 7500;
}
if($interval == 300){
$max = 5;
}
//get timestamps for selected interval
$timestamps = GetTimestamps($interval);
echo "<table class=CSSTableGenerator>";
echo "<tr>";
echo "<td>Datum:</td>";
foreach($timestamps as $timestamp){
echo "<td><center>" . date("d/m/Y", $timestamp) . "<br>" . date("H:i", $timestamp) . "</center></td>";
}
echo "</tr>";
foreach($sensors as $sensor){
echo "<tr>";
$data = GetDataForSensor($sensor, $timestamps, "1");
$i = 0;
$old = 0;
foreach($data as $datapoint){
echo "<td align=\"right\">";
if($interval >= 86400){
$graph_timestamp = date("d/m",$datapoint['timestamp']);
}
else{
$graph_timestamp = date("d/m h:i",$datapoint['timestamp']);
}
if(!isset($old)){
$old = 0;
}
$new = $datapoint['value'];
$usage = $old - $new;
if($i != 0){
if($interval == 604800){
echo "<font color=\"gray\">" . round($old, 2) . "</font><br>";
}
echo round($usage, 2);
${"graphline".$sensor}[$graph_timestamp] = intval(round($usage, 2));
}
else{
echo GetSensorName($sensor);
}
$old = $new;
echo "</td>";
++$i;
}
echo "</tr>";
}
//PUE
echo "<tr>";
$i = 0;
foreach($timestamps as $timestamp){
if(!isset($total_old)){
$total_old = 0;
}
if(!isset($a_old)){
$a_old = 0;
}
if(!isset($b_old)){
$b_old = 0;
}
$PUEvars = GetDataForTimeStamp($timestamp, "1");
$PUE = ($PUEvars['9679'] - $total_old) / (($PUEvars['9680'] - $a_old) + ($PUEvars['9839'] - $b_old));
echo "<td><br><br>";
if($i != 0){
echo "<b>" . round($PUE, 3) . "</b>";
//pass data to array for graph
if($interval >= 86400){
$date = date("d/m",$timestamp);
}
else{
$date = date("d/m H:i",$timestamp);
}
$graph2_data[$date] = round($PUE, 2);
}
else{
echo "<b>PUE</b>";
}
echo "</td>";
$total_old = $PUEvars['9679'];
$a_old = $PUEvars['9680'];
$b_old = $PUEvars['9839'];
++$i;
}
echo "</tr>";
echo "</table>";
echo "Legende:<br>Meting Totaal: <font color=\"red\">ROOD</font><br>INPUT UPS1: <font color=\"green\">GROEN</font><br>A-FEED: <font color=\"blue\">BLAUW</font><br>B-FEED: <font color=\"purple\">PAARS</font><br>KOELING: <font color=\"aqua\">AQUA</font><br>";
//graphcolors black, silver, gray, white, maroon, red, purple, fuscia, green, lime, olive, navy, blue, aqua, teal
$graph = new PHPGraphLib(900,300,"img.png");
$graph->addData($graphline9679, $graphline9680, $graphline9839, $graphline9840, $graphline9841);
$graph->setTitle('Power in KWh');
$graph->setBars(false);
$graph->setLine(true);
$graph->setLineColor('red', 'blue', 'purple', 'aqua', 'teal');
$graph->setDataPoints(false);
$graph->setDataPointColor('maroon');
// $graph->setDataValues(true);
// $graph->setDataValueColor('maroon');
// $graph->setGoalLine(1.3);
$graph->setRange($max,0);
$graph->setGoalLineColor('red');
$graph->createGraph();
$unimg = time();
echo "<img src=\"img.png?$unimg\">";
$graph2 = new PHPGraphLib(900,300,"img2.png");
$graph2->addData($graph2_data);
$graph2->setTitle('PUE');
$graph2->setBars(false);
$graph2->setLine(true);
$graph2->setDataPoints(true);
$graph2->setDataPointColor('maroon');
$graph2->setDataValues(true);
$graph2->setDataValueColor('maroon');
$graph2->setGoalLine(1.3);
$graph2->setRange(2,1);
$graph2->setGoalLineColor('red');
$graph2->createGraph();
$unimg = time();
echo "<img src=\"img2.png?$unimg\">";
?>
</body>
</html>
functions.inc.php
<?php
function GetSensorName($sensor_id){
global $mysqli;
if($stmt1 = $mysqli->prepare("SELECT sensor_name FROM winlog_sensors WHERE sensor_id = ? ")){
$stmt1->bind_param("i", $sensor_id);
mysqli_stmt_execute($stmt1);
mysqli_stmt_store_result($stmt1);
mysqli_stmt_bind_result($stmt1, $sensor_name);
while (mysqli_stmt_fetch($stmt1)) {
$sensor_name = $sensor_name;
}
}
return $sensor_name;
}
function GetSensorIDs($category){
global $mysqli;
$sensors = array();
if($stmt1 = $mysqli->prepare("SELECT sensor_id FROM winlog_sensors WHERE category_id = ? ")){
$stmt1->bind_param("i", $category);
mysqli_stmt_execute($stmt1);
mysqli_stmt_store_result($stmt1);
mysqli_stmt_bind_result($stmt1, $sensor_id);
while (mysqli_stmt_fetch($stmt1)) {
$sensors[] = $sensor_id;
}
}
return $sensors;
}
function GetTimestamps($interval){
global $mysqli;
$timestamps = array();
if($interval == 604800){
if(date("w") == 5 AND date("H") >= 12){
$latest = intval(strtotime("today 12:00"));
}
else{
$latest = intval(strtotime("last friday 12:00"));
}
}
else{
$latest = intval(GetLatestTimestamp());
}
$timestamps[] = $latest;
$i = 0;
$n = 1;
while($i < 24 AND $n < 50){
$deduct = intval($interval) * $n;
$q_timestamp = $latest - $deduct;
//Get calculated timestamp from DC
if($stmt1 = $mysqli->prepare("SELECT DISTINCT timestamp FROM winlog_data WHERE timestamp = ? LIMIT 1")){
$stmt1->bind_param("i", $q_timestamp);
mysqli_stmt_execute($stmt1);
mysqli_stmt_store_result($stmt1);
mysqli_stmt_bind_result($stmt1, $db_timestamp);
$exists = 0;
while (mysqli_stmt_fetch($stmt1)) {
$timestamps[] = intval($db_timestamp);
$exists = 1;
++$i;
}
//if it does not exist, take the previous one
if($exists == 0){
if($stmt1 = $mysqli->prepare("SELECT DISTINCT timestamp FROM winlog_data WHERE timestamp < ? ORDER BY timestamp DESC LIMIT 1")){
$stmt1->bind_param("i", $q_timestamp);
mysqli_stmt_execute($stmt1);
mysqli_stmt_store_result($stmt1);
mysqli_stmt_bind_result($stmt1, $db_timestamp);
$exists = 0;
while (mysqli_stmt_fetch($stmt1)) {
$timestamps[] = intval($db_timestamp);
++$i;
}
}
}
}
++$n;
}
return $timestamps;
}
function GetLatestTimestamp(){
global $mysqli;
$timestamps = array();
if($stmt1 = $mysqli->prepare("SELECT DISTINCT timestamp FROM winlog_data ORDER BY timestamp DESC LIMIT 1")){
mysqli_stmt_execute($stmt1);
mysqli_stmt_store_result($stmt1);
mysqli_stmt_bind_result($stmt1, $timestamp);
while (mysqli_stmt_fetch($stmt1)) {
$timestamp = $timestamp;
}
}
return $timestamp;
}
function GetPreviousTimestamp($timestamp){
global $mysqli;
$timestamps = array();
if($stmt1 = $mysqli->prepare("SELECT DISTINCT timestamp FROM winlog_data WHERE timestamp < ? ORDER BY timestamp DESC LIMIT 1")){
$stmt1->bind_param("i", $timestamp);
mysqli_stmt_execute($stmt1);
mysqli_stmt_store_result($stmt1);
mysqli_stmt_bind_result($stmt1, $prev_timestamp);
while (mysqli_stmt_fetch($stmt1)) {
$prev_timestamp = $prev_timestamp;
}
}
return $prev_timestamp;
}
function GetDataForTimeStamp($timestamp, $category){
global $mysqli;
$data = array();
$exists = 0;
$start_ts = $timestamp;
$stop_ts = $timestamp +1;
if($stmt2 = $mysqli->prepare("SELECT wd.value, wd.sensor_id FROM winlog_data wd, winlog_sensors ws WHERE ws.sensor_id = wd.sensor_id AND wd.timestamp >= ? AND wd.timestamp <= ? AND ws.category_id = ? ")){
$stmt2->bind_param("iii", $start_ts, $stop_ts, $category);
mysqli_stmt_execute($stmt2);
mysqli_stmt_store_result($stmt2);
mysqli_stmt_bind_result($stmt2, $value, $sensor_id);
while (mysqli_stmt_fetch($stmt2)) {
$data[$sensor_id] = $value;
$exists = 1;
$data['timestamp'] = $timestamp;
}
}
return $data;
}
function GetDataForSensor($sensor_id, $timestamps, $category){
global $mysqli;
$data = array();
$i = 0;
$highest = 0;
foreach($timestamps as $q_timestamp){
if(!isset($lowest)){
$lowest = $q_timestamp;
}
if($q_timestamp > $highest){
$highest = $q_timestamp;
}
if($q_timestamp < $lowest){
$lowest = $q_timestamp;
}
}
if($stmt2 = $mysqli->prepare("SELECT DISTINCT wd.value, wd.timestamp FROM winlog_data wd, winlog_sensors ws WHERE wd.sensor_id = ? AND wd.timestamp >= ? AND wd.timestamp <= ? AND ws.category_id = ? ORDER BY wd.timestamp DESC")){
$stmt2->bind_param("iiii", $sensor_id, $lowest, $highest, $category);
mysqli_stmt_execute($stmt2);
mysqli_stmt_store_result($stmt2);
mysqli_stmt_bind_result($stmt2, $value, $timestamp);
while (mysqli_stmt_fetch($stmt2)) {
foreach($timestamps as $q_timestamp){
if($q_timestamp == $timestamp){
$data[$i]['value'] = $value;
$data[$i]['timestamp'] = $q_timestamp;
}
}
++$i;
}
}
return $data;
}
?>
Use Indexes
Indexes are used to find rows with specific column values quickly. Without an index, MySQL must begin with the first row and then read through the entire table to find the relevant rows. The larger the table, the more this costs. If the table has an index for the columns in question, MySQL can quickly determine the position to seek to in the middle of the data file without having to look at all the data. This is much faster than reading every row sequentially.
How to create an index in SQL:
Here’s what the actual SQL would look like to create an index on the Employee_Name column from our example earlier:
CREATE INDEX name_index
ON Employee (Employee_Name)
How to create a multi-column index in SQL:
We could also create an index on two of the columns in the Employee table , as shown in this SQL:
CREATE INDEX name_index
ON Employee (Employee_Name, Employee_Age)
first make sure your DB table is indexed correctly: your timestamp table should have an index on 'timestamp' field. Your winlog_sensors table should have indexes for sensor_id and category_id.
if indexing does not help try profiling the script and see what exactly takes up your time. You could do that with Xdebug but that takse some practice. My favorite tool is NewRelic, has its downsides but gives a nice script execution breakdown so you can see if it's your queries or your code that's to blame.
Background
I have a script which is used to rotate employees to share an allotment of car parks. Everything works fine i.e. i am able to retrieve a list of employees from a mysql db into an array, sort alphabetically and fill a table in a rotating fasion. All good.
What I am trying to achieve
What I would like to able to do is if I change the month i.e. from August to September the rotation from the current month will continue from where it left over in the previous month. Right now with the current script it will rotate perfectly within the given month but if i enter a new month the rotation is reset.
I have been thinking long and hard as to how i can carry over the rotation but struggling to figure this out.
Personal thoughts..
One thought maybe is should I flag in the mysqldb the last person in the rotation then in the next month continue the rotation beginning from the person who was flagged?
Here is the current working script
<?php
$weeks = array();
$month = 'Aug';
$year = '2015';
$date = new DateTime("first Monday of $month $year");
$thisMonth = $date->format('m');
while ($date->format('m') === $thisMonth) {
array_push($weeks, $date->format('d-m-Y'));
$date->modify('next Monday');
}
//print_r($weeks);
$weeks_count = count($weeks);
//echo $weeks_count;
//=========================================
include_once 'connect.php';
dbconnect("roster");
$NoOfRows = 8;
$NoOfWeeks = $weeks_count;
$totalLots = $NoOfRows * $NoOfWeeks;
$dataArr = array();
//fetch all persons
$query = "SELECT * FROM carpark ORDER BY First_Name";
$result = mysqli_query($conn, $query) or die("error getting data");
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
array_push($dataArr, $row['First_Name']);
}
$noOfPersons = count($dataArr);
//Create a new array with filling all lots
while ($noOfPersons < $totalLots) {
$dataArr = array_merge($dataArr, $dataArr);
$noOfPersons = count($dataArr);
}
$weekArr = array_chunk($dataArr , $NoOfRows);
//print the table
echo "<table border=1>";
for ($row = 0; $row < $NoOfRows; $row++) {
if ($row == 0) {
echo "<tr><th></th>";
for ($col = 1; $col <= $NoOfWeeks; $col++) {
$weeks_loop = $col-1;
echo "<th>Week $col<br>$weeks[$weeks_loop]</th>";
}
echo "</tr>";
}
for ($col = 0; $col < $NoOfWeeks; $col++) {
if ($col == 0) {
echo "<tr><td><strong>Bay $row</strong></td>";
}
echo "<td>";
echo $weekArr[$col][$row];
echo "</td>";
}
echo "</tr>";
}
echo "</table>";
?>
Screenshot of output
What should happen is if i change the next month, the rotation should start with Claire, Duncan, Gabriel and so on..
Ok, i have my php code wrote out for the schedule to book time slots. The sql is pulling the user name (text) and displaying it, BUT I AM NOW TRYING TO DISPLAY THE USERS PIC IMAGE INSTEAD OF JUST NAME(text). I cant for the life of me find anything that is clearly telling me how to display an image on click instead of the text from sql. PLEASE HELP, THANKS :)
ENTIRE CODE:
<?php require('head.php');?>
<?php
// Basic info
$slotb = $_GET['slot'];
$day = $_GET['day'];
// User info
$username = $_SESSION['rp_username'];
$avatar = $_SESSION['rp_avatar'];
$rank = $_SESSION['rp_rank'];
// Get user's ID
$sql = mysql_query("SELECT id, username FROM rp_users WHERE username = '$username'");
while($row = mysql_fetch_array($sql))
{
$userid = $row['id'];
}
// Determine day of week
if($_GET['week'] == "")
{
$_GET['week'] = date("l");
}
// Determine day of week
if($_GET['day'] == ""){
$day = $_GET['week'];
$_GET['week'] = date("l");
}
// Get slot info
$slot = mysql_fetch_array(mysql_query("SELECT * FROM rp_timetable WHERE day = '$day'"));
// Timetable heading
echo "<div id='timetable'><center><b><u>Timetable</u></b><p>
<h1>-You are currently viewing $day's timetable-</h1><p>
<a href='?week=Monday'>Monday</a> | <a href='?week=Tuesday'>Tuesday</a> | <a href='? week=Wednesday'>Wednesday</a> | <a href='?week=Thursday'>Thursday</a> | <a href='? week=Friday'>Friday</a> | <a href='?week=Saturday'>Saturday</a> | <a href='? week=Sunday'>Sunday</a><br><hr><br>";
// Process booking
if($_GET["action"] == "book")
{
if($slot[$slotb] == "")
{
$command = mysql_query("UPDATE rp_timetable SET `$slotb` = '$userid' WHERE day = '$day'") or die(mysql_error());
if($command)
{
echo "<center><h1>Successfully booked slot!</h1></center><br/>";
$slot = mysql_fetch_array(mysql_query("SELECT * FROM rp_timetable WHERE day = '$day'"));
}else{
echo "<center><h1>ERROR - An unknown error occurred, please try again.</h1></center> <br/>";
}
}else{
echo "<center><h1>The selected slot is already booked!</h1></center><br/>";
}
}elseif($_GET["action"] == "unbook")
{
if($slot[$slotb] == $userid || $rank == "Administrator")
{
$command = mysql_query("UPDATE rp_timetable SET `$slotb` = '' WHERE day = '$day'") or die(mysql_error());
if($command)
{
echo "<center><h1>Successfully unbooked slot!</h1></center><br/>";
$slot = mysql_fetch_array(mysql_query("SELECT * FROM rp_timetable WHERE day = '$day'"));
}else{
echo "<center><h1>ERROR - An unknown error occurred, please try again.</h1></center> <br/>";
}
}else{
echo "<center><h1>You cannot unbook this slot!</h1></center><br/>";
}
}
elseif($_GET["action"] == "empty"){
if($rank == "Administrator")
{
$command = mysql_query("UPDATE rp_timetable SET `1`='', `2`='', `3`='', `4`='', `5`='', `6`='', `7`='', `8`='', `9`='', `10`='', `11`='', `12`='', `13`='', `14`='', `15`='', `16`='', `17`='', `18`='', `19`='', `20`='', `21`='', `22`='', `23`='', `24`='' WHERE day='$day'") or die(mysql_error());
if($command)
{
echo "<center><h1>Successfully cleared all slots for day!</h1></center><br/>";
$slot = mysql_fetch_array(mysql_query("SELECT * FROM rp_timetable WHERE day = '$day'"));
}else{
echo "<center><h1>ERROR - An unknown error occurred, please try again.</h1></center><br/>";
}
}
else{
echo "<center><h1>Only administrators may unbook all slots for the day!</h1></center> <br/>";
}
}
// Start of timetable
echo "<table border='0' valign='middle' align='center'><tr>
<td width='150px' align='center'><b><u>Time</u></b></td>
<td width='150px' align='center'><b><u>DJ Booked</u></b><td></tr>
<tr><td></td><td></td></tr>";
// Display each timeslot/table
function outit($time, $num)
{
global $day, $slot, $userid, $rank;
$info = mysql_fetch_array(mysql_query("SELECT * FROM rp_users WHERE id = '".$slot[$num]."'"));
if($slot[$num] == "")
{
$book[$num] = "<a href='?action=book&day=$day&slot=$num'>BOOK SLOT</a>";
}
elseif($userid == $slot[$num] || $rank == "Administrator")
{
$book[$num] = "<a href='?action=unbook&day=$day&slot=$num'><b>DJ ".$info['avatar']." (Unbook)</a></b>";
}else{
$book[$num] = "<b><font color='black'>DJ ".$info['avatar']."</font></b>";
}
if($num%2)
{
echo "<tr class='colour'><td width='150px' align='center'>$time</td><td width='150px' align='center'>".$book[$num]."<td></tr>";
}else{
echo "<tr><td width='150px' align='center'>$time</td><td width='150px' align='center'>".$book[$num]."<td></tr>";
}
}
// Print it out
outit('12:00 - 01:00 AM', 1);
$i = 2;
while($i <= 12)
{
$start_time = $i - 1;
$end_time = $i;
if(strlen($start_time) == 1){$start_time = "0".$start_time;}
if(strlen($end_time) == 1){$end_time = "0".$end_time;}
$full_time = "$start_time:00 - $end_time:00 AM";
outit($full_time, $i);
$i++;
}
outit('12:00 - 01:00 PM', 13);
$i = 14;
while($i <= 24)
{
$start_time = $i - 13;
$end_time = $i - 12;
if(strlen($start_time) == 1){$start_time = "0".$start_time;}
if(strlen($end_time) == 1){$end_time = "0".$end_time;}
$full_time = "$start_time:00 - $end_time:00 PM";
outit($full_time, $i);
$i++;
}
// Bottom of timetable
echo "<tr><td align='center'>---------------</td><td align='center'>--------------- </td></tr>";
echo "<tr><td width='150px' align='center'><b>$day</b></td>
<td width='150px' align='center'>";
if ($_SESSION["rp_rank"] == "Administrator")
{
echo("<a href='?action=empty&day=$day'>CLEAR DAY</a>");
}
echo "</td></tr></table>
</center><p></div>";
?>
<?php require('bottom.php');?>
To use the $avatar variable that seems to be stored in your session:
echo '<img src="'.$avatar.'"></img';
You also seem to be selecting that field in the query $info, meaning you should be able to use the following as well:
echo '<img src="'.$info['avatar'].'"></img';
To isolate the problem, please let me know what output you get for just the following:
<?php require('head.php');?>
<?php
// Basic info
$slotb = $_GET['slot'];
$day = $_GET['day'];
// User info
$username = $_SESSION['rp_username'];
$avatar = $_SESSION['rp_avatar'];
$rank = $_SESSION['rp_rank'];
echo $avatar;
<?php require('bottom.php');?>
My guess is that $avatar holds apostrophes or other characters that need to be escaped.
Also could you provide a couple examples of the field values for the avatar column on the rp_users table? If they contain apostrophes, then that is your answer.
I'm wanting to have a list of states and the cities under it. I want 5 states per row with the cities that have records under it, then I want it to start a new row. I started trying to figure it out and I've been going for hours and my brain hurts. Can anyone help?
Here's what I have right now:
$lookup = "SELECT state, city, count(city) as num FROM needs WHERE country IS NULL AND
status='posted' GROUP BY state, city ORDER BY state, city";
if ($result = mysql_query($lookup)) {
$num_rows = mysql_num_rows($result);
echo "<table>";
$i = 1;
$cols = 3;
$prev = '';
while ($frows = mysql_fetch_array($result)) {
$fcity = $frows['city'];
$fstate = $frows['state'];
$fcitycount = $frows['num']; // num is holding your count by city
if ($fstate != $prev) {
echo "<tr><td><h2>$fstate</h2></td>";
$prev = $fstate;
}
echo "<tr><td><a href='browseresults.php?city=$fcity&state=$fstate'>$fcity, $fstate ($fcitycount)</a></td></tr>";
}
echo "</table>";
}
EDIT:
It should look like this:
Arkansas Tennessee Missouri
Searcy, AR (1) Bartlett, TN (1) St. Louis, MO (4)
Little Rock, AR (4) Memphis, TN (3) Perry, MO (3)
Benton, AR (2) Branson, MO (1)
Shell, MO (2)
Except it will be done 5 times instead of 3
EDIT 2:
Here's the code I tried but it's still not working :-/
$lookup = "SELECT state, city, count(city) as num FROM needs WHERE country IS NULL AND status='posted' GROUP BY state, city ORDER BY state, city";
if ($result = mysql_query($lookup)) {
$num_rows = mysql_num_rows($result);
echo "<table><td>";
$i = 1;
$j = 1;
$cols = 5;
$prev = '';
while ($frows = mysql_fetch_array($result)) {
$fcity = $frows['city'];
$fstate = $frows['state'];
$fcitycount = $frows['num']; // num is holding your count by city
if ($fstate != $prev) {
echo "<tr><h2>$fstate</h2></tr>";
$prev = $fstate;
}
echo "<tr><a href='browseresults.php?city=$fcity&state=$fstate'>$fcity, $fstate ($fcitycount)</a><br></tr>";
if ($fstate != $prev) {
echo "</td><td>";
}
}
echo "</td></table>";
}
Here is one way to do it, based off your current code attempt. The state and all of its cities are within the same cell.
echo "<table>";
$i = 1;
$cols = 3; // of cells per row
$prev = '';
echo "<tr>"; // start the first row
while ($frows = mysql_fetch_array($result)) {
$fcity = $frows['city'];
$fstate = $frows['state'];
$fcitycount = $frows['num']; // num is holding your count by city
if ($fstate != $prev) {
if($i>$cols){ // check if we have reached our # of $cols
echo "</td></tr><tr>"; // end cell/row and start new row
$i=1; //reset counter
}
elseif ($prev != '') { // if not the first cell/state
echo "</td>"; // end cell before starting new cell/state
}
echo "<td><h2>$fstate</h2>";
$prev = $fstate;
$i++;
}
echo "<a href='browseresults.php?city=$fcity&state=$fstate'>$fcity, $fstate ($fcitycount)</a><br />";
}
echo "</td></tr>"; //end the last cell/row
echo "</table>";
By changing $cols value (ie $cols=5, you can change the number of cells per row.
See an example of this in a phpfiddle - http://phpfiddle.org/main/code/pkg-90i
this creates a table like this-