PHP Database Connectivity

 To connect to a database using PHP, you can use the PHP Data Objects (PDO) extension or the MySQLi extension. Here are the basic steps for connecting to a MySQL database using each of these extensions:

Using PDO:

  1. Create a new PDO object with the database connection details:
php
$db = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

Replace "mydatabase", "username", and "password" with your actual database name, username, and password.

  1. (Optional) Set the error mode to throw exceptions for any errors:
php
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  1. Use the PDO object to execute SQL queries:
bash
$stmt = $db->query('SELECT * FROM mytable');

Using MySQLi:

  1. Create a new MySQLi object with the database connection details:
php
$db = new mysqli('localhost', 'username', 'password', 'mydatabase');

Replace "mydatabase", "username", and "password" with your actual database name, username, and password.

  1. Check for any connection errors:
perl
if ($db->connect_error) { die('Connect Error (' . $db->connect_errno . ') ' . $db->connect_error); }
  1. Use the MySQLi object to execute SQL queries:
bash
$result = $db->query('SELECT * FROM mytable');

Replace "mytable" with the name of your actual table.

Note: It's always a good idea to sanitize user inputs before using them in SQL queries to prevent SQL injection attacks. You can use prepared statements with PDO or MySQLi to achieve this

Comments