Saturday, 9 September 2017

HOW TO USE PHP TO INSERT DATA INTO MYSQL DATABASE
To achieve these follow the following steps:
1.      Create a table
2.      Writing php code to INSET data into mysql database
3.      Confirming the success of your connection.
To create a table using my phpAdmin
Php myAdmin is the most simple setup that you can use for a table. Here are some analysis of the table.
  • Name – This is the name of your column. It will be displayed at the top of your table.
  • Type – You can set a column type here.
  • Length/Values – Used to specify the maximum length your entry in this column can have.
  • Index – We used “Primary” index for our “ID” field. When creating a table, it is recommended to have one ID column. It is used to enumerate table entries and required when configuring table relationships. I also marked “A_I”, which means Auto Increment.
Click Save and your table will be created.
Writing php code follow this:
<?php
const DB_USER= "root";
const DB_PASS= "";
const DB_SERVER= "localhost";
//create a database connection
$connection= mysqli_connect(DB_SERVER,DB_USER,DB_PASS,DB_NAME);

if ($connection){
echo "successful";

}else {
die ("database cconnection failed".mysqli_connect_error()."(".mysqli_connect_error().")");
}
// Set the variables for the person we want to add to the database
$first_Name = "Maruf";
$last_Name = "Olawale";
$email = "sewen101@yahoo.com";
// Here we create a variable that calls the prepare() method of the database object
// The SQL query you want to run is entered as the parameter, and placeholders are written like this :placeholder_name
$my_Insert_Statement = $my_Db_Connection->prepare("INSERT INTO Students (name, lastname, email)VALUES (:first_name,:last_name, :email)");
// Now we tell the script which variable each placeholder actually refers to using the bindParam() method
// First parameter is the placeholder in the statement above - the second parameter is a variable that it should refer to
$my_Insert_Statement->bindParam(:first_name, $first_Name);
$my_Insert_Statement->bindParam(:last_name, $last_Name);
$my_Insert_Statement->bindParam(:email, $email);
// Execute the query using the data we just defined
// The execute() method returns TRUE if it is successful and FALSE if it is not, allowing you to write your own messages here
if ($my_Insert_Statement->execute()) {
  echo "New record created successfully";
} else {
  echo "Unable to create record";
}

?>

No comments:

Post a Comment