Sunday, May 14, 2023

PHP MySQL Connect to database

To connect to a MySQL database using PHP, you can use the `mysqli` extension or the older `mysql` extension (deprecated in PHP 5.5 and removed in PHP 7). Here's an example using the `mysqli` extension:


<?php

$servername = "localhost";

$username = "your_username";

$password = "your_password";

$database = "your_database";

// Create connection

$conn = new mysqli($servername, $username, $password, $database);

// Check connection

if ($conn->connect_error) {

    die("Connection failed: " . $conn->connect_error);

}

echo "Connected successfully";

// Perform database operations here

// Close the connection

$conn->close();

?>

In the code above, you need to replace `your_username`, `your_password`, and `your_database` with your actual MySQL database credentials.


Once the connection is established, you can perform various database operations using the `$conn` object. For example, you can execute SQL queries, fetch data, insert records, update records, and more.


Remember to handle errors appropriately in your code. The example above shows a basic error handling approach by using `die()` to terminate the script and display an error message if the connection fails. In a production environment, you may want to handle errors more gracefully and log them instead of displaying them directly to users.


Note: It's important to ensure that you're using secure practices when dealing with database connections. Avoid using plain text passwords, and consider using prepared statements or parameterized queries to prevent SQL injection attacks.

Previous Post
Next Post

post written by:

0 Comments: