Search code examples
phpmysql

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';
}

Solution

  • 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';
    }