<?Php
require "config.php";// Database connection details, $connection object
if($stmt = $connection->query("SELECT id, name ,class, mark FROM student")){
echo "No of records : ".$stmt->num_rows."<br>";
while ($row = $stmt->fetch_assoc()) {
echo $row['id'],$row['name'],$row['class'].$row['mark']."<br>";
}
}else{
echo $connection->error;
}
?>
We will get error message if the query fails to execute.
MySQLI database connection file
Single record without parameter checking<?Php
require "config.php";// Database connection
if($stmt = $connection->query("SELECT id, name ,class, mark FROM student")){
echo "No of records : ".$stmt->num_rows."<br>";
$row = $stmt->fetch_assoc();
echo $row['id'],$row['name'],$row['class'].$row['mark'];
}else{
echo $connection->error;
}
?>
Table and bootstrap design
if($stmt = $connection->query("SELECT id, name ,class, mark FROM student")){
echo "No of records : ".$stmt->num_rows."<br>";
echo "<table class='table table-striped'>
<tr class='info'> <th> ID</th><th>Name</th><th>Class</th><th>Mark</th></tr>";
while ($row = $stmt->fetch_assoc()) {
echo "<tr><td>$row[id]</td><td>$row[name]</td><td>$row[class]</td><td>$row[mark] </td></tr>";
}
echo "</table>";
}else{
echo $connection->error;
}
Single record with parameter checking<?Php
require "config.php";// Database connection
//////////////////////////////
$id=3;
if($stmt = $connection->prepare("SELECT id, name ,class, mark FROM student WHERE id=?")){
$stmt->bind_param('i',$id);
$stmt->execute();
$result = $stmt->get_result();
echo "No of records : ".$result->num_rows."<br>";
$row=$result->fetch_object();
echo $row->name;
}else{
echo $connection->error;
}
?>
Multiple records with string parameter
<?Php
require "config.php";// Database connection
//////////////////////////////
$class='Three';
if($stmt = $connection->prepare("SELECT id, name ,class, mark FROM student WHERE class=?")){
$stmt->bind_param('s',$class);
$stmt->execute();
$result = $stmt->get_result();
echo "No of records : ".$result->num_rows."<br>";
while ($row = $result->fetch_assoc()) {
echo $row['id'],$row['name'],$row['class'].$row['mark']."<br>";
}
}else{
echo $connection->error;
}
?>
Procedural style ( with two binding parameters )
<?Php
require "config.php";// Database connection
//////////////////////////////
$class='Three';
$mark=60;
if ($stmt = mysqli_prepare($connection, "SELECT id, name ,class, mark FROM student WHERE class=? AND mark >?")) {
mysqli_stmt_bind_param($stmt, "si", $class,$mark);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
echo " No of records :".mysqli_stmt_num_rows($stmt)."<br>";
mysqli_stmt_bind_result($stmt, $id,$name,$class,$mark);
while (mysqli_stmt_fetch($stmt)) {
echo "$id, $name,$class,$mark <br>";
}
mysqli_stmt_close($stmt);
}else{
echo mysqli_error($connection);
}
?>
PHP code generator using MySQLi functions to display records of a table
MYSQLI Functionsmysqli_num_rows() Number of rows in result set SELECT query UPDATE query