0

I am trying to create a MySQL Database using PHP by using the tutorial on W3Schools: https://www.w3schools.com/mysql/mysql_create_db.asp

However when I try to use this code to make a MySQL Database with the name of a variable I start having trouble. The variable is set via a cookie called Code, which is the users id on my site.

I have tried many different variations but nothing seems to work.

$code = $_COOKIE["Code"];

$servername = "localhost";
$username = "The Username Of My Database";
$password = "The Password Of My Database";

// 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 '$code'";
if ($conn->query($sql) === TRUE) {
    echo "Database created successfully";
} else {
    echo "Error creating database: " . $conn->error;
}

$conn->close();

The error I keep getting is:

Error creating database: 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 ''102159844'' at line 1

If you don't know what the number 10215988 is it's just the users ID.

I have tried many variations for the create line however they always bring up a similar error.

$sql = "CREATE DATABASE '$code'";
$sql = "CREATE DATABASE . $code";
$sql = "CREATE DATABASE " . $code;

If I tell it to echo $sql it outputs this:

CREATE DATABASE '102159844'

Thanks in advance for any help.

Crann Moroney
  • 356
  • 2
  • 4
  • 13
  • 2
    For debugging purposes, you should print $sql, to actually see what's in there. Also, please be aware of SQL injections, right now, this is terrible in terms of security. – infinitezero May 08 '21 at 15:14
  • 1
    @MagnusEriksson MariaDB documentation says that they can be, but only if properly quoted: https://mariadb.com/kb/en/identifier-names/. So it should be something like: `CREATE DATABASE (backtick)102159844(backtick)`. – Zoli Szabó May 08 '21 at 15:24
  • @ZoliSzabó - I stand corrected. I was sure I've heard that you can't, but I guess I remember it wrong :-) Thanks for the clarification. – M. Eriksson May 08 '21 at 15:32
  • 1
    @MagnusEriksson Never tried it myself and I would have said numeric only not possible too :) But it seems that documentation says otherwise. – Zoli Szabó May 08 '21 at 15:33
  • using single quote ' is not the right quote, so you would change it to be the backtick ` – Ahmed Ibrahim May 08 '21 at 16:02

0 Answers0