简体   繁体   中英

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 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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM