I have been using the procedural approach with mysql* until recently. Now I want to shift to mysqli and object oriented approach. Many online resources and books state that OOP is better than procedural even in case of PHP. After going through some online tutorials, I have written a small program that connects to the database and selects a value. I want to know why the object oriented approach is better? Plus is this the right way to code an OO php web page?
The object oriented approach
$host = "localhost";
$username = "root";
$password = "";
$dbname = "compdb";
@ $db = new mysqli($host, $username, $password, $dbname);
if(mysqli_connect_errno())
{
die("Connection could not be established");
}
$query = "SELECT company_id FROM company_basic_details WHERE company_name = 'ABC'";
$result = $db->query($query);
$total_num_rows = $result->num_rows;
echo "The Results Are : <br>";
while($row = $result->fetch_array())
{
echo $row['company_id'];
}
?>
The procedural approach
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "compdb";
@ $db = mysqli_connect($host, $username, $password, $dbname);
if(mysqli_connect_errno())
{
die("Connection could not be established");
}
$query = "SELECT company_id FROM company_basic_details WHERE company_name = 'ABC'";
$result = mysqli_query($db, $query);
$total_num_rows = mysqli_num_rows($result);
echo "The Results Are : <br>";
while($row = mysqli_fetch_array($result))
{
echo $row['company_id'];
}
?>