PHP Insert to Db

We will now use our users table inside the database examples:

users table

 

 

 

 

Our users table has 3 columns: id, name, surname.

To INSERT some new data in our table we will:

  1. connect to the server (localhost)
  2. select a database (examples)
  3. create a SQL query
  4. run the query and store the result
  5. check if the query has been successful
<?php #insertData.php
//connecting to server
$dbc = mysqli_connect('localhost','root','') or
die('could not connect: '. mysqli_connect_error() );

//selecting the database
mysqli_select_db("examples") or die('could not select db');

//DATA TO INSERT..
  $name = "john";
$surname = "doe";

//CREATING A DATABASE QUERY
/**
* $q = "INSERT INTO `DATABASE`.`TABLE` (`FIELD`, `FIELD`, `FIELD`)
* VALUES ('value', 'value', 'value')";

*/

//we can use NULL for the auto incremented primary key
$q = "INSERT INTO `examples`.`users` (`id`, `name`, `surname`)
VALUES (NULL, '$name', '$surname')";

//EXECUTING THE QUERY AND STORING THE RESULT IN A VARIABLE
$result = mysqli_query($dbc, $q);

//CHECKING IF THE QUERY AFFECTED A ROW USING mysqli_affected_rows()
if(mysqli_affected_rows($dbc) == 1){
//positive response
echo "data inserted";
} else {
//negative response
echo "could not insert data";
}

//CLOSING DATABASE CONNECTION
mysqli_close($dbc);
?>

You can INSERT more than one row using the following syntax:

<?php #insertData.php

//DATA TO INSERT..
  $name1 = "john";
$surname1 = "doe";

  $name2 = "bill";
$surname2 = "smith";

  $name3 = "james";
$surname3 = "bond";


//CREATING A DATABASE QUERY
/**
* $q = " INSERT INTO `DATABASE`.`TABLE` (`FIELD`, `FIELD`, `FIELD`)
* VALUES ('value', 'value', 'value'),
* ('value', 'value', 'value'),
* ('value', 'value', 'value') ";
*/


$q = "INSERT INTO `examples`.`users` (`id`, `name`, `surname`)
VALUES (NULL, '$name1', '$surname1'),
(NULL, '$name2', '$surname2'),
(NULL, '$name3', '$surname3') ";

?>

 

PHP Insert to Db

We will now use our users table inside the database examples:

users table

 

 

 

 

Our users table has 3 columns: id, name, surname.

To INSERT some new data in our table we will:

  1. connect to the server (localhost)
  2. select a database (examples)
  3. create a SQL query
  4. run the query and store the result
  5. check if the query has been successful

You can INSERT more than one row using the following syntax: