MySQL Connect

PHP offers multiple methods to connect to a MySQL database, each with its own features and use cases. Below are the primary methods for connecting PHP to MySQL:


  • MySQLi extension (the "i" stands for improved)
  • PDO (PHP Data Objects)


1. MySQLi (MySQL Improved Extension)


MySQLi is a modern, improved extension for working with MySQL databases in PHP. It supports both procedural and object-oriented approaches.

Example - Procedural Style
<?php
$host = "localhost";
$username = "root";
$password = "";
$dbname = "my_database";

// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);

// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}

echo "Connected successfully";

mysqli_close($conn);
?>

Example - Object-Oriented Style

<!DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<body>


<h1>This is a Heading</h1>

<p>This is a paragraph.</p>


</body>

</html>

Advantages of MySQLi:


  • Offers both procedural and object-oriented styles.
  • Allows multiple statements in a single query.


2. PDO (PHP Data Objects)


PDO is a database abstraction layer that supports multiple database types (not just MySQL). It's a great choice if your project might need to switch between databases in the future.



Example

<!DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<body>


<h1>This is a Heading</h1>

<p>This is a paragraph.</p>


</body>

</html>

Advantages of PDO:


  • Supports over 12 different database systems (e.g., PostgreSQL, SQLite).
  • Allows easy error handling using exceptions.

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.