using php to insert records in my database - php

I am trying to insert data into my database from a user form using php
I normally do not have any issues when doing this except this time and I believe it is because of the date type as explained below
Here is the code:
<?php
session_start();
$user = $_SESSION['who'];
if (!$_SESSION['who']){
header("location: login.php");
}
if (isset($_POST['submit'])){
require_once('dbconn.php');
$flightID = $_POST["flights"];
$sql= "INSERT INTO booking (flight_id,customer_id,checkedin,checkin_datetime, booking_datetime,baggage)
VALUES ('1', '1','0','10-10-10', '10-10-10','30')";
if($recordSet = $dbConn->query($sql)) {
echo "record set";
}
else
echo "not set";
}
?>
I will be using variables instead of hard coded values for my insert statement however I am just trying to get it to work.
Here are the attributes in my database table for booking
id, flight_id, customer_id, checkedin, checkin_datetime, booking_datetime, baggage
The ID is automatic which is why it is not in my sql statement
currently my page is displaying not set I think it may be due to the date field as I am not sure which format it may use.
UPDATE: I changed the date in my sql statement and it still is not working, no errors coming up as well.

You can Use
$sql= "INSERT into booking (flight_id,customer_id,checkedin,checkin_datetime, booking_datetime,baggage)
VALUES ('1', '1','0','2020-10-10', '2020-10-10','30')";

$sql= "INSERT INTO booking (flight_id,customer_id,checkedin,checkin_datetime, booking_datetime,baggage)
VALUES ('1', '1','0','2010-10-20', '2010-10-20','30')";
Note :
date format: YYYY-MM-DD
All id must be exists in the database (if you use Foreign Key for flight_id and customer_id).

Date format looks ok in the sql statement.
make sure ID field is auto increment in the database as you have not used in the sql statement.

Related

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.

Some queries in PDO php executing and some are not

I am trying to enter a whole table in itself changing the city variable but when I create a temp table to store data the insert statement to insert data back in original statement not working. Here is the code
<?php
if(isset($_POST['btnsub'])){
$city=$_POST['city'];
$query= $conn->query("create table from_php like menuinstant;
insert into from_php select * from menuinstant where city='Kota';
update from_php set id = replace(id,'Kota','.$city.');
update from_php set city = replace(city,'Kota','.$city.');
insert into menuinstant select * from from_php;
drop table from_php
");
echo "table created";
}
?>
The insert into menuinstant is not executing even the drop query after that is also working. Help me out.
almost all database/sql wrappers will only allow exactly ONE query per call. so your $conn->query([5queries]) should be five $conn->query([1stquery]); $conn->query([2ndquery]); ...
update1:
You should/could also check for errors:
$result = $conn->query('[Your query here]');
if($result === false) {
die(print_r($conn->errorInfo(),true));
}
update2: please read up on mysql injections. for example http://php.net/manual/en/security.database.sql-injection.php

below INSERT INTO SELECT not working with user_id,qty and ord_date,how it can be done?Thanx in advance

<?php
include("config.php");
if ($_SESSION['uname']=='' || $_SESSION['uid']=='') {
header('location:login.php');
} else {
$pid=$_GET['prod_id'];
$q="INSERT INTO
cart_tbl(cat_id,com_id,prod_id,
user_id,price,qty,ord_date)
SELECT cat_id,com_id,
prod_id,'".$_SESSION['uid']."',
(prod_price-prod_discount) as price,1,
date(Y-m-d h:i:s) FROM product_tbl
WHERE prod_id='".$pid."'";
$re=mysql_query($q);
}
?>
I want to insert user_id=$SESSION['UID'],qty=1 and ord_date=date(Y-m-d h:i:s) function and other things from product_tbl. but,code above not inserting anything in cart_tbl.
The SQL query is not correct. As per the query you are inserting values by selecting from a table. In your above written query there couldn't be a field like $_SESSION or date parameter. Insert values by traditional SQL query & from other tables do it as you are doing.

Use PHP or SQL for error check

Give the following table:
CREATE TABLE User (
Email VARCHAR(256) PRIMARY KEY,
Name VARCHAR(256),
);
I am trying to insert date into the table.
To check for duplication, should I use SQL to select email from user where email = $email and check the number or rows return is 1 and if it is 1, I just use php to print error message
OR
Should I just try to insert the data into table and use the following to print error?
mysql_query('INSERT INTO ...');
if (mysql_errno() == 1062) {
print 'no way!';
}
Which is a better way?
You can go for a query like this :
$sql = "INSERT INTO `table` VALUES ('$email','$Name')"
." WHERE NOT EXISTS (SELECT * FROM `table` WHERE `email`='$email')";
mysql_query($sql) or die("There's a duplicate.");`
Generally it's better to let the DBMS do the checking, because the functionality is already there and tested. You just need to handle the error messages.
If you insist on using your own code to do the checking, be prepared for many hours of brainstorming (given the complexity of the problem solved).

Search mysql database before inserting data

I cant quite think about how to do this with mysql and php. Basically I want to be able to submit data into a mysql database but before it is inserted, it will check to see if that entry already exists.
$guid=$_POST['guid'];
$name=$_POST['name'];
//Username
$user="webhost";
//Password
$pass="*******";
//IP To Host
$ip="***********";
//Database
$db="dayz2";
//Table
$table="whitelist";
//Database Connection
$con=#mysql_connect("$ip", "$user", "$pass")
or die(mysql_error());
//Select Database
$dbcon=#mysql_select_db($db, $con)
or die(mysql_error());
$dupesql = "SELECT * FROM $table where (name = '$name' AND guid = '$guid')";
$duperaw = mysql_query($dupesql);
if (mysql_num_rows($duberaw) > 0) {
echo "Entry Already Exists";
}
else {
//Query Data Into Whitelist Table
$sql="INSERT INTO $table (name, guid) VALUES ('$name', '$guid')";
//Submit Data into Whitelist Table
$result=#mysql_query($sql, $con) or die(mysql_error());
}
?>
You can do it in another way, instead of:
submit data into a mysql database but before it is inserted, it will
check to see if that entry already exists.
You can do:
INSERT data into a mysql database if not existed, else ignore them
Something like :
INSERT IGNORE INTO table
INSERT IGNORE INTO yourtablename
SET fieldname = 'blah'
,..
It depends what you are trying to do - what is the exact criteria for your query?
You have several options:
use INSERT IGNORE ... if you only want to insert new rows that don't have a duplicate primary key. See http://dev.mysql.com/doc/refman/5.5/en/insert.html.
use INSERT ... ON DUPLICATE KEY UPDATE to insert new rows and update rows where there is a primary key match.
See http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html.
use a normal SQL SELECT ... to pull the results first before performing business logic on the results before deciding which to INSERT ... or UPDATE ... depending on your requirements.
It depends how you want to handle case when the entry exists.
I you want to throw some error then you can create table trigger for insert event and put some checks there, but it will be slow because every insert will do this check.

Categories