How to connect to a new database using PHP MySQL - php

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.

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 can I get mysql to print rows from a database table

I am trying to learn php from W3schools which includes a mysql section.So far I have completed every other part of the tutorial on w3school except the part that prints content from a database table. For some very weird reason , nothing displays when I run my code. Please how can I get this working and could my problem come from the fact that I am using MariaDB with Xampp instead of Mysql although they said it was practically the same syntax.
Here is the code
<?php
$servername = "localhost";
$username = "uhexos";
$password = "strongpassword";
$database = "fruitdb";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE fruitDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}
$conn->close();
// Create connection
$conn = mysqli_connect($servername, $username, $password,$database);
// sql to create table
$complexquery = "CREATE TABLE MyFruits (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
FruitType VARCHAR(30) NOT NULL,
FruitTaste VARCHAR(30) NOT NULL,
FruitQuantity INT NOT NULL,
DatePurchased TIMESTAMP
)";
if ($conn->query($complexquery) === TRUE) {
echo "Table Fruits created successfully<br> ";
} else {
echo "Error creating table: " . $conn->error;
}
$entry = "INSERT INTO myfruits (fruittype,fruittaste,fruitquantity) VALUES ('orange','sweet','50'),('lemon','sour','10'),('banana','sweet','15')";
if ($conn->query($entry) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $conn->error;
}
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['id']} <br> ".
"EMP NAME : {$row['fruitname']} <br> ".
"EMP SALARY : {$row['fruittaste']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
this is the output I get from all my echos.
Error creating database: Can't create database 'fruitdb'; database existsError creating table: Table 'myfruits' already existsNew records created successfully
or
Database created successfullyTable Fruits created successfully
New records created successfully
Based on the error message, you managed to create the database and tables once and now each time you run the code it fails because you can't reuse the names.
You definitely don't want to have code trying to erase & start fresh on your database every time. In fact, most often I find that you don't even create the database inside your regular code but use phpMyAdmin or some other admin page to do that. But creating tables inside code is normal enough. Two options:
1 - Create the table only if it does not already exist. This is extremely safe. However, if you want to start a table over again with a new structure, or start with it always empty, that won't work. To do that, just change CREATE TABLE to CREATE TABLE IF NOT EXISTS
2 - Delete the table before creating it. Before each CREATE TABLE command, add a command like DELETE TABLE IF EXISTS MyFruits
Remember database name is Case-insensitive, so it doesn't matter whether you create a DB name "fruitdb" or "fruitDb" both are same.That is the reason you are getting error. Also you don't have to create a new database when you execute any file. If you have already created the database than you only have make the connection with it.
Let's debug your code line by line.
Line 8 -
// Create connection
$conn = new mysqli($servername, $username, $password);
Here you are creating the connection with your database because you have already created that database. If you check your phpmyadmin, you'll find a database named "fruitdb"
Line 10 -
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
Here your checking whether the you are able to connect with your database. If not it will throw the error and your script will stop. Right now your code successfully runs till this point.
Line 15 -
// Create database
$sql = "CREATE DATABASE fruitDB";
Here you are again creating a database with same name and your code stops working as you already have it.
The error was from this line
$sql = 'SELECT id, fruitname, fruittaste FROM myfruits';
I accidentally put fruitname instead of fruittype and that is what caused it to fail. So for anyone else with thi problem my advice is to check your variable names if you are 100% sure of your syntax. Thanks for all the help.

How to create a table in MySQL using PHP?

I want to create a table in a MySQL Database with PHP. This is my try:
$dbhost = 'rdbms.strato.de';
$dbusername = 'Userxxx';
$dbuserpass = 'Passwordxxx';
$dbname = 'DBxxx';
$link_id = mysql_connect ($dbhost, $dbusername, $dbuserpass);
echo "success in database connection.";
if (!mysql_select_db($dbname)) die(mysql_error());
echo "success in database selection.";
$result = "CREATE TABLE address_book (first_name VARCHAR(25), last_name VARCHAR(25), phone_number VARCHAR(15))";
if (mysql_query($result)){
echo "TABLE created.";
}
else {
echo "Error in CREATE TABLE.";
}
But this give me the error
success in database connection.Access denied for user XXX to database XXX
I search a lot but find no successfull solution. Have anyone an idea?
Try connecting without involving PHP:
mysql -u Userxxx -h rdbms.strato.de -pPasswordxxx
If this doesn't work, and I suspect it won't, contact your database administrator to reset your password.
If the password isn't the problem, the remote machine may not be ready to accept your connection. See Access remote database from command line for more on this.
If you can get in, then try to access the database you want:
USE DBxxx;
SHOW TABLES;
Thing is, PHP isn't your problem here; it's the connection. So that's what to investigate.
...and when you get that established, you might look into updating your code; mysql_connect and mysql_select_db are deprecated.
I need some clarification about your hostname,username,password,database name.How ever following code will works in my local server.If you have any doubt about my code please share your host name,password,dbname,etc.
$dbhost = 'localhost';
$dbusername = 'root';
$dbuserpass = '';
$dbname = 'test';
$link_id = mysqli_connect ($dbhost, $dbusername, $dbuserpass,$dbname);
echo "success in database connection.";
$result = "CREATE TABLE address_book (first_name VARCHAR(25), last_name VARCHAR(25), phone_number VARCHAR(15))";
if (mysqli_query($link_id,$result)){
echo "TABLE created.";
}
else {
echo "Error in CREATE TABLE.";
}

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 prevent inserting duplicate records?

I want to make my PHP check if something with the same specific data already exists in my database table.
I have a database called test with a table called users.
This is where I would like to check if a row steamid already exists with the same $steamid number.
<?php
// Datebase infomation
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$steamid = $steamprofile['steamid'];
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create data
$sql = "INSERT INTO users (steamid)
VALUES ('$steamid')";
if (!$conn->query($sql) === TRUE) {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
you need to add a PRIMARY KEY or a UNIQUE constraint on the steamid column.
after deleting all the duplicates, then you can run this command:
ALTER TABLE users ADD PRIMARY KEY(steamid)
then your query will fail if you attempt to insert a duplicate steamid into the users table.
as #Jeremy mentioned, you can use REPLACE, but this also only works if you have a PRIMARY KEY or UNIQUE constraint on the column. this is the preferred method if you have additional columns aside from the steamid that you want to store in the database table because it will update those values. however, since your query as stated in the question INSERT INTO users (steamid) VALUES ('$steamid') only contains the one field, then it's not of much consequence unless you want to catch the conditional error of an attempted duplicate record, in which case you should stick to the INSERT statement.

Categories