PHP Tutorial

Define PHP

PHP Installation

PHP INI File

PHP Comment

PHP Case Sensitivity

PHP Variable, DataType

PHP Echo & Print

PHP Operators

PHP Receiving Input

Decision Making - if...else

PHP Switch Case

PHP Loops

PHP Jumping Statement

PHP Image Gallery

PHP File Upload

PHP Arrays

PHP Date Functions

PHP String Functions

PHP Math Functions

PHP Functions

PHP Variable Scope

PHP Constant Variable

PHP Superglobals

PHP Form Validation

PHP Include Statement

PHP Filter

PHP File Handling

PHP Cookies

PHP Session

PHP Send Emails

PHP Captcha

PHP MySQL Select

PHP MySQL Insert

PHP MySQL Delete

PHP MySQL Update

PHP MySQL Injection

PHP Assignment

Page Stats

Visitor: 404

PHP MySql Select

In PHP, we can execute a select MySql statement and fetch the records from the database table. First we need to create a MySql connection, write the sql query, execute the query and fetch the record.

Example 1: Create a MySql connection, execute the query and fetch all the record from the MySql table.

<?php
	//$conn = mysqli_connect("server_name", "username" , "password", "database_name");
	$conn = mysqli_connect("localhost", "root" , "", "student");
	
	if($conn === false){
		die("ERROR: Could not connect to database.");
	}
	
	$sql = "select * from book"; //sql query, book is a table name
	$result = mysqli_query($conn, $sql);
	
	while($rows = mysqli_fetch_array($result)) //fetch all records
	{
		echo $rows['Id'] . $rows['Name'] . "<br>"; //display records
	}
	
	mysqli_close($conn); //close connection
?>

Example 2: Count number of rows/records.

<?php
	$conn = mysqli_connect("localhost", "root" , "", "student");
	
	if($conn === false){
		die("ERROR: Could not connect to database.");
	}
	
	$sql = "select * from book";
	$result = mysqli_query($conn, $sql);
	$rows = mysqli_num_rows($result);
	echo "Total number of Records: ". $rows;
	
	mysqli_close($conn);
?>
Advertisement
Updated: 19-Aug-21