News:

Alert!!! HTML Evaluation 01- Quiz

Main Menu

PHP MySQL Create Table: 014

Started by Cohort Master, Apr 01, 2024, 08:40 AM

Previous topic - Next topic

Cohort Master

A database table has its own unique name and consists of columns and rows.

Create a MySQL Table Using MySQLi
The CREATE TABLE statement is used to create a table in MySQL.

We will create a table named "MyGuests", with five columns: "id", "firstname", "lastname", "email" and "reg_date":
QuoteWe will be creating the table below directly from Mysqli database
CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
)

PHP MySQL Insert Data
Insert Data Into MySQL Using MySQLi
After a database and a table have been created, we can start adding data in them.

Here are some syntax rules to follow:

The SQL query must be quoted in PHP
String values inside the SQL query must be quoted
Numeric values must not be quoted
The word NULL must not be quoted
The INSERT INTO statement is used to add new records to a MySQL table:
INSERT INTO table_name (column1, column2, column3,...)
VALUES (value1, value2, value3,...)

In the previous chapter we created an empty table named "MyGuests" with five columns: "id", "firstname", "lastname", "email" and "reg_date". Now, let us fill the table with data.
QuoteNote: If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP with default update of current_timesamp (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.

The following examples add a new record to the "MyGuests" table:
<?php
$servername 
"localhost";
$username "username";
$password "password";
$dbname "myDB";

// Create connection
$conn = new mysqli($servername$username$password$dbname);
// Check connection
if ($conn->connect_error) {
  die(
"Connection failed: " $conn->connect_error);
}

$sql "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', 'john@example.com')"
;

if (
$conn->query($sql) === TRUE) {
  echo 
"New record created successfully";
} else {
  echo 
"Error: " $sql "<br>" $conn->error;
}

$conn->close();
?>