PHP encapsulates mysqli Object Oriented mysql database operation classes and usage examples
- 2021-11-29 06:15:12
- OfStack
This paper describes the PHP encapsulation mysqli based on object-oriented mysql database operation and usage. Share it for your reference, as follows:
First, encapsulate the mysql class
mysql.php
<?php
class Mysql{
private static $host="localhost";
private static $user="root";
private static $password="123456";
private static $dbName="test"; // Database name
private static $charset="utf8"; // Character encoding
private static $port="3306"; // Port number
private $conn=null;
function __construct(){
$this->conn=new mysqli(self::$host,self::$user,self::$password,self::$dbName,self::$port);
if(!$this->conn)
{
die(" Database connection failed! ".$this->conn->connect_error);
}else{
echo " Connection succeeded! ";
}
$this->conn->query("set names ".self::$charset);
}
// Execute sql Statement
function sql($sql){
$res=$this->conn->query($sql);
if(!$res)
{
echo " Data operation failed ";
}
else
{
if($this->conn->affected_rows>0)
{
return $res;
}
else
{
echo "0 Row data is affected! ";
}
}
}
// Returns the number of affected data rows
function getResultNum($sql){
$res=$this->conn->query($sql);
return mysqli_num_rows($res);
}
// Close the database
public function close()
{
@mysqli_close($this->conn);
}
}
?>
Then you can call
index.php
<?php
require_once "mysql.php";
$conn=new Mysql();
$sql="select * from user";
// Execute the query and get the query results
$result=$conn->sql($sql);
// Output the number of affected data rows
$num=$conn->getResultNum($sql);
echo " Number of rows affected: ".$num;
// Read and output records
while ($row = mysqli_fetch_assoc($result))
{
echo "{$row['name']} ";
echo "{$row['password']}";
}
// Close the database
$conn->close();
For more readers interested in PHP related contents, please check the topics on this site: "Summary of php+mysqli Database Programming Skills", "Introduction to php Object-Oriented Programming", "Encyclopedia of PHP Array (Array) Operation Skills", "Introduction to PHP Basic Syntax", "Summary of php String (string) Usage", "Introduction to php+mysql Database Operation Skills" and "Summary of php Common Database Operation Skills"
I hope this article is helpful to everyone's PHP programming.