updating a field in mysql using php - php

|room type|price|avroom|
|standard |50 |20 |
| super |60 | 7 |
|suite |80 | 4 |
if reservation is made for "room type" = standard
the value entered in the "no of rooms" field in the form should be subtracted from the value in the "avroom" for the "room type" on the database
the code below outputs the form
</select></td>
<th align=left>ROOM TYPE :</th>
<td>
<?php
echo "<select name=txttype>";
$qup="select * from tariff where avroom > 0";
$rs=mysql_query($qup);
while($res=mysql_fetch_row($rs))
{
echo "<option value='".$res[0]."'>".$res[0]."</option>";
}
echo "<select>";
echo "</td>";
?>
<tr>
<th align=left>NO OF ROOMS :</th>
<td><select name=txtroom>
<?php
for($i=1;$i<=20;$i++)
{
echo "<option value=$i>$i</option>";
}
?>
please if you need any more info let me know

First thing I noticed in your mysql table is there cannot have a column like "room type" in a table. It should be edited to "room_type".
First of all, if you only need to display the room type in the top select box, your sql should be edited to $qup="select room_type from tariff where avroom > 0";. Then post the selected values using a html form.
From the other end where the form is posted, try something like,
$room_type= $_POST['txttype'];
$rooms = mysql_real_escape_string($_POST['txtroom']);
if($room_type == "standard")
{
$query = "UPDATE tariff SET avroom=avroom-{$rooms} WHERE room_type='standard'";
// Now execute the above query here.
}

Related

How to tell php to echo something acquired to the selected option

I have two tags, the first one is to select the brand and the second one is to select the product.
My question/problem is that I want to tell php to echo inside the second select tag. The echoed option needs to have the same brand_name as the selected option from the first tag.
What I need is that if I choose Adidas as the brand, php would show every product that has the brand_name Adidas.
I have two different database tables, the first one called brand:
brand_id | brand_name
1 | ADIDAS
2 | NIKE
The second one called product:
product_id | brand_name | product_name | product_image | amount | sell | buy
1 | ADIDAS | T-Shirt | none | 50 | 30 | 28
2 | NIKE | Shoes | none | 20 | 130 | 120
Here is my code:
<select>
<option disabled selected>----SELECT----</option>
<?php
require_once 'connections/dbc.php';
$query = "SELECT `brand_name` FROM `brands`";
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] ='Error loading the brands';
$_SESSION['errormessage'] = 'Something wrong happend while loading the brands.<br/>Please contact The developer';
header("location: error.php");
exit();
} else {
while($row = mysqli_fetch_array($response)){
echo '<option name="brand_name" value='.$row['brand_name'].'>'.$row['brand_name'].'</option>';
}
}
?>
</select>
<select>
<option disabled selected>----SELECT----</option>
<?php
require_once 'connections/dbc.php';
###########HERE WHERE I NEED MY CODE##############
$query = "SELECT `product_name` FROM `product WHERE brand_name = "##### The selected option from the first select tag" ";
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] = "Error loading the prouducts";
$_SESSION['errormessage'] = 'Something wrong happend while loading the proudcts.<br/>Please contact The developer';
header("location: error.php");
exit();
} else {
while($row = mysqli_fetch_array($response)){
echo '<option name="product_name" value='.$row['product_name'].'>'.$row['product_name'].'</option>';
}
}
?>
</select>
There are two options:
First: Download all contents of 'products' table, and make script that will add items with selected 'brand' attribute to box.
Second: (Recommended) When user selects a brand, make an AJAX query, and get all items with selected brand.
Second one is much better, because you will need to download less data, and page will load faster.
Imagine you have 10^9 products, and 10^7 brands(average 100 products per brand)
Using first solution, you will need to download all 10^9 products, and then use JavaScript(which is not very fast) to select 100 of them.
If you use second solution two things are going to be much better:
1. Download 100 items instead of 10^9.
2. To select items use fast SQL engine instead of slow JavaScript
It is not possible to do it with php, because php is server-side. Server is making page code with php, and then sending it to user. It's impossible to make callback to php without AJAX
The easiest way to do this would be to use a single SELECT with LEFT JOIN, to get all of the columns from both tables at the same time:
SELECT brands.brand_name, products.product_name FROM brands LEFT JOIN products on brands.brand_name = products.brand_name GROUP BY brands.brand_name
And build both of your <select> nodes from that single query. To do this, build your first <select> node from the query, the same as you are doing now, then in the lower part of the code reset the $response with $response->data_seek(0). Then you can build the second <select> as though you had done another query.
It will look something like the following code. There are only two minor changes to your original. Look for some comments in the top section, and some in the bottom section. I don't have an easy mechanism to run PHP, so I can't test it, and it might not run perfectly as it is now. But I think it will give you an idea of what to do.
<select>
<option disabled selected>----SELECT----</option>
<?php
require_once 'connections/dbc.php';
// Notice that the query includes LEFT JOIN, to get the
// columns from both tables in a single query.
$query = "SELECT brands.brand_name, products.product_name
FROM brands left join products on brands.brand_name = products.brand_name"
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] ='Error loading the brands';
$_SESSION['errormessage'] = 'Something wrong happend while loading the brands.<br/>Please contact The developer';
header("location: error.php");
exit();
} else {
while($row = mysqli_fetch_array($response)){
echo '<option name="brand_name" value='.$row['brand_name'].'>'.$row['brand_name'].'</option>';
}
}
?>
</select>
<select>
<option disabled selected>----SELECT----</option>
<?php
require_once 'connections/dbc.php';
// Here, you don't need another query. You simply reset
// $response, and then fetch as you would from a
// normal query.
$response->data_seek(0);
while($row = mysqli_fetch_array($response)){
echo '<option name="product_name" value='.$row['product_name'].'>'.$row['product_name'].'</option>';
}
?>
</select>
You can simply use Ajax to do this. I'll try to explain step by step.
I assume jQuery is loaded.
Your product table should use brand_id not brand_name.
product_id|brand_name | product_name | product_image | amount | sell | buy
1 |brand_name_1| T-Shirt | none | 50 | 30 | 28
2 |brand_name_2| Shoes | none | 20 | 130 | 120
I hope this will help you.
Step - Create your first and second select box by using name or id attributes. I will be using the name to define them.
<select name="brand_name">
<?php //call brand_name options from your database
//Sample : <option value="brand_name_1">Brand_Name_1</option>?>
</select>
<select name="product_name" disabled >
<?php //dont fill this select box.
//Leave it empty, contents will be created after our ajax call
?>
</select>
Step
Add jQuery script to your page as below.
<script>
$('[name="brand_name"]').change(function(event){
var brand_name = $(this).val();
$.get(
"ajax.php",
{ brand_name: brand_name },
function(data) {
var opts = $.parseJSON(data);
$.each(opts, function(i, d) {
$('[name="product_name"]').append($('<option>', {
value: d.product_name,
text : d.product_name
}));
});
//Enable the product_name select box
$('[name="product_name"]').prop('disabled', false);
//Refresh the product_name select box
$('[name="product_name"]').selectpicker('refresh');
}
);
});
</script>
Step - The ajax.php must look something like below. I have used your php query code here.
<?php
require_once 'connections/dbc.php';
$getBrandName = $_REQUEST['brand_name']; // This is the id of the selected brand name
$query = "SELECT product_name FROM product WHERE brand_id = '$getBrandName' ";
$response = #mysqli_query($conn, $query);
if (!$response) {
$_SESSION['errortitle'] = "Error loading the prouducts";
$_SESSION['errormessage'] = 'Something wrong happend while loading the proudcts.<br/>Please contact The developer';
//Below Header method will not work cause headers are already been set. You will not be able to redirect page. So just delete it. instead you can return an error by using the json.
header("location: error.php");
exit();
} else {
while($row = mysqli_fetch_array($response)){
$prodyctsArray[]['name'] = $row['product_name'];
}
echo json_encode($brandName);
}
?>
For more information I suggest you to visit references below:
jQuery.ajax()
jQuery.get()
Introducing JSON

Dynamic Optgroup in PHP

This is my current SQL Table I'm using to grab data for my php dropdown. The main goal of this is to turn this into a dropdown that has an optgroup with the members below and so on...
+-----------+------------+-----------+
| GroupName | MemberName | ValueName |
+-----------+------------+-----------+
| 1st Team | Joe Bob | Joe |
| 1st Team | Catherine | Kat |
| 2nd Team | Tommy | Tom |
| 3rd Team | John Razks | John |
+-----------+------------+-----------+
Table name: Members
Basically at the end result is such of the code below. It will be a dropdown with an optgroup called "1st Team" and have the members below ect. for 2nd Team and 3rd Team and so on.
<optgroup class="1st Team">
<option value="Joe">Joe Bob</option>
<option value="Kat">Catherine</option>
</optgroup>
<optgroup class="2nd Team">
<option value="Tom">Tommy</option>
</optgroup>
<optgroup class="3rd Team">
<option value="John">John Razks</option>
</optgroup>
Right now, this is how I get information from my SQL table. This works fine, but if I want to add a new GroupName then I would have to add a new code to my main page and I don't want to do that.
Trying make it dynamic so if the SQL table gets updated with a new GroupName, then a new optgroup class will appear in the dropdown and the members will be below.
<optgroup class="1st Team">
<?php
$conn = mysqli_connect("#connect_to_sql");
if(!$conn){
die("Connection Failed".myslqi_connect_error());
}
$result = mysqli_query($conn, "SELECT distinct MemberName from Members where GroupName = "1st Team" order by MemberName ASC");
while ($row = mysqli_fetch_assoc($result)){
unset($membername, $groupname);
$groupname = $row['GroupName'];
$membername = $row['MemberName'];
echo '<option value="'.$membername.'">'.$membername.'</option>';
}
?>
</optgroup>
I'm not positive at all on what to do. I've looked at other people's examples, but not sure how to approach this step.
First get all records from the database. create an array with keys as group name. Loop the new array to generate the desired output.
// query to get all records from database table
$result = mysqli_query($conn, "SELECT distinct MemberName,GroupName,ValueName from Members order by MemberName ASC");
while ($row = mysqli_fetch_assoc($result)){
// generate an array with keys as group name
$array[$row['GroupName']][] = $row;
}
// loop the array to create optgroup
foreach($array as $key=>$value){
// check if its an array
if(is_array($value)){
// create optgroup for each groupname
echo "<optgroup class='".$key."'>";
foreach($value as $k=>$v){
echo "<option value='".$v['membername']."'>'".$v['membername']."'</option>";
}
echo "</optgroup>";
}
}
I have not tested this but sure this will help you. And you can make improvements.
It's not the most elegant way, but you could build your group this way, what it's doing is checking the name of the group and changes that to a new optgroup each time the name changes, the $first var is just there so it doesn't add a closing tag the first time around.
I'm sure you can improve on this, but it should get you going.
It does kind of rely on a consistent naming convention for the group name, so as I say, I'm sure you could improve on it. I've also not included the connection checks as you've done that already in your example
$result = mysqli_query($conn, "SELECT * FROM Members ORDER BY GroupName");
$groupName = '';
$first = true;
echo '<select>';
while ($row = mysqli_fetch_assoc($result)){
if ($row['GroupName'] != $groupName) {
$groupName = $row['GroupName']; // Just set the new group name
if (!$first) { // Add a closing tag when we change the group, but only if we're not in the first loop
echo '</optgroup>';
} else {
$first = false; // Make sure we don't close the tag first time, but do after the first loop
}
echo '<optgroup label="' . $groupName . '">';
}
// We want to echo the options every loop so it's outside the if condition
echo '<option value="' . $row['MemberName'] . '">' . $row['ValueName'] . '</option>';
}
echo '</select>';

Saving 'if conditon statement' in database and to use it in php form

I have a table named user where I have inserted a value like
($workshop_sales*0.01)+($counter_sales*0.005)+($sub_dealer_sales*0.0075)
in column incentive and value like
if{$workshop_sales>1600000' in column 'open_cond' and value like '}
in close_cond.
Now in my PHP page I have fetched values from that table. How can I use values from my columns open_cond and close_cond because I wish to use it as expression otherwise please help me by giving other way to execute it.I am doing wrong then please give me information whether its possible that I can write 'if statement' in php using it store as a text value in database column value ?? ''
I am getting result as
if($workshop_sales>1600000){2123.085}
but I want to use it as PHP expression in my code.
<?php
$selectalldepartment = "select * from user ";
$selectedalldepartment = mysqli_query($conn,$selectalldepartment);
$selectedalldepartment = mysqli_query($conn,$selectalldepartment);
$depart=1;
while($row10 = mysqli_fetch_assoc($selectedalldepartment))
{
$sqlsel1 = "select * from parameters ";
$sqlsel1q = mysqli_query($conn,$sqlsel1);
$row2 = mysqli_fetch_assoc($sqlsel1q);
//assigned counter sales value
$counter_sales = $row2["counter_sales"];
?>
<tr>
<td style="text-align:center;"><?php echo $depart; ?></td>
<td style="text-align:center;"><?php echo $row10["open_condition"]; eval("echo {$row10['incentive']};");echo $row10["close_condition"];?></td> </tr>
<?php
$depaz++;
$depart++;
}
?>
Here is my table:
<!-- language: lang-none -->
user_id | user_name | incentive |open_cond | close_cond |
1 | Goldy Shahu | ($workshop_sales*0.01)+ | |
| | ($counter_sales*0.005)+ | |
| | ($sub_dealer_sales*0.0075)|if($workshop_sales> |
1600000){ |}
you should not store conditions into your table
need to store data like
$workshop_sales and 1600000 in seporate columns
then you can make condition
like something
if($row10["open_condition"] > $row10["open_condition_value"]){
//your code
}

output sql query in php

I'm a noob at php so I need a bit of help. I have a table with a list of hotels, the columns are
name | address | city | stars | price
so far I've made a dynamic drop-down menu where the user selects a city from the table, this is shown in the code below:
<?php
connection stuff blah blah
?>
<?php
$sql = "SELECT city FROM hotels";
$result_db = $db->query($sql);
if (!$result_db) {
echo $db->error . ' Error perform query!';
} else {
echo '<select name="value">';
echo '<option value="">-Select from below-</option>';
while ($row = $result_db->fetch_object()) {
echo '<option city="' . $row->city . '">';
echo $row->city;
echo '</option>';
}
echo '</select>';
}
?>
How would I now create a table where all the details of hotels in the selected city are outputted? I'm assuming I need another sql query, arrays (perhaps?) which then I echo into a table? :S But I have no idea how to.....
you need to use jquery to add event to your dropdown second in your table you should have an ID field..
You're table should be
Id | name | address | city | stars | price
next you need to create a query that will fetch the id and name fields and put it on a dropdown.
next you need to use jquery to add event to dropdown.
$(function() {
$("#hotel").change(function() {
});
})

(PHP) Categorize into an html opgroup based on mysql value

Basically I have a database with 66 bible books; some from old testament some from new. The bname value is the NAME of the book, while bsect has a value of O or N(new or old), how can I make my dropdown box dynamically display a book into an old or new optgroup based on whether its' bsect is O or N? My teacher said I have to make some array, but i have no idea how to do it. Any thoughts?
My database sample:
+-----------+-------+
| bname | bsect |
+-----------+-------+
| Genesis | O |
| Exodus | O |
| Leviticus | O |
+-----------+-------+
I don't want to have to rely on manually setting opgroups based on the NUMBER OF THE ENTRY, I want it to be dynamic based on value of bsect.
Right now I just have the following query with a select dropdown which puts the book into old or new based on its record number, but It will break if more books were to be added
$query = $mysqli->query("select distinct bname as Name from kjv");
?>
<select name="book">
<?php
$i=1;
while($option = $query->fetch_object()){
if($i==1) echo "<optgroup label='Old Testament'>";
else if($i==40) echo "<optgroup label='New Testament'>";
echo "<option value='$i'>".$option->Name."</option>";
$i++;
}
?>
Simply order by bsect and display different optgroups dynamically
<?php
$query = $mysqli->query("SELECT DISTINCT bsect, bname AS Name FROM kjv ORDER BY bsect");
?>
<select name="book">
<?php
$i = 1;
$bsect = "";
while($option = $query->fetch_object()){
if($bsect != $option->bsect) {
$bsect = $option->bsect;
echo "<optgroup label='{$bsect}'>";
}
else if($i==40) echo "<optgroup label='New Testament'>";
echo "<option value='$i'>".$option->Name."</option>";
$i++;
}
?>
Of course, then your books may be out of order. So what you would want to do is add a book-order column (border) that stores a number defining how to order the books in a given group, e.g.
ALTER TABLE kjy
ADD COLUMN border INT U?NSIGNED NOT NULL DEFAULT 0;
Then you can update the data to have the proper book order and do a query like this:
SELECT DISTINCT bsect, bname AS Name FROM kjv ORDER BY bsect, border;
Of course, this being the Bible, you aren't going to be adding books, so you can probably just define a static Book ID that defines the ordinality of each book. Then you could just sort by ID and know that "Old" and "New" books are coming out in the right order.
ALTER TABLE kjy
ADD COLUMN id INT UNSIGNED NOT NULL PRIMARY KEY BEFORE (bname);
This is how you can create 2 arrays in php,
$query = $mysqli->query("select distinct bname,bsect from kjv");
while($option = $query->fetch_object()){
if ($option->bsect == 'O'){
$books_old[] = $option->bname;
} elseif ($option->bsect == 'N'){
$books_new[] = $option->bname;
} else {
# Error collection - bsect not 'O' or 'N'
}
}
now you have 2 arrays which are lists of books; $books_old and $books_new.
I'd use the name as the value rather than an arbitrary index;
echo "<optgroup label='Old Testament'>";
foreach($books_old as $this_book){
echo "<option value=\"$this_book\">$this_book</option>";
}
echo "<optgroup label='New Testament'>";
foreach($books_new as $this_book){
echo "<option value=\"$this_book\">$this_book</option>";
}

Categories