Currently i'm doing my final year project about hotel management system. Now I'm stuck on using IF STATEMENT on PHP MYSQL query. I had create column named roomtype and roomprice under reservation table. The case are like this:
If guest selected single on roomtype, it automatically shown the
price on roomprice. Let say the price was 100.
Then if guest selected superior, the price is 200.
And then if deluxe was selected, the price is 300.
Below are my codes to store to database
$link = mysql_connect('localhost', 'root', '') or die('Could not connect: ' . mysql_error());
mysql_select_db('hotel_reservation3') or die('Could not select database');
// Store query in variable
$query = "INSERT INTO reservation (user_id,fullname,contactno,passport,roomtype,roomprice,num_of_rooms,dor,dco,bookingdate,length_of_stay)
VALUES
(
'".$_SESSION['user_id']."',
'".$_POST['fullname']."',
'".$_POST['contactno']."',
'".$_POST['passport']."',
'".$_POST['roomtype']."',
'".$_POST['num_of_rooms']."',
'".$_POST['dor']."',
'".$_POST['dco']."',
sysdate(),
DATEDIFF(dco,dor)
)";
// Performing SQL query
$result = mysql_query($query)
or die('Query failed: ' . mysql_error());
//echo "Success inserting record!";
// Closing connection
mysql_close($link);
header("Location:reservation.php?success");
I'm using POST method which comes from a form. Below are partial code of the form
<form action="" method="post">
<ul>
<li>
Full name*: <br>
<input type="text" name="fullname">
</li>
<li>
Contact No.: <br>
<input type="text" name="contactno">
</li>
<li>
IC/Passport*: <br>
<input type="text" name="passport">
</li>
<li>
Room Type*: <br>
<select name="roomtype" id="roomtype">
<option value="Single">Single</option>
<option value="Superior">Superior</option>
<option value="Deluxe">Deluxe</option>
</select>
</li>
<li>
Number of Rooms*:</li>
<input type="text" size="3" name="num_of_rooms">
<br>
<li>
Date of reservation*: <br>
<input type="text" size="12" id="dor" name="dor"/>
</li>
<li>
Check-out Date*: <br>
<input type="text" size="12" id= "dco" name="dco"/>
</li>
<input type="submit" value="Submit">
<input type="reset" value="Clear" >
<li>
<br>
<br>
<br>
<br>
<br>
<br>
</ul>
</form>
Does anyone know the code?
As everyone has mentioned, please protect your SQL from injection.
You should calculate your price in PHP.
if($_POST['roomtype'] == "deluxe"){
$roomprice = 300;
}else if($_POST['roomtype'] == "superior"){
$roomprice = 200;
}else{
$roomprice = 100;
}
// Store query in variable
$query = "INSERT INTO reservation (user_id,fullname,contactno,passport,roomtype,roomprice,num_of_rooms,dor,dco,bookingdate,length_of_stay)
VALUES
(
'".$_SESSION['user_id']."',
'".mysql_real_escape_string($_POST['fullname'])."',
'".mysql_real_escape_string($_POST['contactno'])."',
'".mysql_real_escape_string($_POST['passport'])."',
'".mysql_real_escape_string($_POST['roomtype'])."',
$roomprice,
'".mysql_real_escape_string($_POST['num_of_rooms'])."',
'".mysql_real_escape_string($_POST['dor'])."',
'".mysql_real_escape_string($_POST['dco'])."',
NOW(),
DATEDIFF(dco,dor)
)";
Related
I have a problem, to build INSERT PHP file with HTML form code. When I drop from HTML form, then this error pops out ""invalid input syntax for integer: "" LINE 2:""
in all code, I comment every single line and nothing.
There is my PHP script
`
$order_nr = pg_escape_string($_POST['order_nr']);
$date = pg_escape_string($_POST['date']);
$place = pg_escape_string($_POST['place']);
$service = pg_escape_string($_POST['service']);
$Vards = pg_escape_string($_POST['vards']);
$Uzvards = pg_escape_string($_POST['uzvards']);
$phone = pg_escape_string($_POST['phone']);
$email = pg_escape_string($_POST['email']);
$veids = pg_escape_string($_POST['veids']);
$passw = pg_escape_string($_POST['passw']);
$papildaprikojums = pg_escape_string($_POST['papildaprikojums']);
$save_info = pg_escape_string($_POST['save_info']);
$defekts = pg_escape_string($_POST['defekts']);
$query = " INSERT INTO serviss (order_nr, place, service, vards, uzvards, email, veids, passw, save_info, papildaprikojums, defekts)
VALUES ('$order_id', '$place', '$service', '$vards', '$uzvards', '$email', '$veids', '$passw', '$papildaprikojums', '$save_info', '$defekts') " ;
$result = pg_query($query);
if (!$result) {
$errormessage = pg_last_error();
echo "Error with query: " . $errormessage;
exit();
}
printf ("These values were inserted into the database - %s %s %s", $order_id);
pg_close();
There is my HTML form code
<form action="serviss.php" method="post" >
<div class="ievade">
Pasūtijuma numurs : <input type="text" size="5" name="order_id"> <br><br>
Pieņemšanas datums : <input type="date" data-date="" data-date-format="DD MMMM YYYY" value="2015-08-09" name="date"> <br><br>
Pieņemšanas vieta : <select name="place">
<option value="Ausekļa_iela_9"> Ausekļa iela 9 </option>
</select> <br><br>
Pieņēma : <select >
<option value="service" name="Maris"> Māris </option>
<option value="service name="Toms"> Toms </option>
</select> <br> <br>
Klienta vārds : <input type="text" name="vards" size="5"> <br><br>
Klienta uzvārds : <input type="text" name="uzvards" size="5"> <br><br>
Klienta tel.nr.: <input type="tel" id="phone" size="6"> <br><br>
Klienta e-pasts: <input type="text" value="example#test.net" name="email">
<br><br>
Iekārtas veids: <input type="text" value="iekārta" name="veids" size="5"> <br><br>
Parole: <input type="text" name="passw" size="5"> <br><br>
</div>
<div class="checkbox">
Garantija: <br>
Ir
<input type="radio" name="garantija" value="Ir"> <br>
Nav <input type="radio" name="garantija" value="Nav">
<br> <br>
</div>
<div class="ievade">
Papildaprīkojums: <input type="text" name="papildaprikojums" > <br><br>
Papildus informācija: <input type="text" name="informacija">
<br> <br>
Saglabājamā informācija: <input type="text" name="save_info">
<br> <br>
Defekta apraksts: <input type="text" name="defekts">
</div>
</div>
<input type="submit" value="Submit">
</form>
I hope you can help me.
I use PostgreSQL 10.10
It's like you have mixed up the 'order_id' with 'order_nr'.
The name value attribute is 'order_id' so when you try to get it it is
$_POST['order_id'] not `$_POST['order_nr']`
It means that either you should say
$order_nr = pg_escape_string($_POST['order_id']);
In order to use the variable into the insert statement and then
$query = " INSERT INTO serviss (order_nr, place, service, vards, uzvards, email, veids, passw, save_info, papildaprikojums, defekts)
VALUES ('$order_nr', '$place', '$service', '$vards', '$uzvards', '$email', '$veids', '$passw', '$papildaprikojums', '$save_info', '$defekts') " ;
or you shoud say
$order_id = pg_escape_string($_POST['order_id']);
And then
$query = " INSERT INTO serviss (order_nr, place, service, vards, uzvards, email, veids, passw, save_info, papildaprikojums, defekts)
VALUES ('$order_id', '$place', '$service', '$vards', '$uzvards', '$email', '$veids', '$passw', '$papildaprikojums', '$save_info', '$defekts') " ;
Essentially, i'm trying to select all the users from my table where their type ='users' and if that condition is met, select their first and last name. Store them into variables and then display the variables into a dropdown list one by one(array).
Current code:
<div id="ContainerC">
<form action="AppointmentAddQuery.php" method="post">
<input type="text" name="date" class="datepicker" placeholder="Please select a date" required><br>
<input type="text" name="patient" class="textbox" placeholder="Patient" required> <br>
<?php
include 'dbconnection.php';
?>
<input type="text" name="phlebotomist" class="textbox" placeholder="phlebotomist" required> <br>
<input type="text" name="bloods" class="textbox" placeholder="blood required" required><br>
<p>Has the appointment been allocated?</p>
<select name="allocated" class="textbox" required>
<option value="yes">yes</option>
<option value="no">no</option>
</select>
<br><br><br>
<button type="submit" name="submit" class="SUB">Add patient</button>
</form>
</div>
SQL setup:
For the SQL part of your question, you are probably looking for something like:
select firstname
, lastname
from <table>
where type = 'user'
Assuming the structure of your database (you will likely need to replace table and column names) this is how you could do it:
<?php
include 'dbconnection.php';
$sql = "SELECT firstname, lastname FROM users WHERE type = 'users'";
$result = $conn->query($sql) or die($conn->error);
if ($result->num_rows > 0) {
echo '<select>';
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<option value="'.$row["firstname"].$row["lastname"].'">'.$row["firstname"].$row["lastname"].'</option>';
}
echo '</select>';
} else {
echo '<select><option value="">No Users</option></select>';
}
$conn->close();
?>
This also assumes that inside of dbconnection.php you created a mysqli object like so:
$conn = new mysqli($servername, $username, $password, $dbname);
I am new to PHP and want to create a form where the user inserts data into the form (which works) and then that gets stored on MYSQL DB (that works), now the data has to be displayed and then must be able to modify certain records, now I have the part where the records shows and also the "edit" button, but something went wrong somewhere as the same record keeps appearing, so I guess something is wrong with my code :(
Please help:
Here is the index.php code:
<?php
include('dbinfo.php');
$sql="SELECT * FROM stats";
$result = mysql_query($sql, $db) or die (mysql_error());
$pageTitle = "My Stats Database";
include("header.php");
print <<<HERE
<h2> My Contacts</h2>
Select a Record to update add new stat.
<table id="home">
HERE;
while ($row=mysql_fetch_array($result)){
$id=$row["id"];
$type=$row["type"];
$depthead=$row["depthead"];
$person=$row["person"];
$descr=$row["descr"];
$recdate=$row["recdate"];
$tolog=$row["tolog"];
$senttorev=$row["senttorev"];
$recfromrev=$row["recfromrev"];
print <<<HERE
<tr>
<td>
<form method="POST" action="updateform.php">
<input type="hidden" name="sel_record" value="$id">
<input type="submit" name="update" value=" Edit " </form>
</td>
<td><strong> Description: </strong>$descr,<p> <strong>Type: </strong>$type</p> <p><strong> Department Head: </strong>$depthead</p>
<strong> Test Analyst: </strong> $person<br/></td>
HERE;
}
print "</tr></table></body></html>";
?>
Then here is my update updateform.php script:
<?php
include("dbinfo.php");
$sel_record = $_POST['sel_record'];
//$sel_record = (isset($_POST['sel_record'])) ? $_POST['sel_record'] : '';
$sql = "SELECT * FROM stats WHERE id = 'sel_record'";
//execute sql query and get result
$result = mysql_query($sql, $db) or die (mysql_error());
if (!$result) {
print "<h1> Something went wrong!</h1>";
} else
{ //begin while loop
while ($record = mysql_fetch_array($result, MYSQL_ASSOC)){
$id = $record["id"];
$type = $record['type'];
$depthead = $record['depthead'];
$person = $record["person"];
$descr = $record["descr"];
$recdate = $record["recdate"];
$tolog = $record["tolog"];
$senttorev = $record["senttorev"];
$recfromrev = $record["recfromrev"];
}
}
//end while loop
$pagetitle = "Edit Stat";
include ("header.php");
print <<<HERE
<h2> Modify this Stat</h2>
<p> Change the values in the boxes and click "Modify Record" button </p>
<form id="stat" method="POST" action="update.php">
<input type="hidden" name="id" value="$id">
<div>
<label for="type">Type*:</label>
<input type="text" name="type" id="type" value="$type">
</div>
<p>
</p>
<div>
<label for = "depthead" >Department Head*:</label>
<input type = "text" name = "depthead" id = "depthead" value = "$depthead">
</div>
<p>
</p>
<div>
<label for="person">Test Analyst*:</label>
<input type="text" name="person" id="person" value="$person">
</div>
<p>
</p>
<div>
<label for="descr">Description*:</label>
<input type="text" name="descr" id="descr" value="$descr">
</div>
<p>
</p>
<div>
<label for="recdate">Date Received*:</label>
<input type="text" name="recdate" id="recdate" value="$recdate">
</div>
<p>
</p>
<div>
<label for="tolog">Date to log*:</label>
<input type="text" name="tolog" id="tolog" value="$tolog">
</div>
<p>
</p>
<div>
<label for="senttorev">Sent to Rev:</label>
<input type="text" name="senttorev" id="senttorev" value="$senttorev">
</div>
<p>
</p>
<div>
<label for="recfromrev">Received from Rev*:</label>
<input type="text" name="recfromrev" id="recfromrev" value="$recfromrev">
</div>
<p>
</p>
<div id="mySubmit">
<input type="submit" name="submit" value="Modify Record">
</div>
</form>
HERE;
?>
And then the actual updating of the mysql has an update.php script:
<?php
include "dbinfo.php";
$id = $_POST['id'];
$type = $_POST['type'];
$depthead = $_POST['depthead'];
$person = $_POST['person'];
$descr=$_POST['descr'];
$recdate=$_POST['recdate'];
$tolog=$_POST['tolog'];
$senttorev=$_POST['senttorev'];
$recfromrev=$_POST['recfromrev'];
$sql="UPDATE stats SET
depthead='$depthead',
person='$person',
descr='$descr',
recdate='$recdate',
tolog='$tolog',
senttorev='$senttorev',
recfromrev='$recfromrev'
WHERE id='$id'";
$result=mysql_query($sql) or die (mysql_error());
print "<html><head><title>Update Results</titlel></head><body>";
include "header.php";
print <<<HERE
<h1>The new Record looks like this: </h1>
<td>
<p><strong>Type: </strong>$type</p>
<p><strong>Department Head: </strong>$depthead</p>
<p><strong>Test Analyst: </strong> $person</p>
<p><strong>Description: </strong>$descr</p>
<p><strong>Received Date:</strong>$recdate</p>
<p><strong>Date to Log:</strong>$tolog</p>
<p><strong>Sent to rev:</strong>$senttorev</p>
<p><strong>Received from Rev:</strong>$recfromrev</p>
<br/>
HERE;
Can someone please tell me why only one of the records keeps appearing doesn't matter which one I select from my index.php page. For some reason I think it is my $sel_record variable, but I am not sure and have run out of Ideas..
Thank you in advance..
Here's your issue in updateform.php:
$sql = "SELECT * FROM stats WHERE id = 'sel_record'";
That should be:
$sql = "SELECT * FROM stats WHERE id = $sel_record";
You missed out the $ symbol to call a variable, and you don't need quotation marks around an ID.
I am fairly new to both PHP and MySQL and would appreciate some help with this one.
What I am trying to achieve: store a time sheet into a MySQL table using the form below which should post each day's data into a separate row while keeping the same employee name for each day entered. The user has the option to add additional days to the form -- a max of 7. I've tested everything without the use of arrays and am able to store data to the table without any problems.
HTML:
<form id="timesheet" method="post" action="timekeep.php">
<fieldset>
<h1>Employee Info</h1>
<ul>
<li>
<label>First Name:</label>
<input name="firstname" type="text">
</li>
<li>
<label>Last Name:</label>
<input name="lastname" type="text">
</li>
</ul>
</fieldset>
<fieldset>
<h1>Time Info</h1>
<h3>Day: 1</h3>
<ul>
<li>
<input name="date[]" type="text">
</li>
<li>
<input name="straighthours[]" type="number">
</li>
<li>
<input name="overtimehours[]" type="number">
</li>
<li>
<input name="premiumhours[]" type="number">
</li>
<li>
<input name="perdiem[]" type="number">
</li>
</ul>
<h3>Day: 2</h3>
<ul>
<li>
<input name="date[]" type="text">
</li>
<li>
<input name="straighthours[]" type="number">
</li>
<li>
<input name="overtimehours[]" type="number">
</li>
<li>
<input name="premiumhours[]" type="number">
</li>
<li>
<input name="perdiem[]" type="number">
</li>
</ul>
</fieldset>
<input id="submit" name="submit-time" type="submit" value="Submit Time">
</form>
PHP:
$sql_connection = mysql_connect($dbhost, $dbuser, $dbpass) OR DIE ("Unable to connect to database! Please try again later.");
mysql_select_db($dbuser, $sql_connection);
$sql = "INSERT INTO table (
Date,
FirstName,
LastName,
StraightHours,
OvertimeHours,
PremiumHours,
TotalHours,
PerDiem
)
VALUES (".
PrepSQL($date) . ", " .
PrepSQL($firstName) . ", " .
PrepSQL($lastName) . ", " .
PrepSQL($straightHours) . ", " .
PrepSQL($overtimeHours) . ", " .
PrepSQL($premiumHours) . ", " .
PrepSQL($totalHours) . ", " .
PrepSQL($perDiem) . "
)";
mysql_query($sql, $sql_connection);
mysql_close($sql_connection);
function PrepSQL($value)
{
if(get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
$value = "'" . mysql_real_escape_string($value) . "'";
return($value);
}
Using PDO object would make this easier, mysql_ is legacy anyway:
$db = new PDO($hostname,$username,$password);
$qry = "INSERT INTO table (
Date,
FirstName,
LastName,
StraightHours,
OvertimeHours,
PremiumHours,
TotalHours,
PerDiem
)
VALUES (:date, :firstname, :lastname, :straighthours, :overtimehours, :premiumhours, :totalhours, :perdiem)"; // colon variables will be bound to actual variable
$statement = $db->prepare($query); //prevents injection
// binds variables to place holder in query
$statement->bindValue(':firstname', $firstname);
$statement->bindValue(':lastname', $lastname);
$statement->bindValue(':straighthours', $straighthours);
$statement->bindValue(':overtimehours', $overtimehours);
$statement->bindValue(':premiumhours', $premiumhours);
$statement->bindValue(':totalhours', $totalhours);
$statement->bindValue(':perdiem', $perdiem);
$statement->execute();
$statement->closeCursor();
you can do further input checking with php before passing anything to the sql via:
trim(strip_tags(htmlentities($firstname)));
PDO is a lot simpler to use and understand IMO
UPDATE:
tutorials on PDO
UPDATE #2:
For added functionality with arrays per day you can do:
<input type="text" name="firstname1">
// do this for all fields then
$workingday1 = array();
$workingday1['firstname'] = $_GET['firstname1'];
// etc. for all the other fields
Then you can access the field by:
$workingday1 = $_GET['workingDay1']; // or post or however you want to pass it
$firstname = $workingday['firstname'];
After that you can prune your database however you like. You can have a single table with all the values and edit your selects to display by employee or day or w/e. You can also have a table for each employee and then grab from those tables and display the data how ever you like.
I've successfully login with a user account and now i will like to insert records. As below is the code that has not been successful in inserting record.
<?php
session_start();
echo "Welcome: ". $_SESSION['role'];
?>
<?php
error_reporting(0);
if (!$_POST['submit'])
{
?
<html>
<body>
<br><br>
<fieldset >
Add a new user
<br>
<br>
<label for='username'>Username: </label>
<input type='text' name='username' id='username'/>
<label for='password'>Password: </label>
<input type='password' name='password' id='password' maxlength="50" />
<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
Role:
<br>
<select name="role">
<option value="" selected="selected"></option>
<option VALUE="Administrator"> Administrator</option>
<option VALUE="Secretary"> Secretary</option>
<option VALUE="Employee"> Employee</option>
</select>
<input type='submit' name='Submit' value='Submit' />
</form>
</fieldset>
<table width=100%>
</html>
</body>
<?php
}
else
{
$conn=odbc_connect("employee","","") or die (odbc_errormsg());
if (!$conn)
{
exit
("Connection Failed: " . $conn);
}
$query = "INSERT INTO empTable (empID, password, Role, Days left in MC, Days left in leave) VALUES" .
"('$_POST[username]', '$_POST[password]', '$_POST[role]', 14, 14)";
$result=odbc_exec($conn,$query) or die ("result error ".odbc_error().'-'.odbc_errormsg());
odbc_fetch_row($result);
odbc_close($conn);
}
After clicking the submit button and when i refresh my database, nothing comes out. Why is that so? Thanks alot
Access doesn't like column names with blanks. You have to mask them with [ ].
Change your INSERT query like this:
$query = "INSERT INTO empTable (empID, password, Role, [Days left in MC], [Days left in leave]) VALUES ..."