PHP Connection To MySQL
Submitted by alpha_luna on Wednesday, May 11, 2016 - 12:08.
PHP Connection To MySQL
If you want to know on How To Create PHP Connection To MySQL then you are at the right place. Which one do you prefer? MySQLi or PDO? In my opinion, it would be whatever you like to use it. MySQli and PDO have their advantages. We have 3 ways to create this in PHP and MySQL. These are:- MySQLi (object-oriented)
- MySQLi (procedural)
- PDO (PHP Data Objects)
Creating Connection To MySQL
Example syntax for MySQLi (Object-Oriented)- <?php
- $servername = "localhost";
- $username = "username";
- $password = "password";
- // Create connection
- $conn = new mysqli($servername, $username, $password);
- // Check connection
- if ($conn->connect_error) {
- }
- echo "Successfully Connected!!!";
- ?>
- <?php
- $servername = "localhost";
- $username = "username";
- $password = "password";
- // Create connection
- // Check connection
- if (!$conn) {
- }
- echo "Successfully Connected!!!";
- ?>
- <?php
- $servername = "localhost";
- $username = "username";
- $password = "password";
- try {
- $conn = new PDO("mysql:host=$servername;dbname=myDB", $username, $password);
- // set the PDO error mode to exception
- $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
- echo "Successfully Connected!!!";
- }
- catch(PDOException $e)
- {
- echo "Connection Error. Check your syntax." . $e->getMessage();
- }
- ?>
To Close The Connection To MySQL
Syntax MySQLi (Object-Oriented)$conn->close();
MySQLi (Procedural)
mysqli_close($conn);
PDO (PHP Data Objects)
$conn = null;
But if you ask me which I prefer to use, my answer would be PDO (PHP Data Objects).
I have a syntax to use this to have a connection to MySQL. And to make it simple and short, and easy to remember. This is the syntax:
- <?php
- $conn = new PDO("mysql:host=localhost;dbname=myDB", 'username', 'password');
- ?>
Comments
Add new comment
- Add new comment
- 854 views