Lecture 19 - PHP Connect To MySQL
Lecture 19 - PHP Connect To MySQL
Connect to MySQL
• // Create connection
• $conn = new mysqli($servername, $username, $password);
• // Check connection
• if ($conn->connect_error) {
• die("Connection failed: " . $conn->connect_error);
• }
• echo "Connected successfully";
• ?>
Example (MySQLi Procedural)
• <?php
• $servername = "localhost";
• $username = "root";
• $password = "";
• // Create connection
• $conn = mysqli_connect($servername, $username, $password);
• // Check connection
• if (!$conn) {
• die("Connection failed: " . mysqli_connect_error());
• }
• echo "Connected successfully";
• ?>
Close the Connection
• The connection will be closed automatically
when the script ends. To close the connection
before, use the following:
• MySQLi Object-Oriented:
• $conn->close();
• MySQLi Procedural:
• mysqli_close($conn);