A shortened version of weblog.

A shortened version of weblog.

PHP MySQL Create Table

  • Programming
  • 10 June 2022
  • 170 Views
  • Sathiyamoorthy V

1. Create a MySQL Table ( MySQLi Object-Oriented )

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// sql to create table
$sql = "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 )";
if ($conn->query($sql) === TRUE)
{
echo "Table MyGuests created successfully";
}
else
{
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

2. Create a MySQL Table ( MySQLi Procedural )

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// sql to create table
$sql = "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 )";
if (mysqli_query($conn, $sql))
{
echo "Table MyGuests created successfully";
}
else
{
echo "Error creating table: " . mysqli_error($conn);
}

mysqli_close($conn);
?>

3. Create a MySQL Table ( PDO )

<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDBPDO";

try
{
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

// sql to create table
$sql = "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 )";

// use exec() because no results are returned
$conn->exec($sql);
echo "Table MyGuests created successfully";
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}

$conn = null;
?>

RELATED POST

10 June 2022   |   Programming
PHP Create a MySQL Database
Read More
09 June 2022   |   Programming
PHP Connect to MySQL
Read More
20 May 2022   |   Programming
PHP Variables
Read More
10 June 2022   |   Programming
PHP MySQL Insert Data
Read More
19 June 2022   |   Programming
PHP MySQL Select Data
Read More
20 September 2022   |   Programming
IoT - Internet of Things Presentations & Programming Materials
Read More
PHP MySQL Create Table
http://blogbyte.in/blog-details/?cid=2&pid=36

LEAVE A COMMENT

+