I'm trying to build a booking system for hotels, and i can now insert a new booking, but i want it to check if the room is free on the dates of the booking!
Database Schema
CREATE TABLE IF NOT EXISTS `bookings` (
`booking_id` int(10) NOT NULL AUTO_INCREMENT,
`user_id` int(10) NOT NULL,
`room_no` int(10) NOT NULL,
`hotel_id` int(10) NOT NULL,
`from_time` date DEFAULT NULL,
`to_time` date DEFAULT NULL,
PRIMARY KEY (`booking_id`),
KEY `FK_Users_id` (`user_id`),
KEY `user_id` (`user_id`),
KEY `user_id_2` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin AUTO_INCREMENT=15 ;
Php
include_once 'DbConnection.php';
$room_no = $_POST['roomNo'];
$hotel_id = $_POST['hotel_id'];
$from_date = $_POST['from'];
$to_date = $_POST['to'];
$user_id = $_SESSION['id'];
$date_checker_sql ="SELECT * FROM bookings WHERE hotel_id = $hotel_id";
$result = $mysqli->query($date_checker_sql);
while($row = $result->fetch_object()){
echo $row->booking_id;
if($row->from_time <= $from_date && $row->to_date >= $to_date && $row->room_no = $room_no){
$message = "booking if works.";
echo "<script type='text/javascript'>alert('$message');</script>";
}else{ $message = "something wrong";
echo "<script type='text/javascript'>alert('$message');</script>";
}
}
$insert_post_sql = "INSERT INTO bookings
SET room_no='$room_no', hotel_id='$hotel_id', from_time='$from_date', to_time='$to_date', user_id='$user_id'
";
if ($mysqli->query($insert_post_sql)) {
$message = "hotel created - logging you out sir.";
echo "<script type='text/javascript'>alert('$message');</script>";
//header("location: index.php");
}else{
echo 'something went wrong';
Right now, it books the hotel, since the insert sql is not in the while loop.
But when it checks, it never alerts the message "booking if works" - I just can't figure out how to construct it properly.
All help is much appreciated!
Related
I am trying to build a friend system in php I have the tables, database and the logic in place. I am having trouble getting the friend request receiver's id.
I have registeredusers friends updates table. The registeredusers table looks like this,
CREATE TABLE `registeredusers` (
`id` int(11) NOT NULL,
`FirstName` varchar(50) NOT NULL,
`LastName` varchar(50) NOT NULL,
`UserName` varchar(50) NOT NULL,
`Email` varchar(50) NOT NULL,
`Password` varchar(255) NOT NULL,
`ResetPassword` int(7) DEFAULT NULL,
`friends` int(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
friends
CREATE TABLE `friends` (
`friend_one` int(11) NOT NULL,
`friend_two` int(11) NOT NULL,
`status` enum('0','1','2') DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The requester's ID would be INSERTED into friend_two and receiver's ID would get into friend_one. here's my code
<?php
include 'dbh.php';
$sql = "SELECT * FROM registeredusers";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$username = $row['UserName'];
$requesterU = $_GET['user'];
echo "the requester is ".$requesterU;
while($row=mysqli_fetch_array($result)){
$id = $row[0];
$username = $row[1];
echo "
<form action='list of users.php'>
$id $username<input type='submit' value='send request' name='friendsbanalo'></input></form>";
}
$sql = "SELECT * FROM registeredusers WHERE UserName = '$requesterU'";
$result = mysqli_query($connection,$sql);
$row = mysqli_fetch_assoc($result);
$requester_id = $row['id'];
echo "requester's id ".$requester_id;
if(isset($_POST['friendsbanalo'])){
$sql = "INSERT INTO friends (friend_one,friend_two) VALUES('$requester_id','$reciver_userid')";
$result = mysqli_query($connection, $sql);
}else{
echo "error";
}
?>
I am not able to get the receiver's ID, can anyone tell me how can I get receiver's ID? I tried searching for the solution and the answers were too complicated for me to understand. I tried (on a separate file) INNER JOIN but I couldn't get it to work.
I have created a forum where people can register/login to post topics and replies.
Now I added a Delete link next to each topic that if pressed will go to deletetopic.php and if the user has created this topic it will be deleted, if not, it will say You Didn't create this topic.
this is the deletetopic.php
<?php
session_start();
include("config.php");
if(!isset($_SESSION['uid'])){
echo "<p><b>ERROR: Please log in to delete a topic.";
}
if(isset($_SESSION['username']))
{
$uid = $_SESSION['uid'];
$id=$_GET['id'];
$query1=mysql_query("delete FROM topics WHERE id='$id' and uid='$uid'");
if($query1){
header('location:index.php');
}
else{
echo "<p><b>ERROR: You didnt make this topic.";
}
}
It doesnt work, it just gives me the else {error}
here are my tables:
CREATE TABLE `users` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`firstname` VARCHAR(255) NOT NULL,
`lastname` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL,
`username` VARCHAR(255) NOT NULL,
`password` VARCHAR(100) NOT NULL,
PRIMARY KEY (`id`)
CREATE TABLE `topics` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`categoryID` TINYINT(4) NOT NULL,
`topicTitle` VARCHAR(150) NOT NULL,
`topicCreator` INT(11) NOT NULL,
`topicLastUser` INT(11) NOT NULL,
`topicDate` DATETIME NOT NULL,
`topicReplyDate` DATETIME NOT NULL,
`topicViews` INT(11) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
EDIT:
uid comes from here I think: login.php
if (isset($_POST['username'])){
$username = $_POST['username'];
$password = $_POST['password'];
$sql = "SELECT * FROM users WHERE username='".$username."' AND password='".$password."' LIMIT 1";
$result = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($result) == 1){
$row = mysql_fetch_assoc($result);
$_SESSION['uid'] = $row['id'];
$_SESSION['username'] = $row['username'];
header("Location: index.php");
exit();
}else{
echo "<p>Invalid information. Please return to the previous page.";
exit();
}
}
Update
if(isset($_SESSION['username']))
{
$uid = $_SESSION['uid'];
$id=$_GET['id'];
$check = mysql_query("SELECT * FROM topics WHERE id = '$id' AND topicCreator = '$uid'");
if($check){
$query1=mysql_query("delete FROM topics WHERE id='$id' AND topicCreator='$uid'");
header('location:index.php');
}
else{
echo "<p><b>ERROR: You didnt make this topic.";
}
}
Still doesnt work, just goes back to index
There is no uid column in table topics, it is probably topicCreator:
$query1=mysql_query("delete FROM topics WHERE id='$id' and topicCreator='$uid'");
You should consider the comments left here about changing from mysql to mysqli or PDO. And use of prepared statements to prevent SQL injections.
There is another problem. You need to check if the user is the topicCreator BEFORE deleting the topic.
$check = mysql_query("SELECT * FROM topics WHERE id = '$id' AND topicCreator = '$uid'");
if($check){
// Allow deletion
}
else{
// Don't allow deletion
}
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I need help,
Scenario: Hotel, Checking Guests In. data in MySQL database.
MySQL:
CREATE TABLE IF NOT EXISTS `hotels` (
`ID` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(50) NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Room01` int(11) NOT NULL,
`Room02` int(11) NOT NULL,
`Room03` int(11) NOT NULL,
`Room04` int(11) NOT NULL,
`Room05` int(11) NOT NULL,
`Room06` int(11) NOT NULL,
`Room07` int(11) NOT NULL,
`Room08` int(11) NOT NULL,
`Room09` int(11) NOT NULL,
`Room10` int(11) NOT NULL,
PRIMARY KEY (`ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
$result = mysql_query("SELECT * FROM hotels WHERE Name = 'hotel1'");
$row = mysql_fetch_array($result);
$room01 = $row['room01'];
0 = empty, 1 = not empty.
here is my code:
<?php
//example
$room01=1;
$room02=1;
$room03=0;
$room04=0;
//example
if ($room01 == 0)
{
echo "Your room is room01.";
}
elseif ($room02 == 0)
{
echo "Your room is room02.";
}
elseif ($room03 == 0)
{
echo "Your room is room03.";
}
elseif ($room04 == 0)
{
echo "Your room is room04.";
}
else
{
echo "None!";
}
?>
Result: Your room is room03.
What if I have 100 Rooms?
How to simplify if else statement and get the room name?
Use array_filter to find all empty rooms from database result and then print first room name, if any. Here's how you can write code without assuming there are 100 or n number of rooms in your database.
const EMPTY_ROOM = 0;
const OCCUPIED_ROOM = 1;
$rows = mysql_fetch_array($result);
$emptyRooms = array_filter($rows, function($room_value) {
return EMPTY_ROOM === $room_value;
});
if(empty($emptyRooms) || !is_array($emptyRooms)) {
echo 'None!';
return;
}
$rooms = array_keys($emptyRooms);
echo 'Your room is ' . $rooms[0] . '.' . PHP_EOL;
Update: It's probably because strict check is failing (EMPTY === $room_value). When you get data from database $room_value holds string data. Here's updated code:
function readDatabase() {
$handle = mysql_connect('localhost', 'root');
mysql_select_db('stackexchange');
if(!$handle) {
exit(mysql_error($handle));
}
$result = mysql_query("SELECT * FROM hotels WHERE Name = 'hotel1'", $handle);
return mysql_fetch_array($result, MYSQL_ASSOC);
}
$row = readDatabase();
const EMPTY_ROOM = '0';//set to string value to compare against database value
//use `array_slice` to get rid of columns: `id`, `Name`, `Date`.
//We want to search only in remaining columns: Room01, Room02 .... RoomN.
$row = array_slice($row, 3);
$emptyRooms = array_filter($row, function($room_value) {
return EMPTY_ROOM === $room_value;
});
if(empty($emptyRooms) || !is_array($emptyRooms)) {
echo 'None!';
return;
}
$rooms = array_keys($emptyRooms);
echo 'Your room is ' . $rooms[0] . '.' . PHP_EOL;
This should work (small explanation inside):
$row = mysql_fetch_array($result);
$roomNumber = 1;
//Get data from array
foreach($row as $data){
//if room returns 0 (empty)
if($data == 0){
if($roomNumber < 10){
echo "Your room is room0". $roomNumber;
break;
} else {
echo "Your room is room". $roomNumber;
break;
}
} else {
$roomNumber++;
}
}
The benefit of this approach is that it doesn't matter how many rooms you have. You can add or remove as many as you like. It'll loop through all of them, without having to adept the code.
EDIT:
After #Strawberrys comment, I realise that although my answer will work, this is not the way you should continue. Database normalisation would be the way to go. For example:
CREATE TABLE `hotels` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`Name` VARCHAR(64) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
CREATE TABLE `rooms` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`Hotel_id` INT(11) NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`Room_number` INT(5) NOT NULL,
`Occupied` INT(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
Using this type of Database design, you can easily add and remove Hotels to your system. Using Hotel_id as a reference, you can now easily add and remove rooms to your Hotels, without having to use an insane amount of table columns.
To use it, you simply query the Hotel_id inside rooms to get all rooms returned. Afterwards it's just a matter of checking the first Room_number where Occupied returned 0.
use array_search
const EMPTY_ROOM = 0;
$roomNumber = array_search(EMPTY_ROOM, $row);
if(false === $roomNumber) {
echo 'None!';
return;
}
echo 'Your room is ' . $roomNumber . '.' . PHP_EOL;
Update
hmm, I used test data to generate input. With your table structure here's updated code:
function readDatabase() {
$handle = mysql_connect('localhost', 'root');
mysql_select_db('stackexchange');
if(!$handle) {
exit(mysql_error($handle));
}
$result = mysql_query("SELECT * FROM hotels WHERE Name = 'hotel1'", $handle);
return mysql_fetch_array($result, MYSQL_ASSOC);
}
const EMPTY_ROOM = 0;
const OCCUPIED_ROOM = 1;
$row = readDatabase();
//use `array_slice` to get rid of columns: `id`, `Name`, `Date`. We want to search only in remaining columns: Room01, Room02 .... RoomN.
$roomNumber = array_search(EMPTY_ROOM, array_slice($row, 3));
if(false === $roomNumber) {
echo 'None!';
return;
}
echo 'Your room is ' . $roomNumber . '.' . PHP_EOL;
I am using this code for registering users, but it is not working. It always echos "Registration failed." I tried many times but nothing works
if(isset($_POST['sub']))
{
$uname = $_POST['uname'];
$email = $_POST['email'];
$pass_hash = PassHash::hash($_POST['pass']);
$sq="SELECT * FROM user WHERE username='$uname'";
//echo $sq;
$re=mysqli_query($link,$sq);
if(mysqli_num_rows($re)>0)
{
echo "Username already taken !";
}
else
{
$SQ = "SELECT * FROM user WHERE email='$email'";
//echo $SQ;
$res=mysqli_query($link,$SQ);
if(mysqli_num_rows($res)>0)
{
echo "Email already taken !";
}
else
{
$SQL = "INSERT INTO user(username,email,password) VALUES('$uname','$email','$pass_hash')";
//echo $SQL;
$result = mysqli_query($link,$SQL);
if(!$result)
{
echo "Registration failed !";
}
else
{
echo"register done";
}
}
}
}
below is table structure
CREATE TABLE `user` (
`id` int(11) NOT NULL auto_increment,
`username` varchar(20) NOT NULL,
`password` varchar(100) NOT NULL,
`email` varchar(20) NOT NULL,
`status` int(11) default '0',
`sdate` date NOT NULL,
`s_type` varchar(2) NOT NULL,
`amount` decimal(10,2) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
Does anyone know what the problem is?
You have a bunch of not null fields in your table, but you're not assigning them any values, so your insert query fails.
Good day to all. I'm trying to make a task tracking module for my system. The logic is, whenever I assign a task to a user, the system updates the task to "IsTaken" meaning the particular user is responsible for that task. Upon updating, it creates an entry into "user_task" table which basically ties together the task and the user table. Whenever I assign a task to somebody it's fine. But when I do it again, the previous task record's IsTaken field reverts back to 0. I try to re-assign it, but again, the previous record reverts. It's quite weird. I'm using XAMPP, MySQL and PHP. I'm hoping I'm not the only one experiencing this. Any help would be much appreciated.
Here are my tables:
CREATE TABLE IF NOT EXISTS `task` (
`Task_No` int(11) NOT NULL AUTO_INCREMENT,
`Task_Name` varchar(100) NOT NULL,
`Task_Desc` varchar(450) DEFAULT NULL,
`Task_DateCreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Task_IsTaken` tinyint(1) NOT NULL,
PRIMARY KEY (`Task_No`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
CREATE TABLE IF NOT EXISTS `user_task` (
`UT_No` int(11) NOT NULL AUTO_INCREMENT,
`User_Email` varchar(100) NOT NULL,
`Task_No` int(11) NOT NULL,
`Task_Duration` varchar(20) NOT NULL,
`Task_DateTaken` date DEFAULT NULL,
`Task_DateFinished` timestamp NULL DEFAULT NULL,
`Task_IsIssue` tinyint(1) NOT NULL,
PRIMARY KEY (`UT_No`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
And here are my scripts (from the form):
//Process - Insert Task
if(isset($_POST['btnCreateTask']))
{
if($_POST['taskName']!=NULL)
{
$taskName = mysql_real_escape_string ($_POST['taskName']);
$taskDesc = mysql_real_escape_string ($_POST['taskDesc']);
$insertTask = "INSERT INTO task(Task_Name, Task_Desc, Task_IsTaken) VALUES('$taskName', '$taskDesc', 0)";
$sqlResult1 = mysql_query($insertTask);}
else
{
echo "No task name given";
$errorCode = 1;
}
}
if(isset($_POST['btnAssignTask']))
{
if($_POST['assignTaskName']!=NULL)
{
$assigntaskName = mysql_real_escape_string($_POST['assignTaskName']);
$assigntaskNo = mysql_real_escape_string($_POST['assignTaskNo']);
$assigntaskOwner = mysql_real_escape_string($_POST['assignTaskOwner']);
$assigntaskDuration = mysql_real_escape_string($_POST['assignTaskDuration']);
$updateUpcomingTask = "UPDATE task SET Task_IsTaken = '1' AND Task_No = '$assigntaskNo'";
$createUserTask = "INSERT INTO user_task (User_Email, Task_No, Task_Duration, Task_DateTaken, Task_DateFinished)
VALUES ('$assigntaskOwner', '$assigntaskNo', '$assigntaskDuration', '$now', NULL)";
$sqlResult2 = mysql_query($updateUpcomingTask);
$sqlResult3 = mysql_query($createUserTask);
}
else
{
echo "No task selected";
$errorCode = 2;
}
}
Your code should be changed to:
if(isset($_POST['btnAssignTask']))
{
if($_POST['assignTaskName']!=NULL)
{
$assigntaskName = mysql_real_escape_string($_POST['assignTaskName']);
$assigntaskNo = intval($_POST['assignTaskNo']);
$assigntaskOwner = mysql_real_escape_string($_POST['assignTaskOwner']);
$assigntaskDuration = mysql_real_escape_string($_POST['assignTaskDuration']);
$updateUpcomingTask = "UPDATE task SET Task_IsTaken = '1' WHERE Task_No = $assigntaskNo";
$createUserTask = "INSERT INTO user_task (User_Email, Task_No, Task_Duration, Task_DateTaken, Task_DateFinished)
VALUES ('$assigntaskOwner', '$assigntaskNo', '$assigntaskDuration', '$now', NULL)";
$sqlResult2 = mysql_query($updateUpcomingTask);
$sqlResult3 = mysql_query($createUserTask);
}
else
{
echo "No task selected";
$errorCode = 2;
}
}