FeatureUp News
Loading...

How to insert data in MySQL Database using PHP

Hello, Guys. Finally you reached your destination to know how to post data in MySql database using PHP right? Lets learn by following example


How to insert data in MySQL Database using PHP_FeatureUp


First of all we must make the html form for index.html:

<html>
<body>
<form action="index.php" method="get">
<input type="text" name="user">
<input type="submit" value="post">
</form>
</body>
</html>

This html script will post form data to index.php, for example we write "Mikel" on the box and clock post button, the url will change to index.php?user=castiel

Now the php part, index.php:

<?php
// we get submitted data and check if user really submitted it
if(isset($_GET['user']){
$user = $_GET['user'];

// make an mysql connection, make sure to edit this
mysql_connect("host", "user", "password"); // host = host name, user = database user, password = database password
mysql_select_db("database"); // database = mysql database name

// escape input from dangerous charachters
$user = htmlentities(mysql_real_escape_string($user));
}
else{
// else print "you have not submitted anything
die("You have not submitted anything.");
}
?>

Ok we are done with html and php part, now go to mysql: localhost/phpmyadmin if you are on localhost, go to your database and create a table named users with 2 fields:

How to insert data in MySQL Database with PHP_FeatureUp
And click go.
How to insert data in MySQL Database with PHP_FeatureUp

And click save.
Now lets move back to index.php
After $user = htmlentities(mysql_real_escape_string($user)); create a new line and add:
mysql_query("INSERT INTO users(name) VALUES('$user');
echo "Submitted.";

Thats it! Whole script of index.php should look:

<?php
// we get submitted data and check if user really submitted it
if(isset($_GET['user']){
$user = $_GET['user'];

// make an mysql connection, make sure to edit this
mysql_connect("host", "user", "password"); // host = host name, user = database user, password = database password
mysql_select_db("database"); // database = mysql database name

// escape input from dangerous charachters
$user = htmlentities(mysql_real_escape_string($user));

mysql_query("INSERT INTO users(name) VALUES('$user');
echo "Submitted."; 
}
else{
// else print "you have not submitted anything
die("You have not submitted anything.");
}
?>

Thanks for reading and don't forget to follow us or like on Facebook :D

0 comments:

Post a Comment

Quick Message
Press Esc to close
Copyright © 2013 FeatureUp All Right Reserved. The content is copyrighted to FeatureUp and may not be reproduced on other websites without permission or credit.