MySQLi Select Using PHP
MySQLi Select Query Using PHP
The SELECT statement is used to display data from a table. To display all data from a table using select(*) statement and to display particular field's data use select filed1,filed2 at the place of (*).
Syntax
The SELECT statement is used to select data from one or more tables:
SELECT column_name(s) FROM table_name
Or we can use the * character to select ALL columns from a table:
SELECT * FROM table_name
MySQLi functions used in select query:
- mysqli_num_rows(mysqli_result $result): returns number of rows.
- mysqli_fetch_assoc(mysqli_result $result): returns row as an associative array. Each key of the array represents the column name of the table. It returns NULL if there are no more rows.
PHP MySQLi Select Query Example
<?php
$host = "localhost";
$user = "";
$pass = "";
$dbname = "users";
$conn = mysqli_connect($host,$user,$pass,$dbname) or die(mysqli_error($conn));
$sql = "SELECT * FROM users";
$retval=mysqli_query($conn,$sql);
if(mysqli_num_rows($retval) > 0){
while($row = mysqli_fetch_assoc($retval)){
echo "EMP ID :$row['id']<br> ".
"EMP NAME :$row['name']<br> ".
"EMP SALARY : $row['salary'] <br> ".
"--------------------------------<br>";
} //end of while
}else{
echo "0 results";
}
mysqli_close($conn);
?>
Output:
Connected successfully
User ID :1
User Name: name1
User Salary: 90000
--------------------------------
User ID :2
User Name: name2
User Salary: 50000
--------------------------------
User ID :3
User Name: name3
User Salary: 900000
Display the Records inside Table:
<?php
$host = "localhost";
$user = "";
$pass = "";
$dbname = "users";
$conn = mysqli_connect($host,$user,$pass,$dbname) or die(mysqli_error($conn));
$sql = "SELECT * FROM users";
$retval=mysqli_query($conn,$sql);
if(mysqli_num_rows($retval) > 0){
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Salary</th></tr>";
while($row= mysqli_fetch_array($val))
{
echo "<tr>";
echo "<td>".$row['id']."</td>";
echo "<td>".$row['name']."</td>";
echo "<td>".$row['salary']."</td>";
echo "</tr>";
}
echo "</table>";
}else{
echo "0 results";
}
mysqli_close($conn);
?>
Output:
Display Data with table: Users
| id | name | salary |
|---|---|---|
| 1 | Name1 | 55000 |
| 2 | Name2 | 70000 |
Series:
MySql Tutorials Hub
