How to create two query mysql insert and create table - php

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

Related

How to create a table and insert data into it?

What I'm trying to do is in the $sql this is where I'm going to code the SQL commands
$connect = new mysqli($servername, $username, $password, $database);
if ($connect -> connect_error) {
die("Unable to Connect : " . connect_error);
}
$sql = /*"CREATE TABLE student (
student_id INT,
name VARCHAR(20),
major VARCHAR(20),
PRIMARY KEY(student_id)
); */
"INSERT INTO student VALUE(3, 'joseph', 'education');";
if ($connect -> query($sql) === TRUE) {
echo "New Table Created! <br><br>";
}
else {
echo "Error : " . $sql . " <br><br>" . $connect -> error . "<br><br>";
}
echo "Connected Successfully!";
This is the output when I removed the create table. The inserted data is successful
New Table Created!
Connected Successfully!
This the output when I did not removed the CREATE TABLE
Error : CREATE TABLE student ( student_id INT, name VARCHAR(20), major VARCHAR(20), PRIMARY KEY(student_id) ); INSERT INTO student VALUE(3, 'joseph', 'education');
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'INSERT INTO student VALUE(3, 'joseph', 'education')' at line 8
Connected Successfully!
What function do I need to use to put in the $sql the SQL commands like this? Is it even possible? Is this how SQL works?
$sql = "CREATE TABLE student (
student_id INT,
name VARCHAR(20),
major VARCHAR(20),
PRIMARY KEY(student_id)
);
INSERT INTO student VALUE(3, 'joseph', 'education');"
You need to do it in two steps. First, prepare a statement with the CREATE TABLE and then prepare the second statement with INSERT.
<?php
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli($servername, $username, $password, $database);
$connect->set_charset('utf8mb4'); // always set the charset
$sql = "CREATE TABLE student (
student_id INT,
name VARCHAR(20),
major VARCHAR(20),
PRIMARY KEY(student_id)
)";
$stmt = $connect->prepare($sql);
$stmt->execute();
$stmt = $connect->prepare("INSERT INTO student VALUE(3, 'joseph', 'education')");
$stmt->execute();

Why MySQL database not update when I update something in PHP?

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.

Insert into two table foreign key and primary key

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

PHP / MySQL: Create Database from User Input

I would like to create a database based on user input if that database doesn't exist. Problem is, I do not understand how to check whether the database exists or not.
Also another question is I wonder if the following code would work:
if (isset($_POST['companyName'])) {
$companyName = $_POST['companyName'];
}
$query = "
CREATE DATABASE 'companyName';
USE 'companyName';
CREATE TABLE users (
ID int NOT NULL AUTO_INCREMENT,
FirstName varchar(255),
LastName varchar(255),
user text,
Password varchar(255),
Email varchar(255),
PRIMARY KEY (ID)
);
";
$result = mysqli_query($conn, $query);
Because basically I typed the whole SQL code in and just query it, would that create any problem?
I'm not really experienced in PHP and MySQL so thank you for paying attention and answer my question in advance!
You can try this
<?php
$servername = 'localhost';
$username = 'root';
$password = 'xxxxx';
$conn = new mysqli($servername, $username, $password);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
$conn = mysqli_connect($servername, $username, $password,'myDB');
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "CREATE TABLE users
(
ID int NOT NULL AUTO_INCREMENT,
FirstName varchar(255),
LastName varchar(255),
user text,
Password varchar(255),
Email varchar(255),
PRIMARY KEY (ID)
)";
if ($conn->query($query) === TRUE) {
echo "Table users created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
?>
My result
But I'm not recommend user can create new database in your sql server.
You should first filter out the user inputs before putting to use in mysql queries. Use htmlspecialchars(), stripslashes() functions.
Before creating a database you should check if it exists. You can do it by using : CREATE DATABASE IF NOT EXISTS yourdb;
It is not advisable to create db and tables based on user inputs, but in case you have no other option, make sure to filter the user inputs.

PDO creating database and tables

I'm currently struggling with an assignment. I am to create a PHP script that will create a database and all the tables for that database. I have been able to cobble together the script to create the database itself from reading here and W3Schools, however I am stumped as to how to have the same script create tables on that new database. Here's what I have to create a new database:
<?php
$servername = "localhost";
$username = "root";
$password = "mysql";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE IF NOT EXISTS musicDB";
$conn->exec($sql);
echo "DB created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
I tried to follow on that to then create tables with this:
<?php
$servername = "localhost";
$username = "root";
$password = "mysql";
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE IF NOT EXISTS musicDB";
$sql = "use musicDB";
$sql = "CREATE TABLE IF NOT EXISTS ARTISTS (
ID int(11) AUTO_INCREMENT PRIMARY KEY,
artistname varchar(30) NOT NULL)";
$conn->exec($sql);
echo "DB created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
$conn = null;
?>
However that is not working and I get the following error: CREATE TABLE IF NOT EXISTS ARTISTS ( ID int(11) AUTO_INCREMENT PRIMARY KEY, artistname varchar(30) NOT NULL)
SQLSTATE[3D000]: Invalid catalog name: 1046 No database selected
Basically, how do I tell the script to use the newly created table and then create tables for it? And I know the username and password are showing but this is running on my laptop and will never be anywhere so I'm not worried.
You're only executing the last statement. You keep assigning to $sql, but not executing those statements.
try {
$conn = new PDO("mysql:host=$servername", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "CREATE DATABASE IF NOT EXISTS musicDB";
$conn->exec($sql);
$sql = "use musicDB";
$conn->exec($sql);
$sql = "CREATE TABLE IF NOT EXISTS ARTISTS (
ID int(11) AUTO_INCREMENT PRIMARY KEY,
artistname varchar(30) NOT NULL)";
$conn->exec($sql);
echo "DB created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
Instead, try wrapping all these statements in a procedure and call that from your code behind like
create procedure usp_createDB
as
begin
CREATE DATABASE IF NOT EXISTS musicDB;
use musicDB;
CREATE TABLE IF NOT EXISTS ARTISTS (
ID int(11) AUTO_INCREMENT PRIMARY KEY,
artistname varchar(30) NOT NULL);
end

Categories