Infolinks

Breaking

Adsense

Thursday, January 21, 2016

PHP INSERT INTO: Add New Record Into A Database

Data is essential in an organization. So storing it in a database helps an organization to easily store it so they can retrieve it in the near future for decision-making. All information systems have the following common functions, to add or insert new record, update existing record, view list of records in the database and delete records. If you are going to create one, all you have to do is to reuse your codes since they are all the same. It just differs in the name of table, column names and variable names.

Here is a code to insert new record in the database using PHP and MySQLi.

Let's assume that you already have your input controls such as textbox, buttons, checkbox, etc. Make sure that the name of your textboxes are lastname and firstname and your form method should be post. Create a table and name it student with the following columns: stud_id, stud_last and stud_first. It is where we are going to save or insert our data from textboxes later.

Student Table

STUDENT









PHP Code Insert Record


<?php
$con = mysqli_connect("localhost","root","","db_name");

$last=$_POST['lastname'];
$first=$_POST['firstname'];
//insert to db
mysqli_query($con,"INSERT INTO student(stud_last,stud_first) values ('$last','$first')") or die(mysqli_error());
?>

I will explain the code above. The first line of code will our database connection. If you are using LAMP, XAMPP or WAMP, your server name is localhost, your username is root and the default password is null (replace null with your password if you have a password), and the last is your database name. Note: database name should start with a letter and should not contain spaces, and other symbols except for unserscore (_).

Next is to collect the data inputted from textboxes after form was submitted and assigning it to varibles $last and $first. The last line of code is used to insert the data to our student table.

Output Insert Record to db



Hope this helps! Just comment below for questions/clarifications. Thank you and God bless! ^_^

PHP INSERT INTO: Add New Record Into A Database

No comments:

Post a Comment

Adbox