直到最近,我一直在使用 mysql* 的程序方法。现在我想转向 mysqli 和面向对象的方法。许多在线资源和书籍指出,即使在 PHP 的情况下,OOP 也比程序性更好。在浏览了一些在线教程之后,我编写了一个连接数据库并选择一个值的小程序。我想知道为什么面向对象的方法更好?另外,这是编写 OO php 网页的正确方法吗?
面向对象的方法
$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'];
}
?>
程序方法
<?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'];
}
?>