Reputation: 27
What I'm trying to do is in the $sql
this is where I'm going to code the SQL commands
$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!";
This is the output when I removed the create table. The inserted data is successful
New Table Created!
Connected Successfully!
This the output when I did not removed the 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!
What function do I need to use to put in the $sql
the SQL commands like this? Is it even possible? Is this how SQL works?
$sql = "CREATE TABLE student (
student_id INT,
name VARCHAR(20),
major VARCHAR(20),
PRIMARY KEY(student_id)
);
INSERT INTO student VALUE(3, 'joseph', 'education');"
Upvotes: 2
Views: 1075
Reputation: 33305
You need to do it in two steps. First, prepare a statement with the CREATE TABLE
and then prepare the second statement with 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();
Upvotes: 3