MYSQLphp

How to connect mysql,mysqli,PDO

If You want to access to Mysql database using all programming languages on the server then you can connect MySQL database server. Mysql provides two types Mysql or Mysqli and PDO.

Connecting to a MySQL database is a fundamental skill for PHP developers. Two commonly used methods for establishing a connection to a MySQL database are MySQLi (MySQL Improved) and PDO (PHP Data Objects). In this blog post, we’ll explore how to connect to MySQL using both MySQLi and PDO in PHP.

Connecting with MySQLi:

MySQLi is a PHP extension that provides an object-oriented interface to interact with MySQL databases. To connect to a MySQL database using MySQLi, follow these steps:

  1. Open a PHP script: Start by creating a PHP script where you will write the code for connecting to the MySQL database.
  2. Establish the connection: Use the mysqli_connect() function to create a connection to the MySQL server. You’ll need to provide the server hostname, username, password, and database name as arguments to this function.

PDO stands for PHP data object. PDO is only object-oriented and allows a number of different database type that use PHP.

PHP 5.4 version or below we use mysql_connect and now we use mysqli_connect() or PDO.

Introduction:

When it comes to working with databases in PHP, MySQL is a popular choice. To interact with MySQL databases, you have several options, including MySQL, MySQLi (MySQL Improved), and PDO (PHP Data Objects). In this blog post, we’ll walk you through the process of connecting to a MySQL database using both MySQLi and PDO, highlighting the key differences and advantages of each approach.

Connecting to MySQL using MySQLi

MySQLi is a PHP extension that provides an object-oriented and procedural interface for interacting with MySQL databases. It offers better security and performance compared to the older MySQL extension.

<?php
$host="localhost";
$user="root";
$pwd="password";
$conn = mysql_connect($host,$user,$pwd) or die("Server unavailable");
mysql_select_db("database");
$result = mysql_query("SELECT emp_name FROM employee_master");
$row = mysql_fetch_assoc($result);
echo htmlentities($row['emp_name']);
?>
<?php
$con = mysqli_connect("localhost","root","password","database");

// Check connection
if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  exit();
}
$mysqli = new mysqli("localhost", "root", "password", "database");
$result = $mysqli->query("Select emp_name FROM employee_master");
$row = $result->fetch_assoc();
echo htmlentities($row['emp_name']);
?>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=database', 'root', 'password');
$statement = $pdo->query("SELECT emp_name FROM employee_master");
$row = $statement->fetch(PDO::FETCH_ASSOC);
echo htmlentities($row['emp_name']);
?>

Related Articles

Leave a Reply

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

Back to top button