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>";
Related
We are trying to make life easier on one of our website coded platforms.
There are 8 rows in the database, each with 1-4 at the end of them.
ie. childrensrange1, childrensrange2 and so on.
Then childrennumber1, childrennumber2...
But I don't want to be creating a ton of code, so I have started writing this. But I cannot work out how to assign the number to the end of the $row->variable.
Look at the row starting with: $childrenamountrow
I need it to query the database for $row->childrenamount1, then $row->childrenamount2 and so on.
I'm sure I have done this before, but I cannot remember how to do it.
This block should cover all 4 blocks of age ranges rather than reams of code for each set.
$countchild = 1;
while ($countchild <=4) {
echo "<tr><td><select name='childrensrange$countchild'>";
$querychildren = ("SELECT * FROM `childrensagerange` ORDER BY id");
$resultchildren = $pdo->query($querychildren);
while ($rowchildren = $resultchildren->fetch(PDO::FETCH_OBJ)) {
$childrenrangerow = "$rowchildren->agerange"."$countchild";
echo "<option value='$rowchildren->agerange'";
if ($rowchildren->agerange == $childrenrangerow) { echo " selected='selected'";}
echo ">$rowchildren->agerange</option>";
}
echo "</td><td>";
$childrenamountrow = "$row->childrenamount$countchild";
echo "<input type='text' name='childrenamount$countchild' value='$childrenamountrow'></td></tr>";
$countchild ++;
}
echo "</table>```
why not something like this ?
for (var i=1;i<=4;i++) {
$querychildren = ("SELECT childrensrange"+i+" FROM `childrensagerange` ORDER BY id");
$resultchildren = $pdo->query($querychildren);
(...)
}
I've trying to create an array that consists of the values of inputs in loops. I am very new to PHP and looked up several other questions but to no avail. I am taking a random number "$QuestionNoSelect" and selecting a text and info from a MySQL server about the question.
//For loop for displaying and naming
for($i = 0; $i < 11; $i++)
{
$QuestionNoSelect = rand(1,16);
array_push($IDListing, $QuestionNoSelect);
$sql = "SELECT QuestionText FROM johnconn_sstest.tbRandomArray WHERE QuestionNo = $QuestionNoSelect";
$QuestionText = $conn->query($sql);
if ($QuestionText->num_rows > 0)
{
// output data of each row
while($row = $QuestionText->fetch_assoc())
{
//Number Question, Increment, Question then input box
echo "<br><br>".$QuestionNumberer. ". ". "<br>";
echo "Question number ID= ".$QuestionNoSelect, "<br>";
$QuestionNumberer++;
echo $row["QuestionText"];
echo '<br>'.'Answer';
echo "<input type='text' name='answerbox[]' id='answerbox[]' class='userInfo' value='".$i."'/>";
echo '<br>'.'comment(if Applicable)';
echo "<input type='text' name='commentbox[]' id='commentbox'[]' class='userInfo' value='".$i."'/>";
}
}
else
{
echo "0 results";
}
}
I am trying to get these values from the array of names or IDs I've created but cannot figure out why I can't get it to work. I cannot even get the array of values to print
//PRINT ANSWER
echo '<br>Answer List <br>';
for($i = 0; $i < 11; $i++)
{
$_POST("answerbox[$i]");
}
Any help would be greatly appreciated. Thank you.
The short answer is that you are treating $_POST like it is a function ($_POST()) instead of an array ($_POST[]). Because your form fields are 1-dimensional arrays, your $_POST data is a 2-dimensional array. Access the submitted array elements using this syntax:
$_POST[formfieldname][numerickey]
I have rewritten a portion of your code and added some refinements which should improve efficiency and show some good practices.
$conn=new mysqli($host, $user, $pass, $dbname);
$conn->select_db('johnconn_sstest'); // designate a default database
$sql="SELECT QuestionNo,QuestionText FROM tbRandomArray ORDER BY RAND() LIMIT 10;"; // until your table gets very, very large RAND() will serve you well
if($result=$conn->query($sql)){ // declare $result and check if true/success or false/syntax failed
$i=0;
echo "<form action=\"receiving_page.php\" method=\"post\">"; // assign receiving page and data delivery method
while($row=$result->fetch_assoc()){ // loop through your db table rows
++$i;
echo "Q$i ID:{$row['QuestionNo']}<br>"; // show counter and question's row id
echo "<input type=\"hidden\" name=\"QNo[$i]\" value=\"{$row['QuestionNo']}\">"; // invisibly pass question id to receiving page
echo "{$row['QuestionText']}<br>";
echo "Answer <input type=\"text\" name=\"answerbox[$i]\" id=\"answerbox$i\" class=\"userInfo\" value=\"\"><br>"; // assign numeric key to each answer input name beginning with 1
echo "Comment(if Applicable) <input type=\"text\" name=\"commentbox[$i]\" id=\"commentbox$i\" class=\"userInfo\" value=\"\"><br><br>"; // assign numeric key to each answer input name beginning with 1
}
echo "<input type=\"submit\" value=\"Submit\">"; // submit button with no name attribute so the value is not passed to the receiving page
echo "</form>";
}else{
echo $conn->error;
}
# receiving_page.php:
if(isset($_POST["QNo"]) && sizeof($_POST["QNo"])==10 &&
isset($_POST["answerbox"]) && sizeof($_POST["answerbox"])==10 &&
isset($_POST["commentbox"]) && sizeof($_POST["commentbox"])==10){
foreach($_POST["QNo"] as $index=>$value){
// do whatever you like with the values, use $index access other arrays' elements
// $value is each QNo in sequence.
// $_POST["answerbox"][$i] is answerbox value in the same QNo row
// $_POST["commentbox"][$i] is commentbox value in the same QNo row
}
}else{
echo "Did not receive the full batch of expected values";
}
Of course, on your form, the fields' keys ($i in fieldname[$i]) can be omitted like this: fieldname[] -- this may be preferable but just be aware that then the numerickeys will start at 0 instead of 1 and will automatically increment.
print_r is your friend. You can print_r($_POST) which will let you see if you have what you think you have. Once you see that it should be clear why you aren't seeing what you want.
If this code is intended to be printing the answers, it needs to be something like
echo $_POST["answerbox[{$i}]"];
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.
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.
I've been searching for a week now on how to accomplish this but none of the tutorials have worked - I typically get a message "resource id 18."
I'm creating a bank simulation game.
End goal: I want a variable "$player_balance" to be the sum of all account balances owned by that player so that it can be displayed at the bottom of the table under account balances.
Here is my code, thanks for any help or direction that you can provide.
function displayMyAccounts(){
global $database, $session;
$q = "SELECT game_account_number,game_account_owner,game_account_name,game_account_balance FROM ".TBL_ACCOUNTS." WHERE game_account_owner='".$session->username."'";
$result = $database->query($q);
/* Error occurred, return given name by default */
$num_rows = mysql_numrows($result);
if(!$result || ($num_rows < 0)){
echo "Error displaying info";
return;
}
if($num_rows == 0){
echo "Database table empty";
return;
}
/* Display table contents */
echo "<table align=\"left\" border=\"1\" cellspacing=\"0\" cellpadding=\"3\" width=\"100%\">\n";
echo "<tr><td><b>Account Number</b></td><td><b>Account Name</b></td><td><b>Balance</b></td></tr>\n";
for($i=0; $i<$num_rows; $i++){
$anumber = mysql_result($result,$i,"game_account_number");
$aowner = mysql_result($result,$i,"game_account_owner");
$aname = mysql_result($result,$i,"game_account_name");
$abalance = mysql_result($result,$i,"game_account_balance");
setlocale(LC_MONETARY, 'en_US');
$abalance2 = money_format('%(#10n', $abalance);
echo "<tr><td>$anumber</td><td>$aname</td><td>$abalance2</td></tr>\n";
}
echo "<tr><td></td><td></td><td>$player_balance</td></tr>\n";
echo "</table><br>\n";
}
displayMyAccounts();
The above code is what appears on each player's "account page." I want the sum of their accounts to appear on the last row. Thanks for any help, I'll continue searching and trying in the meantime.
Here is the output based on the above:
Account Number Account Name Balance
1000083690 Maverick $ 50,000.00
1000083696 WellsFargo $ 50,000.00
1000083697 Wachovia $ 50,000.00
Don't use mysql_result(). It's slow and inefficient, and what you're doing is better done with mysql_fetch_assoc():
$player_balance = 0;
// Also, ditch the for loop. This is the typical convention for retrieving results.
while ($row = mysql_fetch_assoc($result)) {
$abalance1 = money_format('%(#10n', $row['game_account_balance']);
echo "<tr><td>{$row['game_account_number']}</td><td>{$row['game_account_name']}</td><td>$abalance1</td></tr>\n";
// Now add to the balance
$player_balance = $player_balance + $row['game_account_balance'];
}
// And output your balance
$abalance_sum = money_format('%(#10n', $player_balance);
echo "<tr><td></td><td></td><td>$abalance_sum</td></tr>\n";
resource error means
YOU DO NOT HAVE THE TABLE OR THE PERMISSION, OR YOU ARE TRY TO ACCESS A COLUMN WHICH DOES NOT EXIST