Insert User Data in SQL in PHP


/********************************** Create Database ************************************/

// Create connection
$servername = "localhost";
$username = "CMS_user";
$password = "CMS_pass";
$dbname = "my_CMS";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
  die("Connection failed: <br />" . mysqli_connect_error());
}

// Create database
$sql = "CREATE DATABASE IF NOT EXISTS my_CMS";
if (mysqli_query($conn, $sql)) {
  echo "Database $dbname created successfully<br />";
} else {
  echo "Error creating database: <br />" . mysqli_error($conn);
}

mysqli_close($conn);
/********************************** Create Connection ************************************/

// Create connection
$connect = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$connect) {
  die("Connection failed: <br />" . mysqli_connect_error());
}

/********************************** Create Table ************************************/

// sql to create table
$create_table = "CREATE TABLE IF NOT EXISTS Users (
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($connect, $create_table)) {
  echo "Table Users for database $dbname created successfully<br />";
} else {
  echo "Error creating table: <br />" . mysqli_error($connect);
}

/********************************** Insert User Data ************************************/

$inset_user_data = "INSERT INTO Users (firstname, lastname, email)
VALUES ('John', 'Doe', 'john_doe@email.com')";

if (mysqli_query($connect, $inset_user_data)) {
  echo "New record created successfully";
} else {
  echo "Error: " . $inset_user_data . "<br>" . mysqli_error($connect);
}

mysqli_close($connect);

Leave a Reply