Booking System. checking for existing data - php

I want to check and compare the information on my input form with information that is stored in my database.
Basically. if trainer, sessionslot eventdate is the same dbtrainer, dbeventdate dbsessionslot ECHO "Booked";
Else insert into booking table
I know very little about programming, could really do with some help on this one.
This is snippet of the code i am using.
if(isset($_GET['add'])){
$trainee = $_POST['txttrainer'];
$trainer = $_POST['txttrainee'];
$sessionSlot = $_POST['txtsession'];
$eventdate = $month."/".$day."/".$year;
$query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");
$sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";
$resultinsert = mysql_query($sqlinsert);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
echo "this timeslot is booked"
if($resultinsert){
echo "Booking Successful....";
}else{
echo "Booking Failed";
}
}
}

if(isset($_GET['add'])){
$trainee = $_POST['txttrainer'];
$trainer = $_POST['txttrainee'];
$sessionSlot = $_POST['txtsession'];
$eventdate = $month."/".$day."/".$year;
$query = mysql_query("SELECT * FROM BOOKING WHERE trainer='$trainer' AND SessionSlot='$sessionslot");
$sqlinsert = "insert into booking (Trainee,Trainer,sessionSlot,eventDate,dateAdded) values ('".$trainee."','".$trainer."','".$sessionSlot."','".$eventdate."',now())";
$numrows = mysql_num_rows($query);
if($numrows >0) {
echo "this timeslot is booked"
}else{
$resultinsert = mysql_query($sqlinsert);
if(mysql_error()==""){
echo 'time slot booked';
}else{
echo 'error';
}
}
}
Explanation:
if there are rows selected, the timeslot is booked, else execute the query. If there is no error with the query, then print out success.

If you call mysql_query, the query is executed. So you're executing the INSERT before you check whether the SELECT returned a row or not.
That means you should place the INSERT part inside an if($numrows != 1) condition.
Please be aware that using mysql_query is deprecated: http://ch1.php.net/manual/en/function.mysql-query.php and you should use MySQLi or PDO_MySQL. Your code is vulnerable to SQL injections.

Related

How to make insert data with checker when value exist the insert function not triggered

I want to make an insert function with php mysqli.
But before I do the insert function I need to check the value in the table does not exist. My value is an array. I am really don't know how to do it.
The checker will be checking
'".$item['no_pol']."','".$item['date']."','".$item['time']."' when that Value exist the insert function will not run.
This is the code I just made. I would appreciated when help me with an example.
<?php
include("../../Connections/koneksi.php");
if(isset($_POST['table-bordered'])){
$array=json_decode($_POST['table-bordered'],true);
foreach($array as $item) {
$sql = "INSERT INTO wjm (sloc,kode,nama,no_pol,id,date,netto,uses,unit,payroll,time) VALUES ('".$item['sloc']."', '".$item['kode']."', '".$item['nama']."', '".$item['no_pol']."', '".$item['id']."', '".$item['date']."', '".$item['netto']."', '".$item['Unit']."', '".$item['uses']."', '".$item['payroll']."', '".$item['time']."')";
if(mysqli_query($db, $sql)){
echo "Records inserted successfully.";
} else{
echo "Records inserted failed ";
}
}
}else{
false;
}
?>
Just run a query and use row count to determine if it exists:
choose a select column that's unique per column, like for example a list of employee ID numbers, do id=231231.
If nothing is unique, then you could try a WHERE with multiple key conditions but that's not advised.
foreach($array as $item){
$sql = "SELECT no_pol, date, time from wjm WHERE no_pol = ? AND date = ? AND time = ?";
// some unique combination
if($stmt = $db->prepare($sql)){
$stmt->bind_param("sss",$item['no_pol'],$item['date'],$item['time']);
$stmt->execute()
$stmt->store_result();
$rows = $stmt->num_rows;
$stmt->fetch();
$stmt->close();
}
if($rows == 0){
//do your insert
}else{
//don't insert and say record exists
}
}
You have to run the SELECT query which return the count of records so,if record is not present in database table means SELECT query returns 0 that means COUNT will be 0 and when COUNT == 0 at that time you have to execute your INSERT query just as follow:
<?php
include("../../Connections/koneksi.php");
if(isset($_POST['table-bordered'])){
$array=json_decode($_POST['table-bordered'],true);
foreach($array as $item) {
$sql_query = "Select count('*') from wjm where no_pol = '".$item['no_pol']."' AND date = '".$item['date']."' AND time = '".$item['time']."'";
if($result = mysqli_query($db, $sql_query)){
$count = mysqli_num_rows($result);
/** Check the count of returned records **/
if($count == 0){
$sql = "INSERT INTO wjm (sloc,kode,nama,no_pol,id,date,netto,uses,unit,payroll,time) VALUES ('".$item['sloc']."', '".$item['kode']."', '".$item['nama']."', '".$item['no_pol']."', '".$item['id']."', '".$item['date']."', '".$item['netto']."', '".$item['Unit']."', '".$item['uses']."', '".$item['payroll']."', '".$item['time']."')";
if(mysqli_query($db, $sql)){
echo "Records inserted successfully.";
} else{
echo "Records inserted failed ";
}
}
}
}
}else{
false;
}
?>
Hope it will work for you.

Booking Availability

I have a database field which are
Appt_Datetime (which is call as DateTime in my table)
Svc_ID (which i call ApptType in my table)
I wanted the system to let the customer know that the datetime for the appt type is not available once someone else has book that slot.I have done a lot of research and trying out different codes but to no avail. I've seen answers on stackoverflow that uses PDO but im not so clear about it hence i'd like something to do with mysql. I have been stuck at with this at least few weeks now. Help
This is my call func:
$datetime = $_POST['DateTime'];
$appt = $_POST['ApptType'];
This is the query i last tried out but still is not working:
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
$result = mysql_query($query, $conn);
$row = mysql_fetch_assoc($result);
if($row==1)
{
echo "Date in not available";
}
else if($row==0)
{
$query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn);
}
Hint:
change this to $result = mysql_query($query, $conn); to $result = mysql_query($vquery, $conn);
at the time you are using $conn you do not have $query it is $vquery:
$result = mysql_query($vquery, $conn);
And as suggested above in comments better use mysqli or PDO.
you can try this condition..
//Define query
$vquery = "SELECT * FROM Appointment where Appt_DateTime='$datetime' && Svc_ID='$appt'";
//Run Query
if($result = mysql_query($vquery, $conn)){
//$row = mysql_fetch_assoc($result);
if(mysql_num_row($result)>0)
{
echo "Date in not available";
}
else
{
/* $query = "INSERT INTO Appointment (Client_ID,Svc_ID,Appt_DateTime)
VALUES ('$_POST[ClientID]','$_POST[ApptType]','".date('Y-m-d H:i:s', strtotime($_POST[DateTime]))."')";
mysql_query($query,$conn); */
echo "insert";
}
}else{
echo mysql_error();
}

limit the submission of form by date

Here is my coding. Basically i want to set form limitation based on user defined in ($result2). Another thing is the date. Eg. Today can submit 3 form then tomorrow can submit another 3 form until the user makes the changes on $result2. The problem from this code it will ignore the date and keep let user submit the form without the limit. Hope you guys can help, thanks
$name = $_POST['name'];
$address = $_POST['address'];
$contact = $_POST['contact'];
$email = $_POST['email'];
$tbl_name="torder";
$sql="INSERT INTO $tbl_name
(name,address,contact,email,orderdate)
VALUES('$name','$address','$contact','$email',now())";
$tbl2_name="tblfree";
$query="SELECT * FROM tblfree";
$result2=mysql_query($query);
$row = mysql_fetch_array(
mysql_query("SELECT COUNT(*) AS 'submit' FROM torder"));
if ($row['submit'] > $result2) {
echo 'We have reached our Free-T limit';}
else {
$result=mysql_query($sql);
echo 'success';
}
The problem is that you're comparing a scalar value to a mysql_result, you can see where that is happening below
if ($row['submit'] > $result2)
Instead, you need to fetch the result of $result2 and compare it, so modify it to the following
$result2=mysql_query($query);
$row2 = mysql_fetch_array($result2);
$row = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS 'submit' FROM torder where orderdate = {$current}"));
if ($row['submit'] > $row2['value_you_want_to_compare']) {
echo 'We have reached our Free-T limit';}
else {
$result=mysql_query($sql);
echo 'success';
}
Also, your code is vulnerable to SQL Injection, to fix that, stop using mysql_* functions as they're deprecated and start using mysqli or PDO with prepared statements
$tbl2_name="tblfree";
$query="SELECT amount FROM tblfree where id=1";
$result2=mysql_fetch_array(mysql_query($query));
$row = mysql_fetch_array(mysql_query("SELECT COUNT(*) AS submit FROM torder where orderdate = CURDATE()"));
if ($row ['submit'] >= $result2['amount']) {
echo 'We have reached our Free-T limit';
echo $result2['amount'];}
else {
$tbl_name="torder";
$sql="INSERT INTO $tbl_name
(name,address,contact,email,orderdate)VALUES('$name','$address','$contact','$email',CURDATE())";
$result=mysql_query($sql);
$sql="INSERT INTO $tbl_name (name,address,contact,email,orderdate)VALUES('$name','$address','$contact','$email','$orderdate')";
echo 'success';
}

MySQLI and Select 1

When getting data from the databas my if statement isn't working as expected, even though I have the $badgename in the database for that user I got "You get a new badge". But it dosen't put it on.
Im new to MySQLI so it's probably something I missed...
$numberofposts=$row['posts'];
$userid = $_SESSION['userid'];
$badgename = "Legend";
if($numberofposts >= 10){
$SQL = $mysqli->query("SELECT 1 FROM `badges` WHERE `mid`='$userid' AND 'badge' = '$badgename'");
$num = $SQL->num_rows;
if($num > 0){
echo "You got a new badge";
$mysqli->query("INSERT INTO badges ('mid', 'badge') VALUES ('$userid', '$badgename')");
}
else
{
echo "You already have this badge";
}
Thanks.
YOu have typo's in both queries:
replace the single quotes( ' ) on badge with backticks( ` )
from your select query.
then replace the single quotes with backticks in the insert query. ex:
$numberofposts=$row['posts'];
$userid = $_SESSION['userid'];
$badgename = "Legend";
if($numberofposts >= 10){
$SQL = $mysqli->query("SELECT 1 FROM `badges` WHERE `mid`='$userid' AND `badge` = '$badgename'");
$num = $SQL->num_rows;
if($num > 0){
echo "You got a new badge";
$mysqli->query("INSERT INTO `badges` (`mid`, `badge`) VALUES ('$userid', '$badgename')");
}
else
{
echo "You already have this badge";
}
Your INSERT query is wrong.
You have single-quotes around your column names, but you should be using backticks instead (like in the SELECT query)

Update value only if Null php/mysql

Thanks for checking out my question. I am trying to only update a value in my database if that field is null (so existing users won't be overwritten if someone tries to signup for a spot that is all ready taken and an error message will be output). I have listed below 2 of the most recent scripts I have tried. The first script works for updating the database if the select statement is not there but will overwrite users if entered for the same day and time. Thanks everybody!
$sql = ("SELECT `player1` FROM `users` where id = '$id' and Times = '$time'");
$result = $conn->query($sql);
if ($result->fetch_assoc === NULL) {
$update_player = ("UPDATE users SET player1 = '$name' where id = '$id' AND Times = '$time'")
if($update_player){
echo "Date for $name inserted successfully!";
}
}
else {
echo 'That spot is all ready taken!';
}
//2nd script
$query=mysql_query("UPDATE users SET
player1 = isNULL (player1, $name)
where id = '$id' AND Times = '$time'" );
if($query){
echo "Data for $name inserted successfully!";
}
else {
echo 'That spot is all ready taken!';
}
The following code should do the trick:
$query=mysql_query("UPDATE users SET
player1='$name'
where id = '$id' AND Times = '$time' AND player1 IS NULL" );
if(mysql_affected_rows() == 1){
echo "Data for $name inserted successfully!";
}
else {
echo 'That spot is all ready taken!';
}
Note that you should use pdo or mysqli functions instead.
Try This.
while($row = $result->fetch_assoc) {
if($row['player1'] == NULL){
$update_player = ("UPDATE users SET player1 = '$name' where id = '$id' AND Times = '$time'")
}

Categories