0

I am working on a project, and I have to use sql. The variable $file_name needs to be the table name, but when i try this:

$sqlTableCreate = "CREATE TABLE ". $file_name . "( 
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
    firstname VARCHAR(30) NOT NULL,
    lastname VARCHAR(30) NOT NULL,
    email VARCHAR(50),
    reg_date TIMESTAMP
)";

The table does not create. I checked by using this:

if ($sqlConnection->query($sqlTableCreate) === TRUE) {  
    echo 'Created Sucessfully';
} else {
    echo 'Table does not create.';
}

I get 'Table does not create' when trying to use this. Help would be greatly appreciated. Thanks in advance!

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Teddy Codes
  • 489
  • 4
  • 14

3 Answers3

2

Your filename contains a extension, but I suspect you just want to use the name without the extension as the name of the table. You can use the basename function to remove the extension.

$sqlTableCreate = "CREATE TABLE ". basename($file_name, ".csv") . "( 
    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 there can be different extensions, and you want to remove them more generally, see

How to remove extension from string (only real extension!)

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

I don't see any issue with your posted query but couple things may be wrong

Make sure that there is no table exists with that same name. You can use IF NOT EXISTS marker to be sure like

  CREATE TABLE IF NOT EXISTS". $file_name . "(
  1. make sure that the variable $file_name is not empty. Else, you are passing a null identifier in CREATE TABLE statement; which will not succeed.

Per your comment: you have $file_name = 'currentScan.csv';

That's the problem here. You are trying to create a table named currentScan.csv which your DB engine thinking that currentscan is the DB name and .csv is the table name which obviously doesn't exits and so the error.

Rahul
  • 76,197
  • 13
  • 71
  • 125
-1

first check your database connection and change your query with given below :

$sqlTableCreate = "CREATE TABLE ". $file_name . " ( 
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY, 
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP
)";
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
jilesh
  • 436
  • 1
  • 3
  • 13