PDO creating database and tables - php

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

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.

How to create two query mysql insert and create table

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

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.

How to connect to a new database using PHP MySQL

So I've been trying to learn how to use MySQL with PHP, and I've managed to create a connection and create a database along with a table. What I don't know how to do is create the database along with the tables all in one go.
What I mean by this is easier shown in my code (Which will show unable to connect error message because the connect method is trying to connect to a database that does not exist.
<?php
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
// sql to create table
$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
if (mysqli_query($conn, $sql)) {
echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
mysqli_close($conn);
?>
So, all I am trying to achieve is Connect to MySQL, create the database, create a table for said database and close the connection all within one .php file.
On a side note, due to the user being able to define a database name ($dbname), how would I add this value into the MySQL code above? I heard somewhere that you're supposed to add the variable into quotes? So '$dbname'. Any help with that would be good too! Thanks in advance!
Okay, the reason for this question is because I am creating a setup-type page where the user will be able to connect to their own database, allowing them to give it a name and connect using their credentials. Obviously I am not very experienced within this field, I hope I have explained it better.
All the code you have looks fine to me. The only thing I think your missing is after you create a database you have to call
$conn->select_db("myDB");
Also if you want to have the database name be $dbname then
$sql = "CREATE DATABASE myDB";
should be
$sql = "CREATE DATABASE " . $dbname;
If I didn't cover your problem please give me more detail on your problem.
where you passing all of this variable ?
$servername = isset($_POST["servername"]) ? $_POST["servername"] : '';
$username = $_POST["username"];
$password = $_POST["password"];
$dbname = $_POST["dbname"];
just simply hardcode the servername, username, password and your dbname.

Categories