Database Connectivity in PHP

 Database Connectivity in PHP


PHP can be used to connect to databases and perform database operations such as inserting, updating, and retrieving data.

Example:


php


// connect to a database

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "mydb";

$conn = mysqli_connect($servername, $username, $password, $dbname);


// insert data into a database

$sql = "INSERT INTO users (name, email) VALUES ('John', 'john@example.com')";

if (mysqli_query($conn, $sql)) {

    echo "Record inserted successfully";

}


// retrieve data from a database

$sql = "SELECT * FROM users";

$result = mysqli_query($conn, $sql);

while ($row = mysqli_fetch_assoc($result)) {

    echo $row["name"] . " - " . $row["email"] . "<br>";

}


// update data in a database

$sql = "UPDATE users SET email='newemail@example.com' WHERE id=1";

if (mysqli_query($conn, $sql)) {

    echo "Record updated successfully";

}


// close the database connection

mysqli_close($conn);

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...