Database connection in PHP

Database connection in PHP

To connect to a database using PHP, you can use the mysqli or PDO extensions. Here’s an example using mysqli:

// Database credentials
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

In this example, replace localhost with the hostname or IP address of your database server, username and password with the credentials to authenticate with the database, and database_name with the name of the database you want to connect to.

You can then use the $conn variable to execute queries on the database. Don’t forget to close the connection when you’re done:

// Execute a query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);

// Process the results
if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Do something with each row
    }
} else {
    echo "0 results";
}

// Close the connection
$conn->close();

Note that using mysqli directly is not recommended for security reasons. It’s better to use prepared statements to avoid SQL injection attacks. You can also use the PDO extension, which supports multiple databases and has built-in support for prepared statements.

Apply for PHP Certification!

https://www.vskills.in/certification/certified-php-developer

Back to Tutorials

Share this post
[social_warfare]
Changing the Parameter Source
Financial Market, Participants and Instruments

Get industry recognized certification – Contact us

keyboard_arrow_up