Create Table – PHP & MySQL

Create Table – PHP sử dụng hàm mysqli query() hoặc mysql_query() để tạo bảng MySQL. Hàm này nhận hai tham số và trả về TRUE nếu thành công hoặc FALSE nếu thất bại.

Cú pháp

$mysqli->query($sql,$resultmode)
STTMô tả thông số
1$sql
Bắt buộc – Truy vấn SQL để tạo bảng MySQL.
2$resultmode
Tùy chọn – Hằng số MYSQLI_USE_RESULT hoặc MYSQLI_STORE_RESULT tùy thuộc vào hành động mong muốn kết quả của bạn. Theo mặc định, MYSQLI_STORE_RESULT được sử dụng.

Ví dụ Create Table

Hãy thử ví dụ sau để tạo bảng trong cơ sở dữ liệu đã được tạo

Sao chép và dán ví dụ sau vào file mysql_example.php

<html>
   <head>
      <title>Creating MySQL Table</title>
   </head>
   <body>
      <?php
         $dbhost = 'localhost';
         $dbuser = 'root';
         $dbpass = 'root@123';
         $dbname = 'TUTORIALS';
         $mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
         
         if($mysqli->connect_errno ) {
            printf("Connect failed: %s<br />", $mysqli->connect_error);
            exit();
         }
         printf('Connected successfully.<br />');
         $sql = "CREATE TABLE tutorials_tbl( ".
            "tutorial_id INT NOT NULL AUTO_INCREMENT, ".
            "tutorial_title VARCHAR(100) NOT NULL, ".
            "tutorial_author VARCHAR(40) NOT NULL, ".
            "submission_date DATE, ".
            "PRIMARY KEY ( tutorial_id )); ";
         if ($mysqli->query($sql)) {
            printf("Table tutorials_tbl created successfully.<br />");
         }
         if ($mysqli->errno) {
            printf("Could not create table: %s<br />", $mysqli->error);
         }
         $mysqli->close();
      ?>
   </body>
</html>

Dữ liệu đầu ra

Truy cập vào mysql_example.php được thực thi trên máy chủ web apache và kết quả đầu ra.

Connected successfully.
Table tutorials_tbl created successfully.