How to create a table and insert data into it? - php

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();

Related

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 not creating database

Struggling now for a day. Need to make a database in PHP (if not existing) and after make sure it is empty (if already was existing). But somehow I probably miss something essential and nothing happens. Looks like it just skips the creation and the delete part altogether.
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//Database variables
$servername = "localhost";
$username = "Somename";
$password = "Verysecret";
$dbname = "TESTDB";
$temptable = "tablename";
//Open database
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to database: ",$dbname,"<br>" ;
?><br><?php
//Create table if not existing yet (syntax error here?)
echo "Creating table if non existing","<br>";
$conn->select_db('$dbname');
$sql = "CREATE TABLE IF NON EXIST `{$temptable}` (
`xml_date` datetime,
`xml_duration` int(2),
`xml_boat` VARCHAR(30),
`xml_itinerary` VARCHAR(30),
`xml_dep_arr` VARCHAR(30),
`xml_spaces` INT(2),
`xml_rate_eur` decimal(4,2),
`xml_rate_gbp` decimal(4,2),
`xml_rate_usd` decimal(4,2))";
//This part not showing up in output at all!
if(mysqli_query($conn, $sql)){
echo "Table created successfully";
} else {
echo "Table is not created successfully ";
}
//Deleting rows if table existed already (same syntax error here?)
echo "Making sure table is empty","<br>";
$sql = "DELETE * FROM `{$temptable}`";
mysqli_close($conn);
?>
All I see when I run (Localy with Mamp)is:
Connected successfully to
database: TESTDB
Creating table if non existing Making sure table is empty
The Database is not created, when I create it myself in SequelPro before and add some rows.
Help, searching now a day! What am I doing wrong? Lost in quotes, back quotes, double quotes? Overseeing the obvious?
Let's iterate over what you used here.
DELETE *, is invalid since the asterisk is used for SELECT and not DELETE.
The basic syntax is DELETE FROM TABLE WHERE col_x = ? (with optional WHERE clause).
Example:
DELETE [LOW_PRIORITY] [QUICK] [IGNORE] FROM tbl_name
[PARTITION (partition_name [, partition_name] ...)]
[WHERE where_condition]
[ORDER BY ...]
[LIMIT row_count]
https://dev.mysql.com/doc/refman/5.7/en/delete.html
Your table creation syntax is incorrect, the basic syntax is:
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
(create_definition,...)
[table_options]
[partition_options]
as per the documentation.
https://dev.mysql.com/doc/refman/5.7/en/create-table.html
which uses the keywords IF NOT EXISTS and not your IF NON EXIST.
You also didn't execute the DELETE query.
http://php.net/manual/en/mysqli.query.php
and check for errors on it also:
http://php.net/mysqli_error
Plus, as Chris was so nice to point out in comments; variables don't get parsed in single quotes.
Either remove them from $conn->select_db('$dbname'); as in either
$conn->select_db($dbname);
or set in double quotes:
$conn->select_db("$dbname");
Edit:
If the goal here is to get rid of the table entirely (after and seeing your DELETE query), then both DELETE and TRUNCATE are not what you want to use here, but DROP TABLE.
Consult the documentation:
https://dev.mysql.com/doc/refman/5.7/en/drop-table.html
Basic example:
DROP [TEMPORARY] TABLE [IF EXISTS]
tbl_name [, tbl_name] ...
[RESTRICT | CASCADE]
Try this , i got the table created
<?php
error_reporting(E_ALL); ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
//Database variables
$servername = "localhost";
$username = "detecttn_user";
$password = "Azer12345";
$dbname = "detecttn_teststack";
$temptable = "test ";
//Open database
$conn = new mysqli($servername, $username, $password,$dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully to database: $dbname <br>" ;
?><br><?php
//Create table if not existing yet (syntax error here?)
echo "Creating table if non existing","<br>";
$sql ="SHOW TABLES LIKE '$temptable'";
if(mysqli_query($conn, $sql)){
echo "Table exist";
} else {
echo "Table does not exist";
// if table not exist create it
$sql = "CREATE TABLE IF NOT EXISTS $temptable (
`xml_date` datetime,
`xml_duration` int(2),
`xml_boat` VARCHAR(30),
`xml_itinerary` VARCHAR(30),
`xml_dep_arr` VARCHAR(30),
`xml_spaces` INT(2),
`xml_rate_eur` decimal(4,2),
`xml_rate_gbp` decimal(4,2),
`xml_rate_usd` decimal(4,2))";
mysqli_query($conn, $sql);
$sql ="SHOW TABLES LIKE '$temptable'";
if(mysqli_query($conn, $sql)){
echo "Table created";
} else {
echo "Table creation failed";
}
}
//Deleting rows if table existed already (same syntax error here?)
echo "Making sure table is empty","<br>";
$sql2 = "TRUNCATE TABLE $temptable";
if(mysqli_query($conn, $sql2)){
echo "Table is empty";
} else {
echo "Error";
}
mysqli_close($conn);
?>

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