Shady
Shady

Reputation: 82

Cannot create TABLE with php mysql

I'm not sure what's happening here but I cannot seem to create the table.

Is this a syntax error or something else?

When I tried to paste the CREATE TABLE part into the SQL part on PHPMyAdmin, I had to tinker with the syntax a bit before it worked.

What I want to be able to do it via PHP directly.

$server = 'localhost';
$user = 'root';
$pass = '';

$conn = mysqli_connect($server, $user, $pass);

if (! $conn) {
    echo 'Failed to connect to Server';
}
else {
    echo 'Connected';
}

$sql = 'CREATE DATABASE college';
$table = 'CREATE TABLE students(
    student_id int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY ,
    student_name VARCHAR(255) NOT NULL,
    student_email VARCHAR(255) NOT NULL,
    student_city VARCHAR(255) NOT NULL,
)';

if (mysqli_query($conn, $sql)) {
    echo 'Database created';
}
else {
    echo 'Failed to create Database';
}

if (mysqli_query($conn, $table)) {
    echo 'Table Created';
}
else {
    echo 'Failed to create Table';
}

Upvotes: 1

Views: 1084

Answers (3)

Sergio Castellani
Sergio Castellani

Reputation: 1

I struggled with this a bit, especially because defining $sql = (create table query...) isn't enough, at least with MariaDB, despite what many tutorials suggest. It doesn't throw an error, but it also doesn't create anything.

I solved it by adding this line after defining $sql:

mysqli_query($con, $sql);

Upvotes: -2

Saty
Saty

Reputation: 22532

After create database successfully to need to select database then use create statement.

mysqli_select_db($conn, 'college'); // select database first

if (mysqli_query($conn, $table)) {
    echo 'Table Created';
}
else {
    echo 'Failed to create Table';
}

Upvotes: 1

Arulkumar
Arulkumar

Reputation: 13237

Remove the comma in the end of the below line inside the CREATE TABLE

student_city VARCHAR(255) NOT NULL, 

it will cause the error below:

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 ''' at line 1

Upvotes: 1

Related Questions