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.
Related
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();
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
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);
?>
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.
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.