I have two tables in my database namely reservations and guests. The rows are as follow:
Reservation:
Reservation id
Property Id
Checkin date
Checkout date
Price
Guest
Guest id
Reservation id
Guest name
Guest address
Using a form that contains the reservation details and the guest details at the same time.
How can I run the insert query so that the auto generated reservation id(auto-increment in database) can also be inserted into the guest table at the same time?
This is what I have so far. I changed my code using last_insert_id()
INSERT INTO reservations
SET Checkin date= '24/05/2018', checkout date = '29/05/2018';
INSERT INTO guests
SET reservation id = LAST_INSERT_ID(),
guest name = guest name
First insert to reservation table
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sqlR = "INSERT INTO Reservation(firstname, lastname, email)
VALUES ('John', 'Doe', 'john#example.com')";
$rStatus = $conn->query($sqlR);
$res_id = $conn->insert_id;
$sql = "INSERT INTO MyGuests (firstname, lastname, email,res_id)
VALUES ('John', 'Doe', 'john#example.com',$res_id)";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id;
echo "New record created successfully. Last inserted ID is: " . $last_id;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
Firstly you can insert the data into the Reservation table, based on the last inserted id, you can use the value for the column Reservation id for the table Guest. Also, please maintain foreign key constraints, so as on update and delete operations of Reservation, simultaneous operations are performed on the Guest table.
To get the last inserted id,
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO ...";
if ($conn->query($sql) === TRUE) {
$last_id = $conn->insert_id; //gives the last inserted id
}
Run the insert query first with the insert_id function and then use that insert_id to run the second insert query
Related
How should i solve this? there is not a row 1 and i cant insert or update data. Unique keys are indeed ip and uid in my table.
My code is as follows:
//Retrive listeners per reload
echo 'Data Höganäs <br>';
$sc="http://USER:PWD#SUB.SERVER.se:10000/admin.cgi?sid=1&mode=viewxml&page=3";
$xml2 = simplexml_load_file($sc);
foreach ($xml2->LISTENERS->LISTENER as $listener2) {
// Create connection
$conn = new mysqli($host, $user, $pwd, $db);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = " insert INTO hoganaskey
(ip, uid, tid, starttid, date)
VALUES
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')
on duplicate key
update tid='$listener2->CONNECTTIME' ";
//$sql = "INSERT INTO hoganaskey (ip, uid, tid, ua, starttid, date) VALUES('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT' '$starttid', '$date') ON DUPLICATE KEY UPDATE tid='$listener2->CONNECTTIME' ";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
} //End foreach SHOUcast listener
Im returning this error in insert "Column count doesn't match value count at row 1".
In your insert query, you listed only 5 field names:
(ip, uid, tid, starttid, date)
but you are passing 6 values not 5:
('$listener2->HOSTNAME', '$listener2->UID', '$listener2->CONNECTTIME', '$listener2->USERAGENT', '$starttid', '$date')
I've recently setup up a MySQL server and an Apache webserver to test my Mysql Database. But there is a problem. PHP won't update the MySql server, or the MySQL server will not update.
I've even gone back and copied and pasted from W3Schools and this seems to do nothing what so ever. What am I doing wrong?
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "password";
$dbname = "form_acceptance";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE MyGuests SET Player_name='Doe' WHERE id=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
MySql
CREATE DATABASE form_acceptance;
CREATE TABLE form_acceptance (
PersonID int,
Player_Name varchar(255),
Countries varchar(255),
Username varchar(255),
Level_and_rank varchar(255),
Max_BR varchar(255)
);
INSERT INTO form_acceptance (PersonID, Player_Name, Countries, Username, Level_and_rank, Max_BR)
SELECT 'SayByeBye_exe', 'SayByeBye_exe', 'US', '^GYMP^SayByeBye_exe', '12_Luitenant', '4.7';
select * FROM form_exceptance;
Nothing seems to work. PHP will not update data into MySql. Why not?
Is it maybe because I am using Linux? Or not?
For the query to execute make sure you have at least 2 records in the table
$sql = "UPDATE MyGuests SET Player_name='Doe' WHERE id=2";
if there is no id with value 2 then the query fails so make sure you check that, I don't see anything else wrong except the typing error at last line
There is couple error you are having with your setup. You do not have any MyGuests table so I assume you want to update the form_acceptance table. Then the form_acceptance table doesn't have any id column so either we have to add this or use the PersonID column. Here is the code snippet to fix your issues.
First
Please update your MySQL table creation like this. This will make PersonID as a primary auto incremental column.
CREATE DATABASE form_acceptance;
CREATE TABLE form_acceptance (
PersonID int NOT NULL AUTO_INCREMENT, //Notice we added NOT NULL AUTO_INCREMENT
Player_Name varchar(255),
Countries varchar(255),
Username varchar(255),
Level_and_rank varchar(255),
Max_BR varchar(255),
PRIMARY KEY (`PersonID `)//define PersonId as primary key
);
Second
Insert a few records
INSERT INTO form_acceptance (Player_Name, Countries, Username, Level_and_rank, Max_BR)
Values('Player_Name1', 'US', 'Username`', '12_Luitenant', '4.7'),
('Player_Name2', 'US', 'Username2', '12_Luitenant', '4.7');
select * FROM form_acceptance;//Will show you 2 records having PersonID 1 and 2
Now fix your update query
<?php
$servername = "127.0.0.1";
$username = "root";
$password = "password";
$dbname = "form_acceptance";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "UPDATE form_acceptance SET Player_name='Doe' WHERE PersonID=2";
if (mysqli_query($conn, $sql)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
This will successfully update the record of the second row where PersonID is 2.
So I've been trying to figure out how to do this but I've had no luck.
I have a database that includes ID, name, date, and username
I have a simple submit form that generates an id and a user adds a name and an event date then it logs the username, However I would like to take that date and then have it appear in a select tag with the format of Name - Date and have it sorted by the closest date. I want to view info about that event when someone clicks it. But I can't figure out how to make it appear in the select tag. I don't even know where to start with this. all help appreciated.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = uniqid(rand(), false);
$name=$_POST['name'];
$date=$_POST['date'];
$username = $_POST['username'];
// Insert data into database
$sql="INSERT INTO events (id, name, date, username)
VALUES
('$id', '$name', '$date', '$username')";
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
error_log(implode("-",$_POST));
$conn->close();
?>
I would like to create two queries, one to enter the data into one table, another to create a new table. This is my code that creates the new table but does not insert the data. Where am I wrong? Thank you.
$sql = "INSERT INTO progetti(data, ora, nome_progetto)VALUES('".$_POST["data"]."','".$_POST["ora"]."','".$_POST["nome_progetto"]."')";
"CREATE TABLE $_POST[nome_progetto] (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
data date,
intervento varchar(30),
descrizione varchar(70),
ore int(2)
)";
Here you can create if else statement , if insertion is done then creation will run
<?php
/*
* These are Database Credentials
*/
$servername = "localhost";
$username = "root";
$password = " ";
$dbname = "test_db";
/*
* Intiating the Database connection
*/
$conn = new mysqli($servername, $username, $password, $dbname);
/*
* Checking the Databse connection
*/
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$create = "CREATE TABLE ".$_POST[nome_progetto]." (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
data date,
intervento varchar(30),
descrizione varchar(70),
ore int(2))";
$result = $conn->query($create);
if ($result === TRUE) {
$sql = "INSERT INTO progetti(data, ora, nome_progetto)VALUES('".$_POST["data"]."','".$_POST["ora"]."','".$_POST["nome_progetto"]."')";
$insert = $conn->query($sql);
if ($insert === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
Use different SQL statement ( in your case 2, one for insert and other one for create table )
use prepare statements provided by Abstraction Layers ( PDO ) in PHP
read about SQL Injection
I have a database with three columns: ID, userName, feedback
I want the feedback value to be updated when the userName is same.
my php code:
<?php
conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$value = $_POST['name'];
$value2 = $_POST['message'];
$sql = "INSERT INTO js (userName, feedback) VALUES('$value', '$value2');
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
};
$conn->close();
?>
If you want to do it with mysql you first of should define a unique index on the userNamecolumn.
ALTER TABLE js
ADD CONSTRAINT u_userName UNIQUE (userName)
The edit your insert query like this:
INSERT INTO js (userName, feedback) VALUES ('$value', '$value2')
ON DUPLICATE KEY UPDATE feedback=VALUES(feedback);
Now if the duplicate key violation is hit by mysql, the value for feedback will be updated while inside the row where your username equals.
Or you implement a update logic inside php and detect if there already is an entry inside the table with the same username.