Connecting to MySQL
- PHP installed (via XAMPP, WAMP, or LAMP)
- MySQL server running
- A database (e.g., testdb) and user credentials
1. Using MySQLi (Object-Oriented Style)
<?php $host = "localhost"; $username = "root"; $password = ""; $database = "testdb"; // Create connection $conn = new mysqli($host, $username, $password, $database); // Check connection if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "Connected successfully!"; ?>
2. Using MySQLi (Procedural Style)
<?php $conn = mysqli_connect("localhost", "root", "", "testdb"); if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "Connected successfully!"; ?>
3. Using PDO (PHP Data Objects)
<?php $host = "localhost"; $db = "testdb"; $user = "root"; $pass = ""; try { $pdo = new PDO("mysql:host=$host;dbname=$db", $user, $pass); $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); echo "Connected successfully!"; } catch (PDOException $e) { echo "Connection failed: " . $e->getMessage(); } ?>
Method | Description |
---|---|
MySQLi | MySQL Improved, supports OO + procedural |
PDO | Flexible, supports multiple DB systems |
Best Use | PDO (for secure and scalable apps) |
Quickly Find What You Are Looking For
OnlineTpoint is a website that is meant to offer basic knowledge, practice and learning materials. Though all the examples have been tested and verified, we cannot ensure the correctness or completeness of all the information on our website. All contents published on this website are subject to copyright and are owned by OnlineTpoint. By using this website, you agree that you have read and understood our Terms of Use, Cookie Policy and Privacy Policy.