www139 www139 - 1 year ago 66
MySQL Question

how to name a mysql database after user input

I would like to know how to make a text box for the user to type and then create a database named after this input.

code to connect and make a mysql database named after the user input


<form action=<?php $_SERVER['PHP_SELF']; ?>>
<input type="text" name="databasename">
<input type="submit" name="submit">

Answer Source

You absolutely have to make sure the user's input is useable and not a hacking attempt or a mistake. So, first you check the input, and then if it's okay, you create a database.

This is assuming you add action="post" in the form. I don't like putting inputs into "get" because then your variable's part of the URL, and some people might try to set bookmarks with it there.

if(isset($_POST['databasename'])) {  //this lets us know the form has posted
   // 1. Check for acceptable name
   $name = $_POST['databasename'];
   $name = strtolower($name);       //all lowercase (makes things easier to deal with)
   $name = preg_replace("/[^a-z]/", '', $name);  //get rid of things that aren't letters

   if($name != '') {
       // 2. Create the database
       $mysqli = new mysqli('localhost', 'my_user', 'my_password');

       if ($mysqli->connect_error) {
           throw new Exception("Connect Error ($mysqli->connect_errno) $mysqli->connect_error");
       $query = "CREATE DATABASE `$name`";
       if($mysqli->errno) {
           throw new Exception("Error creating database: $mysqli->error");
           // I am pretty sure this is enough to catch the error of the database already existing
       echo "Database $name created.";
    } else {
       throw new Exception("Invalid name");

If I were you, I would put this in a try-catch to catch the exceptions and handle them.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download