PHP Connect to MySQL

🔗 PHP Connect to MySQL Tutorial

Connecting PHP to a MySQL database is the first step for any dynamic web application. You can use mysqli (procedural or object-oriented) or PDO.


1️⃣ Using mysqli (Procedural)


 

  • $servername → Database host (usually localhost)

  • $username → MySQL username (default: root)

  • $password → MySQL password

  • $dbname → Name of your database

mysqli_connect_error() returns the error message if connection fails.


2️⃣ Using mysqli (Object-Oriented)


 

  • $conn->connect_error returns the connection error.

  • $conn object is used to execute queries later.


3️⃣ Using PDO (PHP Data Objects)

PDO provides flexible and secure database access and supports multiple databases.


 

✅ PDO is preferred for prepared statements and database flexibility.


4️⃣ Closing the Connection

  • mysqli procedural:


 

  • mysqli object-oriented:


 

  • PDO: Automatically closed when $conn variable goes out of scope.


5️⃣ Key Points

  1. Check connection errors using mysqli_connect_error() or PDOException.

  2. Use mysqli for MySQL-specific applications.

  3. Use PDO for secure, flexible, and multi-database applications.

  4. Always close the connection after finishing database operations.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *