KEMBAR78
PHP Database Connection | PDF | Databases | Computer Programming
0% found this document useful (0 votes)
13 views9 pages

PHP Database Connection

The document provides PHP code examples for establishing a database connection, creating a database and table, inserting data, and implementing a login system. It includes HTML and CSS for a login interface, as well as code for fetching and displaying data from a database. The examples illustrate basic CRUD operations and user authentication using MySQL with PHP.

Uploaded by

Wipro pvt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views9 pages

PHP Database Connection

The document provides PHP code examples for establishing a database connection, creating a database and table, inserting data, and implementing a login system. It includes HTML and CSS for a login interface, as well as code for fetching and displaying data from a database. The examples illustrate basic CRUD operations and user authentication using MySQL with PHP.

Uploaded by

Wipro pvt
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

PHP Database Connection

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

// Create connection
$conn = new mysqli($servername, $username, $password);

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>

Create a database

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

// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// Create database
$sql = "CREATE DATABASE myDB";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error;
}

$conn->close();
?>

Create a table in database using php

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

// sql to create table


$sql = "CREATE TABLE MyGuests (
id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50),
reg_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE
CURRENT_TIMESTAMP
)";

if ($conn->query($sql) === TRUE) {


echo "Table MyGuests created successfully";
} else {
echo "Error creating table: " . $conn->error;
}

$conn->close();
?>

Insert data in database

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

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)


VALUES ('John', 'Doe', 'john@example.com')";

if ($conn->query($sql) === TRUE) {


echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

$conn->close();
?>

PHP MySQL Login System

Create four files here for the login system

1. index.html - This file is created for the GUI view of the login page and empty field
validation.
2. style.css - This file is created for the attractive view of the login form.
3. connection.php - Connection file contains the connection code for database
connectivity.
4. authentication.php - This file validates the form data with the database which is
submitted by the user.

index.html

<html>

<head>

<title>PHP login system</title>

// insert style.css file inside index.html

<link rel = "stylesheet" type = "text/css" href = "style.css">

</head>

<body>

<div id = "frm">

<h1>Login</h1>

<form name="f1" action = "authentication.php" onsubmit = "return validation()" met


hod = "POST">

<p>

<label> UserName: </label>


<input type = "text" id ="user" name = "user" />

</p>

<p>

<label> Password: </label>

<input type = "password" id ="pass" name = "pass" />

</p>

<p>

<input type = "submit" id = "btn" value = "Login" />

</p>

</form>

</div>

// validation for empty field

<script>

function validation()

var id=document.f1.user.value;

var ps=document.f1.pass.value;

if(id.length=="" && ps.length=="") {

alert("User Name and Password fields are empty");

return false;

else

if(id.length=="") {

alert("User Name is empty");


return false;

if (ps.length=="") {

alert("Password field is empty");

return false;

</script>

</body>

</html>

style.css

body{

background: #eee;

#frm{

border: solid gray 1px;

width:25%;

border-radius: 2px;

margin: 120px auto;

background: white;

padding: 50px;

#btn{

color: #fff;
background: #337ab7;

padding: 7px;

margin-left: 70%;

connection.php

<?php

$host = "localhost";

$user = "root";

$password = '';

$db_name = "javatpoint";

$con = mysqli_connect($host, $user, $password, $db_name);

if(mysqli_connect_errno()) {

die("Failed to connect with MySQL: ". mysqli_connect_error());

?>

authentication.php

<?php

include('connection.php');

$username = $_POST['user'];

$password = $_POST['pass'];

//to prevent from mysqli injection

$username = stripcslashes($username);

$password = stripcslashes($password);
$username = mysqli_real_escape_string($con, $username);

$password = mysqli_real_escape_string($con, $password);

$sql = "select *from login where username = '$username' and password = '$passwor
d'";

$result = mysqli_query($con, $sql);

$row = mysqli_fetch_array($result, MYSQLI_ASSOC);

$count = mysqli_num_rows($result);

if($count == 1){

echo "<h1><center> Login successful </center></h1>";

else{

echo "<h1> Login failed. Invalid username or password.</h1>";

?>

Fetching the data from database using php and mysql

Important points: Create a database mydb and create a table “students”

<!-- PHP code to establish connection with the localserver -->


<?php

// Username is root
$user = 'root';
$password = '';

// Database name is geeksforgeeks


$database = 'mydb';
$servername='localhost';
$mysqli = new mysqli($servername, $user,
$password, $database);

// Checking for connections


if ($mysqli->connect_error) {
die('Connect Error (' .
$mysqli->connect_errno . ') '.
$mysqli->connect_error);
}

// SQL query to select data from database


$sql = " SELECT * FROM students";
$result = $mysqli->query($sql);
$mysqli->close();
?>
<!-- HTML code to display data in tabular format -->
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>Student Details</title>
<!-- CSS FOR STYLING THE PAGE -->
<style>
table {
margin: 0 auto;
font-size: large;
border: 1px solid black;
}

h1 {
text-align: center;
color: #006600;
font-size: xx-large;
font-family: 'Gill Sans', 'Gill Sans MT',
' Calibri', 'Trebuchet MS', 'sans-serif';
}

td {
background-color: #E4F5D4;
border: 1px solid black;
}

th,
td {
font-weight: bold;
border: 1px solid black;
padding: 10px;
text-align: center;
}

td {
font-weight: lighter;
}
</style>
</head>

<body>
<section>
<h1>Student Data</h1>
<!-- TABLE CONSTRUCTION -->
<table>
<tr>
<th>Name</th>
<th>PRN</th>
<th>Marks</th>
<th>Class</th>
</tr>
<!-- PHP CODE TO FETCH DATA FROM ROWS -->
<?php
// LOOP TILL END OF DATA
while($rows=$result->fetch_assoc())
{
?>
<tr>
<!-- FETCHING DATA FROM EACH
ROW OF EVERY COLUMN -->
<td><?php echo $rows['Name'];?></td>
<td><?php echo $rows['PRN'];?></td>
<td><?php echo $rows['Marks'];?></td>
<td><?php echo $rows['Score'];?></td>
</tr>
<?php
}
?>
</table>
</section>
</body>

</html>

You might also like