09- MySQL Insert Query

0
76

The MySQL Insert Query is used To insert a record in MySQL database the statement used is INSERT INTO command.

Syntax:

INSERT INTO name_of_table (column1, column2, column3,…)
VALUES (value1, value2, value3,…)

 

Rules in performing the INSERT INTO Command:

  • A Numeric Values and NULL word should not be quoted
  • String Values inside SQL query should be quoted
  • Using PHP all SQL query should be quoted
  • No Need to specify a for a column that is SET to AUTO_INCREMENT and TIMESTAMP

 

In last tutorial called 08-MySQL Create Table, we created a blank table named ‘tblpeople’ . This time, we’re going to populate this table.

 

Here are the different examples on how to populate the ‘tblpeople’:

 

Example using MySQLi (Object-Orient):

  1. die("Connection failed: " . $conn->connect_error);
  2. }
  3.  
  4. // sql to Insert record table
  5. $sql = "INSERT INTO <code>tblpeople</code> (<code>LNAME</code>, <code>FNAME</code>, <code>ADDRESS</code>)
  6. VALUES ('Villanueva', 'Joken', 'Kabankalan City');";
  7.  
  8. if ($conn-&gt;query($sql) === TRUE) {
  9. echo "New record created successfully";
  10. } else {
  11. echo "Error: " . $sql . "
  12. " . $conn-&gt;error;
  13. }
  14.  
  15. $conn-&gt;close();
  16. ?&gt;

Example using MySQLi (Procedural):

  1. $server = "localhost";
  2. $username = "root";
  3. $password = "";
  4. $database = "mysqltutorial";
  5.  
  6. // Create connection
  7. $conn = mysqli_connect($server, $username, $password, $database);
  8. // Check connection
  9. if (!$conn) {
  10. die("Connection failed: " . mysqli_connect_error());
  11. }
  12.  
  13. // sql to Insert record table
  14. $sql = "INSERT INTO <code>tblpeople</code> (<code>LNAME</code>, <code>FNAME</code>, <code>ADDRESS</code>)
  15. VALUES ('Villanueva', 'Joken', 'Kabankalan City');";
  16.  
  17. if (mysqli_query($conn, $sql)) {
  18. echo "New record created successfully";
  19. } else {
  20. echo "Error: " . $sql . "
  21. " . mysqli_error($conn);
  22. }
  23.  
  24. mysqli_close($conn);
  25. ?&gt;

Example using PDO:

  1. $sql = "INSERT INTO <code>tblpeople</code> (<code>LNAME</code>, <code>FNAME</code>, <code>ADDRESS</code>)
  2. VALUES ('Villanueva', 'Joken', 'Kabankalan City');";
  3.  
  4. // use exec() because no results are returned
  5. $conn-&gt;exec($sql);
  6. echo "New record created successfully";
  7. }
  8. catch(PDOException $e)
  9. {
  10. echo $sql . "
  11. " . $e-&gt;getMessage();
  12. }
  13.  
  14. $conn = null;
  15. ?&gt;

Out Previous Topic called: 08- MySQL Create Table

Facebook Comments
  • books
    books
  • mysql-php
    mysql-php

LEAVE A REPLY

Please enter your comment!
Please enter your name here