how to i calculate the total sum - php

As the title stated;
How do i calculate TOTAL when user checked multiple checkboxs on the selected hotel?
and
How do i make it so that whenever a TOTAL is added and the current TOTAL (which is in mysql) exceed 500k, an alert will pop saying BUDGET EXCEEDED
Thanks you!
CODE:
<?php
require ("config.php");
$link = mysqli_connect($h,$u,$p,$db)
OR die(mysqli_error());
$query = "select BIL, HOTEL, TOTAL, address from HOTELS"
OR DIE(mysqli_error());
$result = mysqli_query($link,$query);
echo "<table border=2>";
echo "<tr><th><b>HOTEL</th><th><b>TOTAL(RM)</th><th>ADDRESS</th></tr>";
while ($row = mysqli_fetch_array($result)) {
echo "<tr><td>$row[HOTEL]</td>";
echo "<td>RM $row[TOTAL]</td>";
echo "<td>$row[address]</td>";
echo "<td><a href='delete.php?del=$row[BIL] '>Delete</a></td>";
echo "<td><input name='checkbox[]' type='checkbox' value='{$row['HOTEL']}'></td></tr>" ;
}
?>

Use JavaScript or JQuery (JS library).
Whenever a checkbox selected/deselected, retrieve the value from corresponding 'total' cell
$selected_val = $(this).parent.(".total").text //sample in jquery,
and remove the 'RM' word. then +/- the value in total.

Related

Updating data in MySQL database based on checked dynamic checkboxes in the table

I'm sorry about my question, but I'm starting with PHP and I want to ask you for a help with my problem.
In my web application I work with a table, which has a dynamic count of rows based on the number of rows in a source table in MySQL database. In the application should be a checkbox in each row of the table. After clicking on the submitt button there should be update of records in the source table and it should be update just of these records where the checkboxes were checked.
The table in the application looks simillar like in the picture.
The primary key in the source table is in the column NUMBER. As a first try I simulated that after clicking on submitt button there will be shown the msgbox with the values from the column NUMBER for the rows, where the checkboxes were checked.
<html>
<head>
<title>APLICATIONa</title>
<script type="text/javascript">
function GetSelected() {
//Reference the Table.
var grid = document.getElementById("Table");
//Reference the CheckBoxes in Table.
var checkBoxes = grid.getElementsByTagName("INPUT");
var message = "\n";
//Loop through the CheckBoxes.
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
message += " " + row.cells[1].innerHTML;
message += "\n";
}
}
//Display selected Row data in Alert Box.
alert(message);
}
</script>
</head>
<body>
<?php
$values = mysql_query("SELECT * FROM table_03_2020");
echo "<br><form action='main.php' method='POST'>";
echo "<input type='submit' name='button' value='Get Selected' class='btn btn-primary' onclick='GetSelected()' />";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
echo "<td><input type='checkbox' name='cbox[]' ></td>";
echo "<td><font color='red'>".$zaznam["number"]."</font></td>";
echo "<td>".$zaznam["name"]."</td>";
echo "</tr>";
endwhile;
echo "</table><br>";
echo "</form>";
?>
</body>
</html>
The msgbox is just an illustration. Instead of msgbox, I need that after clicking on the submit button, there should be an update for these records in the source table, where the checkboxes were selected (so of these records, which are now shown in the msgbox). So I need something like:
"UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
There'll be also a second submit button and after clicking on it, there should be another different update. So after clicking on the second button, I need something like:
"UPDATE table_03_2020 SET column1 = 'ab' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
I'm sorry if my question is not so clear, but I'd really appreciate any help.
Thank you very much.
Add key values with the number to the cbox form variable:
echo "<td><input type='checkbox' name='cbox[" .$zaznam["number"]. "]' ></td>";
Then use the following PHP to get the number list.
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
The addslashes function is for SQL Injection protection.
This will create a list with comma separated numbers.
Than, you can insert it in the the SQL query.
UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('. $checked_list .')
If you assign a value to the checkboxes, like this:
<input type='checkbox' name='cbox[]' value='{$zaznam["number"]}' >
When the form is submitted the cbox variable will contain an array of these numbers, which means that you can process them like this:
<?php
include 'db.php'; #your database connection!!!
$sql='update table_03_2020 set `column1`="XY" where `column2` in ( ? )';
$stmt=$db->prepare( $sql );
$ids=implode(',',$_POST['cbox']);
$stmt->bind_param('s',$ids);
$stmt->execute();
?>
Note that the above has not been tested so there might be errors but I hope it'll give the idea.
Thank you, I tried to improve the part of the code to:
echo "<input type='submit' name='buttonupdate' value='Get Selected' >";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
if ($_POST["buttonupdate"]) {
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
}
echo "<td><input type='checkbox' name='cbox[" .$zaznam["cflot"]. "]' ></td>";
It didn't work, there was no update. Did I edited the code incorrectly?
Actually I forgot to mention the second button, so I edited my first post. Would it be possible to distinguish between the first and the second button? Thank you very much for any help.

Organise seats into tablerows in html output with PHP

I'm putting together something that's mean to allow for a user to book seats for a cinema showing. The row and seat numbers for every showing are stored in the database. I'm currently extracting them in the following method so that users can click on a seat button to select that seat for their booking:
echo "<form>";
echo "<table>";
while($row = mysqli_fetch_assoc($result)){
$rownum = $row['row'];
$seat = $row['seat'];
echo "<tr><td><button type=\"submit\" name=\"seatsel\" value=\"$rownum$seat\">$rownum$seat</button></td></tr>";
}
echo "</table>";
Right now this just outputs html showing all of the buttons as a single row in the table. I'd like the output to show seating across a single table row for every one of the table rows in the cinema screen. I'm not sure how to do this exactly given that each row is of differing lengths. E.g row A has twelve seats while row C has eight.
What would be the best way of accomplishing this?
You could easily update your code so that you will get a new table row every time the mysql row has another value. One thing to note is that you might want to add (depending on whether you're already sorting your results) the following ORDER BY row,seat.
echo "<form>";
echo "<table>";
echo "<tr>";
while($row = mysqli_fetch_assoc($result)){
if (!isset($oldrownumber)) $oldrownumber = $row['row'];
else if ($oldrownumber != $row['row']) {
echo "</tr><tr>";
$oldrownumber = $row['row'];
}
$rownum = $row['row'];
$seat = $row['seat'];
echo "<td><button type=\"submit\" name=\"seatsel\" value=\"$rownum$seat\">$rownum$seat</button></td>";
}
echo "</tr>";
echo "</table>";

Multiple html drop down with values from database using while loop

i already have a while loop that displays select inputs in my form depending on how many passengers the user is booking. Each drop down was supposed to show all data from a column in my database. The problem is that only the first drop down displays the data i fetched which is seats 1 to 30.
Query to get the airline id of the current flight
$result = mysqli_query($conn,"select * from flight_seat_status where flight_number = '$_SESSION[departure]'");
Variables i used to start the counting in the loop
$print = 1; $name = 0;
My while loop with the problem
echo "<h1 class='adminContent_h1'>Please choose a seat</h1>";
while($print <= $_SESSION['passengers']){
echo "<label style = 'width:170px;'>". $_SESSION['firstname'][$name]."'s Seat</label>";
echo "<select class = 'content_dropdown' style = 'width:15%; margin-bottom:20px;' name = 'passengers[]'>";
while($row = mysqli_fetch_assoc($result)){
echo "<option value='".$row['seat_id']."'>".$row['seat_number']."</option>";
}
echo "</select><br>";
$print++;
$name++;
}
it is able to print out a number of drop downs depending on the user but only the first drop down contains the data.
what is wrong with my code? please explain
You have to set the pointer back to 0 for using the result again
// set the pointer back to the beginning
mysqli_data_seek($result, 0);
while($row = mysqli_fetch_assoc($result)){
// do whatever here...
}
Please use below code. All the seats records you have to fetch once outside passenger loop and store in another array and then you have to use seats array inside the passenger loop each time.
echo "<h1 class='adminContent_h1'>Please choose a seat</h1>";
$seats = [];
while($row = mysqli_fetch_assoc($result)){
$seats[] = $row;
}
while($print <= $_SESSION['passengers']){
echo "<label style = 'width:170px;'>". $_SESSION['firstname'][$name]."'s Seat</label>";
echo "<select class = 'content_dropdown' style = 'width:15%; margin-bottom:20px;' name = 'passengers[]'>";
foreach($seats as $res_seat){
echo "<option value='".$res_seat['seat_id']."'>".$res_seat['seat_number']."</option>";
}
echo "</select><br>";
$print++;
$name++;
}

PHP parse MYSQL after comma and output to html table

Thank you all for you help! I received some phenomenal help about 17 days ago which saved my *!. I am still learning PHP and have run across a new problem. I have a MYSQL database field called "Tracking" this is a long text field in which we want to input tracking numbers (for shipping) separated by commas . We ship some times 20-50 individual boxes in the same order.
The following script outputs to an HTML table the number of boxes being shipped (EX Box 1 of 12, Box 2 of 12...etc) and then the value of the tracking number field. I need to modify it so it parses at the "comma" in the Tracking field and includes the tracking number for each box. So Box 1: Tracking Number "take first tracking number and end at comma", So Box 2: Tracking Number "take second tracking number and end at comma"....etc...does this make sense?
Please provide whatever help possible, would greatly be appreciated!
Script:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('***','***','***','***');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db116223_wmi");
$sql="SELECT * FROM tbl_purchase_order WHERE purchase_order_id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
for ($i=0; $i<$row['product_quantity']; $i++) {
$my_val=1;
$x += 1;
echo "<table>";
echo "<tr>";
echo "<td width=400><br>Box $x of ". $row['product_quantity'] ." Tracking Number:". $row['Tracking'] ."</td>";
echo "</tr>";
echo "</table>";
}
}
mysqli_close($con);
?>
JB
As jjonesdesign mentioned, you need to use explode to break the tracking number field up at each comma. explode creates an array of values, each split out of the Tracking field. Look below for the solution:
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('***','***','***','***');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db116223_wmi");
$sql="SELECT * FROM tbl_purchase_order WHERE purchase_order_id = '".$q."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
$myTracking = explode(',',$row['Tracking']); // get an array of tracking numbers. Array element starts with 0
for ($i=0; $i<$row['product_quantity']; $i++) {
$my_val=1;
$x += 1;
echo "<table>";
echo "<tr>";
echo "<td width=400><br>Box $x of ". $row['product_quantity'] ." Tracking Number:". $myTracking[$i] ."</td>";
echo "</tr>";
echo "</table>";
}
}
mysqli_close($con);
?>

MSSQL and PHP: Select specific row based on which button is clicked

I am making a website for a mock book database using MSSQL where users can search for different books and select particular books that they might like to add to a list of favorites under their account name. The problem I am having is that I have no idea how to differentiate which book selection they want to add to their favorites because I can't figure out how to set the ISBN of the book, which uniquely identifies it, to a php session variable. If anyone can shed some light on this I would appreciate it, have been trying to figure it out all day.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
//Search to run if searching for book title
if(isset($_GET['searchBook'])){
$searchBook = $_GET['searchBook'];
$query = "SELECT BOOK.ISBN, Title, Author, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Title LIKE '%$searchBook%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Search to run is searching for a book author
if(isset($_GET['searchAuthor'])){
$searchAuthor = $_GET['searchAuthor'];
$query = "SELECT BOOK.ISBN, Title, Author, Genre, Publisher, NumberOfPages, Language, LocationName, ListPrice FROM BOOK, PRICE, LOCATION WHERE Author LIKE '%$searchAuthor%' AND BOOK.ISBN = PRICE.ISBN AND PRICE.LocationID = LOCATION.LocationID";
}
//Store query result
$query_result = mssql_query($query, $connection)
or die( "ERROR: Query is wrong");
//Set up table to display search results
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><input name=\"".$line['index']."\" type=\"submit\" value=\"Add To Favorites\"></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
Not sure if this is relevant but the following code is my best attempt at getting the value of ISBN that corresponds to the row of the button being clicked, which doesn't exactly work like I had hope.
//Get the ISBN
$data = mssql_fetch_assoc($query_result);
$ISBN = $data['ISBN'];
echo $ISBN;
Here is the code for my addFavorite.php which is where the form action is set to. This is the file that needs to know what user is adding a book as a favorite AND what book they are adding to that list.
//Set up connection
$connection = mssql_connect("$hostName", "$sqlUsername", "$sqlPassword")
or die("ERROR: selecting database server failed.");
//Select database
mssql_select_db($databaseName, $connection)
or die("ERROR: Selecting database failed");
$User = $_SESSION['userID'];
//Set up query
$query = "INSERT INTO FAVORITES VALUES(\"$User\",\"**I NEED A SESSION VARIABLE OR SOMETHING TO GO HERE\")";
//Store query result
$query_result = mssql_query($query, $connection)
//or die( "ERROR: Query is wrong");
Any help would be much appreciated. I know it's alot of information and if there is anything that doesn't make sense or I have forgotten to provide please let me know. Thanks.
EDIT
I have tried using the BUTTON instead of using INPUT but the value of the button is not setting to anything for some reason.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records **PROBLEM IN HERE since $line['ISBN'] returns nothing**
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line['ISBN']."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
EDIT 2
Finally got it working, thanks to everyone for helping! Partial code that was problematic posted below in working condition.
echo "<form action=\"addFavorite.php\" method=\"POST\" name=\"table\">";
echo "<table border=1 align=\"center\">";
echo "<tr>";
// fetch attribute names
while ($filed = mssql_fetch_field($query_result)) {
echo "<th>".$filed->name."</th>";
}
echo "<th>Favorite</th>";
echo "</tr>";
// fetch table records
while ($line = mssql_fetch_row($query_result)) {
echo "<tr>\n";
foreach ($line as $eachline) {
echo "<td> $eachline </td>";
}
echo "<td><button name=\"FavoriteButton\" type=\"submit\" value=\"".$line[0]."\">Add To Favorites</button></td>";
echo "</tr>\n";
}
echo "</table>";
echo "</form>";
Use a BUTTON-element instead of the INPUT-element. That way, you can use the 'value'-attribute of this element to pass the correct value.
echo "<td><button name=\"$line['index']\" value=\"$line['ISBN']\" type=\"submit\">Add to favorites</button></td>";
Although I would suggest using AJAX instead of the above approach for this: use the onclick event from a button to execute javascript that calls a seperate php-file and passes the correct ISBN-number. This is then added to the database and your original page should be refreshed or part of the page reloaded.

Categories