Connection of database in mysql using php(source code)

Connection of database  in  mysql using php

Connection with the database can be  established using mysqli_connect() function which accepts four parameter as the argument viz. server name,username ,password and database name.
  Server name-It can be url of the database or localhost in case of      on the same machine .
  Username-It is the name of user (e.g. root) .
  Password-Password associated with that user name . 
  Database-The name of database in which you want to insert the       data.

The code for the same is given below.


<?php
$servername="localhost";
$username="root";
$password="";
$dbname="db1";

$conn=mysqli_connect($servername,$username,$password,$dbname);
if($conn)
{
echo "connection ok";
}
else
{
die("Connnetion Failed because".mysqli_connect_error());
}

?>


Explanation:
Here $conn is a variable which will store true value in case of successful connection
is established so it will print Connection Ok as if condition will be true else it will print
connection field.
The die() function prints a message and exits the current script.
mysqli_connect_error()will print the type of error occurred.

Insert Data into the database by taking it

from user using php mysql connection

The code for the insertion of data into database using php by taking input from user is given below.

<?php
$servername="localhost";
$username="root";
$password="";
$dbname="project";

$conn=mysqli_connect($servername,$username,$password,$dbname);
if($conn)
{
//echo "connection ok";
}
else
{
die("Connnetion Failed because".mysqli_connect_error());
}

error_reporting(0);
?>

<html>
<head><title>Database Connection</title>
</head>
<body>
<form action="" method="GET">
Rollno<input type="text" name="rollno" value=""/><br/><br/>
Name<input type="text" name="studentname" value=""/><br/><br/>
Class<input type="text" name="class" value=""/><br/><br/>
<input type="submit" name="submit" value="submit"/>
</form>

<?php
if($_GET['submit'])
{

$rn= $_GET['rollno'];
$sn=$_GET['studentname'];
$cn=$_GET['class'];

if($rn!=""&& $sn!="" && $cn!="")
{
$query="INSERT INTO student VALUES ('$rn','$sn','$cn')";
$data=mysqli_query($conn,$query);
if($data)
{
echo "Data inserted into Database";
}
}
else
{
echo "All Fields Required";
}
}
?>
</body>
</html>

Explanation:
Above program is taking input from user with the help of form created in html and insertion of data
is done .Validation of input have been done using if condition,if user leave any field "All fields
are required " message will be displayed.

Output:












After clicking submit button:


Comments

Popular posts from this blog

Error http://172.0.0.1:8080/apex application not found in oracle 10g Solved

Sequence diagram of Airport Check-in and Sreening System in uml