如何创建一个 table 并向其中插入数据?

How to create a table and insert data into it?

我想做的是在 $sql 这是我要编写 SQL 命令的地方

    $connect = new mysqli($servername, $username, $password, $database);
    
    if ($connect -> connect_error) {
        die("Unable to Connect : " . connect_error);
    }
    
    $sql = /*"CREATE TABLE student (
        student_id INT,
        name VARCHAR(20),
        major VARCHAR(20),
        PRIMARY KEY(student_id)
    ); */
    
    "INSERT INTO student VALUE(3, 'joseph', 'education');";
    
    if ($connect -> query($sql) === TRUE) {
        echo "New Table Created! <br><br>";
    }
    else {
        echo "Error : " . $sql . " <br><br>" . $connect -> error . "<br><br>";
    }
    
    echo "Connected Successfully!";

这是我删除创建 table 时的输出。插入数据成功

New Table Created!

Connected Successfully!

这是我没有删除 CREATE TABLE

时的输出
Error : CREATE TABLE student ( student_id INT, name VARCHAR(20), major VARCHAR(20), PRIMARY KEY(student_id) ); INSERT INTO student VALUE(3, 'joseph', 'education');

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 'INSERT INTO student VALUE(3, 'joseph', 'education')' at line 8

Connected Successfully!

我需要使用什么函数来将这样的 $sql 和 SQL 命令放入?有可能吗?这就是 SQL 的工作方式吗?

$sql = "CREATE TABLE student (
        student_id INT,
        name VARCHAR(20),
        major VARCHAR(20),
        PRIMARY KEY(student_id)
    );
    
    INSERT INTO student VALUE(3, 'joseph', 'education');"

您需要分两步完成。首先,用 CREATE TABLE 准备一个语句,然后用 INSERT.

准备第二个语句
<?php

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$connect = new mysqli($servername, $username, $password, $database);
$connect->set_charset('utf8mb4'); // always set the charset

$sql = "CREATE TABLE student (
    student_id INT,
    name VARCHAR(20),
    major VARCHAR(20),
    PRIMARY KEY(student_id)
)";
$stmt = $connect->prepare($sql);
$stmt->execute();

$stmt = $connect->prepare("INSERT INTO student VALUE(3, 'joseph', 'education')");
$stmt->execute();