作者:宝丫2502933885 | 来源:互联网 | 2023-05-19 09:19
I am learning MySQL with PHP and how to create tables & insert the Data. But I am particular confused about the following code:
我正在学习MySQL和PHP,以及如何创建表和插入数据。但我对下面的代码感到特别困惑:
//SECTION 1
$sql = "CREATE TABLE ingredients (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
quanity INT(6) NOT NULL,
package INT(6) NOT NULL,
item VARCHAR(50),
cost DECIMAL(18,2),
store VARCHAR(50),
reg_date TIMESTAMP
)";
//SECTION 2
if ($conn->query($sql) === TRUE) {
echo "Table ingredients created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
//SECTION 3
$conn->close();
So I copied and pasted this code and ran it in my browser, then checked localhost/phpmyadmin and sure enough the TABLE was created.
因此,我复制并粘贴了这段代码并在浏览器中运行,然后检查localhost/phpmyadmin,并确保创建了表。
However, I then deleted the code and ran only SECTION 1, (section 2 & 3 were deleted and not present in the code) assuming this was all I needed to create a Table. After refreshing my browser, no Table in my Database was created.
但是,我随后删除了代码,只运行了第1部分(第2和第3部分被删除,并且没有出现在代码中),假设这是创建表所需的全部内容。在刷新浏览器之后,我的数据库中没有创建任何表。
So I took another look and thought, its probably because I didn't close the connection. So this time I inserted SECTION 1 & SECTION 3 and left out SECTION 2.
所以我又看了一眼,心想,这可能是因为我没有关闭连接。所以这一次我插入了第1节和第3节,省略了第2节。
This also did not create a Table to my surprise. So this is where I am confused at. Why do I need SECTION 2? As far as I can tell from reading it, it only prints out a string, which is just a small notification to me or any user that a Table was created, but it doesn't seem vital in the making of a Table. Why then, can I NOT create a Table without it? I am confused!
这也没有创建一个表,让我吃惊。这就是我困惑的地方。为什么我需要第二部分?从我的阅读中可以看出,它只打印出一个字符串,对于我或任何用户来说,这只是一个创建表的小通知,但对于创建表来说,这似乎并不重要。那么,为什么我不能创建一个没有它的表呢?我是困惑!
2 个解决方案
1
Let me explain your code:
让我解释一下你的代码:
Here you only assign an SQL query-like string to variable $sql.
这里,您只向变量$ SQL分配一个类似SQL查询的字符串。
//SECTION 1
$sql = "CREATE TABLE ingredients (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
quanity INT(6) NOT NULL,
package INT(6) NOT NULL,
item VARCHAR(50),
cost DECIMAL(18,2),
store VARCHAR(50),
reg_date TIMESTAMP
)";
Now you need to execute the SQL script:
现在需要执行SQL脚本:
//SECTION 2
if ($conn->query($sql) === TRUE) {
echo "Table ingredients created successfully";
} else {
echo "Error creating table: " . $conn->error;
}
You don't need an if statement, you can do only:
你不需要if语句,你只需要:
//SECTION 2
$conn->query($sql);
However, the if statements let you check, if the query was actually executed, meaning, if you get true, the query was executed and you know, that the table was created, else, you get an error $conn->error
that you can process and see, what went wrong.
但是,if语句让你检查,如果查询实际上执行了,意思是,如果你得到了true,查询就被执行了,你知道,这个表被创建了,否则,你会得到一个错误$conn->错误,你可以处理和查看,什么出错了。
Closing connection, to release DB memory
关闭连接,释放DB内存
//SECTION 3
$conn->close();