MySQLi কী?
MySQLi (MySQL Improved) হলো PHP-র extension যা MySQL database-এর সাথে যোগাযোগ করে। পুরনো mysql_* function-এর আধুনিক সংস্করণ।
MySQLi vs PDO
| MySQLi | PDO | |
|---|---|---|
| Database | শুধু MySQL | ১২টি DB |
| API | OOP + Procedural | শুধু OOP |
| Named Params | ❌ | ✅ |
Connection (OOP) ⭐
<?php
$conn = new mysqli("localhost", "root", "", "shop_db");
if ($conn->connect_error) {
die("সংযোগ ব্যর্থ: " . $conn->connect_error);
}
$conn->set_charset("utf8mb4"); // বাংলা সমর্থন
echo "সফল";
$conn->close();
?>
Procedural
$conn = mysqli_connect("localhost", "root", "", "shop_db");
if (!$conn) die(mysqli_connect_error());
mysqli_set_charset($conn, "utf8mb4");
Reusable Class
<?php
class DB {
private static $instance = null;
private $conn;
private function __construct() {
$this->conn = new mysqli("localhost", "root", "", "shop_db");
if ($this->conn->connect_error) {
throw new Exception($this->conn->connect_error);
}
$this->conn->set_charset("utf8mb4");
}
public static function getInstance(): self {
if (self::$instance === null) self::$instance = new self();
return self::$instance;
}
public function getConnection(): mysqli {
return $this->conn;
}
}
$conn = DB::getInstance()->getConnection();
?>
Error Handling
try {
$conn = new mysqli("localhost", "root", "", "shop_db");
if ($conn->connect_error) throw new Exception($conn->connect_error);
$conn->set_charset("utf8mb4");
} catch (Exception $e) {
error_log("DB: " . $e->getMessage());
http_response_code(500);
die(json_encode(["error" => "DB সমস্যা"]));
}
Useful Properties
$conn->server_info // MySQL version $conn->affected_rows // শেষ query এ প্রভাবিত $conn->insert_id // শেষ AUTO_INCREMENT id $conn->error // error message $conn->errno // error code