Unable to create table using PHP script

I am unable to create table with the follwing php script:

<?php

$tablename = "XDA";

$servername = "";

$username = "";

$password = "";

$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);

}

$sql = "CREATE TABLE $tablename (

id INT(255) AUTO_INCREMENT PRIMARY KEY,

image_name VARCHAR(255),

image_link VARCHAR(255),

image_size VARCHAR(255))";

if ($conn->query($sql) === TRUE) {

echo "Table $tablename created successfully";

} else {

echo "Error creating table: " . $conn->error;

}

$conn->close();

?>

I don’t know what’s wrong with the code but whenever I am running it I am getting the following error:

Error creating table: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ‘( id INT(255) AUTO_INCREMENT PRIMARY KEY, image_name VARCHAR(255), image_link VA’ at line 1

I solved your problem. This should be your final code:

<?php $tablename = 'XDA';

$servername = '';

$username = '';

$password = '';

$dbname = '';

$conn = new mysqli($servername, $username, >$password, $dbname);

if ($conn->connect_error) {

die('Connection failed: ' . $conn-connect_error);

}

 $sql = 'CREATE TABLE $tablename (id INT(255) AUTO_INCREMENT PRIMARY KEY,

 image_name VARCHAR(255),


 image_link VARCHAR(255),

 image_size VARCHAR(255))';

 if ($conn->query($sql) === TRUE) {

 echo 'Error creating table: ' .$tablename.'created successfully';

 } else {

 echo 'Error creating table: ' . $conn-error;

	}
 $conn->close();

?>

The problem here is about quotation marks used.
Just note that this (which is correct):


Is not like this:

Just use single quote marks ( ’ ') which is safer to do with php.

EDIT: I also changed this:

to this:

echo ‘Table’ .$tablename. " created successfully";

1 Like

Please put your code snippets between ``` and ``` If you don’t want to tire us with formatting your codes :weary:

You cannot create tables via Php code, It must be dome via Phpmyadmin at Cpanel :slight_smile:

3 Likes

Hehe sorry. I already fix it right now :sweat_smile:

1 Like

Oh, I wasn’t with you but thanks :sweat_smile:

Alright BayoDino This was the last one my website is now completely developed. And I think now I need PHP torurials.

The only thing about your code caught my attention is the INT(255) one. I’m not sure you can specify a column length for INT columns. Maybe changing that to just INT works?

That was the first thing I thought of as well! But it’s databases that cannot be created through PHP, tables can be created through PHP.

4 Likes

My bad.

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.