PHP & MYSQL -- dont insert same data - php

I need your help. I’m stuck at a point from where I can’t figure it out that how to stop a product to be booked twice a day on a web form.
I have 41 products to rent out on daily basis.
My problem is: if a client books a product #4 (pg_no) and date 26-06-2017 then another client isn't able to book the same product for the same period of time.
If a client selects the same product and date, then a message should appear saying "already booked - please select another date"
Also, do I have to define anything on database level?
Your help will be highly appreciated.
Please note: this rule is only for product # (pg_no) and date fields are not allow for the same day.
<?php
//connecting string
include("dbconnect.php");
//assigning
$pg_no=$_REQUEST['pg_no'];
$name=$_REQUEST['Name'];
$tele=$_REQUEST['Tele'];
$city=$_REQUEST['City'];
$date=$_REQUEST['Date'];
//checking if pg_no and Date are same
$check=mysqli_query($db_connect,"SELECT * FROM lstclient WHERE pg_no='{$pg_no}', Date='{$date}'");
if(mysqli_fetch_row($check) ==0)
{
echo "Already booked please select another date<br/>";
}
//if not the insert data
else
{
$query=mysqli_query($db_connect,"INSERT INTO lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}
mysqli_close($db_connect);
// messaging
if($query)
{
header("location:index.php?note=failed");
}
else
{
header("location:index.php?note=success");
}
?>

Create a UNIQUE KEY constraint on your table between the two columns.
ALTER TABLE lstclient ADD CONSTRAINT `pg_no_date` UNIQUE (pg_no, date)
Then when you try to insert a row that violates this constraint mysql will throw an error. You should catch this MySQL error and respond with the correct error.
if( mysqli_errno() == 1062) {
// Duplicate key error
}

Add a unique key to your lstclient table like ryan suggested. Also, your check query has syntax error, it should be like below.
SELECT * FROM lstclient WHERE pg_no='{$pg_no}' AND Date='{$date}'

Related

Add a new file to a database with foreign key error in PHP

I've been recently working on my course work and stuck with the problem.
The case is this:
User makes a request of an art work from the website HTML, input data such as UserID for who the art must be made is needed to include into SQL table, but it gives an error that I can't modify a foreign key that it takes from session data
This is the error it displays and the code itself
errorCannot add or update a child row: a foreign key constraint fails (project work.arts,
CONSTRAINT arts_ibfk_1FOREIGN KEY (For_UserID) REFERENCESusers(UserID`))
<?php
session_start();
$genre=$_POST['genre'];
$ext=$_POST['ext'];
$desc=$_POST['desc'];
$conn= new mysqli("127.0.0.1", "root", "","project work") or die ("Can't connect to db");
if (($genre!="") and ($ext!="") and ($desc!="")) {
$query= "INSERT INTO `Arts` (`Genre`,`Extension`,`Description`,`For_UserID`,`Is_Done`)
VALUES ('$genre','$ext','$desc','{$_SESSION['UserID']}','0')";
if ($conn->query($query)== TRUE)
echo "Succesfully!" ;
else die('error' .$conn->error);
}
else echo "Fill all the fields, please!";
?>
Is there a way to avoid this error?
This error only means that the For_UserID entered as an input is not a valid (existing) UserID of your table 'users'.
For instance, if there are 3 users in your table 'users' with respective ids 1,2,3, and you try to enter id 4 for who the art must be made, it will throw this error, because your table 'arts_ibfk_1' has a foreign key related to this table 'users'.

PHP MYSQL Attendance Limit Once a Day

I am Beginner in php and i am making the project on attendance system but i don't know how to code for single-day attendance for the student once in a day. I didn't get the appropriate result.
Thanks in advance.
<?php
include 'config.php';
if($_SESSION['user']==true){
if(isset($_POST['submit'])){
$sql= ("INSERT INTO `student_attendence`(`Student_id`,`Date`,`Attendence`) VALUES ('".$_SESSION['user']."','$date','$attendence') ");
if(count($error)==0){
if(!mysqli_query($conn,$sql)){
echo "Error ".mysqli_error($conn);
}
else{
header("location:studentlogin.php");
}
}
}
}
else{
header("location:studentlogin.php");
}
?>
You have to increase one more attribute in DB table which is date.
So whenever you insert a new attendence insert today's date also.
Always check for today's date must not present in DB before inserting the attendence.
So while inserting the attendence in DB, you must have to check first -
If today's date is already present in DB
true : display message(today's attendence has already taken).
false: save the attendence in DB.
Note -
MySQL's default DATE format is YYYY-MM-DD.
This is the quick method you can impliment.

UPDATE specific fields in mysql php

I've a table in MySQL named product where fields are set as below..
id int(3) NOT NULL AUTO_INCREMENT,
nm varchar(255),
category varchar(255),
price int(4)
when i insert a new product then I've put some code to check duplication as below.
select nm,category from product where nm='".$pnm."' AND category='".$cat."'
If there is any row then code will not insert that record in database...(problem starts now)
same condition I've set during update..
if user edit that product and change name or category which is already in database then it'll return false and exit the code..
now if i want to just update price then name and category will be same then what to do???
please give your best ! !
Thank you friends
You can do it by using unique id..First check for duplication while updating and if duplication occurs then only update other fields except name and category else update all the fields which are going to be changed.
I give you demo.Make changes according to your requirement like field name,table name and all that.
$sql="select * from product where nm='".$_REQUEST['name']."'" or category='".$_REQUEST['category']."';
$query=mysql_query($sql);
if(mysql_num_rows($query)>0)
{
while($row=mysql_fetch_array($query))
{
$id=$row['id'];
if(isset($_REQUEST['price']))
{
$sql="update product set price='".$_REQUEST['price']."' where id='$id'";
$query=mysql_query($sql);
}
}
}
else
{
$sql="update product set nm='".$_REQUEST['name']."',category='".$_REQUEST['category']."',price='".$_REQUEST['price']."' where id='$id'";
$query=mysql_query($sql);
}
Two step solution:
- Create a UNIQUE index
- Use INSERT IGNORE and UPDATE IGNORE instead of INSERT and UPDATE

Stopping Duplicates in two fields in the same row in a SQL Database

I'm creating a sign up sheet system for my website. Each sign up sheet is given an ID number. When a user signs up it sends the username and the ID number to a database. However I want to stop duplicate entries so that the same user can only sign up to an event once. I can't use a WHERE statement in the SQL query and I was just wondering what the best way to tackle this would be. I can't use primary or unique keys as then they can only sign up for one event, or only one event can be signed up for. Thanks in advance.
This is the code for the page
<?php
session_start();
$user = $_POST['username'];
$id = $_POST['id'];
if(empty($user) == FALSE )
{
$con=mysqli_connect("localhost","emuas","flgdls","EMUAS_signUp");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql="INSERT INTO SIGN_UP_TEST (EventID, User, Comments)
VALUES
('$_POST[id]','$_SESSION[username]','$_POST[comments]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
header("Location: {$_SERVER['HTTP_REFERER']}");
}
else
{
header("Location: {$_SERVER['HTTP_REFERER']}");
}
?>
You can add this UNIQUE key. It'll make it so a user can only sign up for each event once.
alter table SIGN_UP_TEST add unique index(EventID, User);
If you use a composite primary key (id and user), then a user can sign up for multiple events, but not the same event twice.
primary key (id, user)

Recording data on DB table

Is it possible to have a table and insert data n a single row on two different occasion? I mean, I have a table with five column and on first data submission, i want to record data on only just two field on that table, and in different data submission on that same row, I would want to record data on those 3 remaining column that haven't been recorded with any data. What method should i use? INSERT or UPDATE? Or neither?
Sorry for my bad english and confusing way of asking question.
Code:
$query = ("SELECT q1 FROM grades where studentnumber = '$_POST[studentnumber]' && subjectcode = '$_POST[subjectcode]' ");
$result=mysql_query($query);
if($result)
{
if(mysql_num_rows($result) ==1)
{
$sql=mysql_query("UPDATE grades SET q1 = '$_POST[q1]' where studentnumber = '$_POST[studentnumber]' AND subjectcode = '$_POST[subjectcode]'");
if($sql)
{
echo "<script type='text/javascript'>alert('Password successfully changed'); location.href = 'cvsu-sis_grades.php';</script>";
}
}
}
else
{
echo "<script type='text/javascript'>alert('Record Does not Exist'); location.href = 'cvsu-sis_grades.php';</script>";
}
i omitted some columns just to make the coed shorter but most likely it is the same. just a series of q1, q2, ...
The first query should be an INSERT, then you can get the last inserted id and do an UPDATE query
You can use INSERT for first two columns, and get your inserted id using mysql_insert_id() (only if your primary key column name is "id") and using this you can update your remaining three columns using UPDATE
First of all you have to make sure, that when you insert the 2 fields on your first INSERT, the fields you leave empty are allowed to be NULL!
You have to INSERTthe first data into the table and later on, when you want to add the remaining fields, you have to UPDATE that row. Make sure that, when you UPDATE, you are using a WHERE-constraint (e.g. with the 2 fields already entered), otherwise all rows will be updated!

Categories