PHP Basics

How can we use SQL in PHP Server Side Scripting?

PHP has predefined functions that helps us to use SQL syntax inside a php file.

SQL in PHP

We can execuate following sql related task.

Establish connection with database

Syntax

mysqli_connect(hostname, username, password, databasename)

Example

<?php

$conn=mysqli_connect(“localhost”,”root”,”password”,”root_database”);

if($conn){

echo “connected to database”;

}else{

echo “failed to connect to the database check connection parameters”;

}

?>

Fetch Data from table using sql syntax in php

Example

Using SQL in a php file, fetch all employee name from employee table.

<?

$conn=mysqli_connect(“localhost”,”root”,”password”,”root_database”);

$sql=”select * from employee_table”;

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

if(mysqli_num_rows($result)>0){

while($row=mysqli_fetch_assoc($result)){

echo $row[“name”].'<br/>’;

}

}

?>

Output

Ram

Shyam

John

Smith

Neha

Raju