You are on page 1of 9

PHP Database Connectivity

• Open database connection


mysqli_connect(host,username,password,dbname);
• Select database
mysqli_select_db(connection,dbname);
• Query the database
mysqli_query(connection,query);
Query types
• Insert
mysqli_query($con,"INSERT INTO Persons
(FirstName,LastName,Age) VALUES ('Glenn','Quagmire',33)");
• Select
mysqli_query($con,"SELECT * FROM Persons");
• Update
mysqli_query($con, "UPDATE Persons SET LastName='Doe'
WHERE Age=40";
• Delete
mysqli_query($con, "DELETE FROM Persons WHERE Age=50");
Fetch the selected data
• mysqli_fetch_row()
– fetches one row from a result-set and returns it as an
enumerated array.
mysqli_fetch_row(result);
• mysqli_fetch_array()
– fetches a result row as an associative array, a numeric
array, or both.
mysqli_fetch_array(result);
• mysqli_num_rows()
– returns the number of rows in a result set.
mysqli_num_rows(result);
• Close database connection
mysqli_close(connection);
Sample code
// Open the connection and select the database
$host="localhost";
$username="root";
$password="";
$dbname="sample";
$conn =mysqli_connect($host,$username,$password,$dbname)
or die("Error");
OR
$conn =mysqli_connect($host,$username,$password)
or die("Error");
mysqli_select_db($conn, $dbname);
//Executing the query
mysqli_query($conn,"INSERT INTO persons
(FirstName,LastName,Age)VALUES('John','Quagmire',55)");
echo "Inserted Successfully";

mysqli_query($conn,"UPDATE persons SET LastName='Doe'


WHERE FirstName='Glen'");
echo "Updated Successfully";

mysqli_query($conn,"DELETE FROM persons WHERE


LastName='Doe'");
echo "Deleted Successfully";

$result=mysqli_query($conn,"SELECT * FROM persons");


//Retrieve result from the select query
$result=mysqli_query($conn,"SELECT * FROM persons");
while($row=mysqli_fetch_row($result)) {
echo $row[0]."<br/>";
}

$result=mysqli_query($conn,"SELECT * FROM persons");


while($row=mysqli_fetch_array($result)) {
echo $row["FirstName"]."<br/>";
echo $row["LastName"]."<br/>";
echo $row["Age"]."<br/>";
}

echo "No of rows in the table ".mysqli_num_rows($result);


//Close the connection
mysqli_close($conn);

You might also like