Question: Write a PHP Program to insert a record into MYSQL database.
0

Subject: Internet Programming

Topic: Server Side Programming: PHP

Difficulty: High

ADD COMMENTlink
modified 14 months ago  • written 14 months ago by gravatar for Binita Mayekar Binita Mayekar70
0

PHP Program to insert a record into MYSQL Database

  • 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,...)
  • Following program create table named "MyGuests" with five columns: "id", "firstname", "lastname", "email" and "reg_date"; -
  • Then add a new record to the "MyGuests" table using MySQLi (Procedural) approach.
  • If a column is AUTO_INCREMENT (like the "id" column) or TIMESTAMP (like the "reg_date" column), it is no need to be specified in the SQL query; MySQL will automatically add the value.
<?php
$servername = "localhost";
$username = "username";
$password = "password"; 
$dbname = "myDB";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
     // Check connection
     if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}
// 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
     )";
     if (mysqli_query($conn, $sql)) {
         echo "Table MyGuests created successfully";
     } else {
         echo "Error creating table: " . mysqli_error($conn);
 }
 // add a record to the "MyGuests" table
 $sql = "INSERT INTO MyGuests (firstname, lastname, email)
     VALUES ('ABC', 'XYZ', '[email protected]')";
     if (mysqli_query($conn, $sql)) {
         echo "New record created successfully";
     } else {
         echo "Error: " . $sql . "<br>" . mysqli_error($conn);
     }
     mysqli_close($conn);
?>
ADD COMMENTlink
modified 14 months ago  • written 14 months ago by gravatar for Binita Mayekar Binita Mayekar70
Please log in to add an answer.