PHP : MySQL Database

Working with MySQL databases in PHP involves several steps, including establishing a connection, executing queries, fetching results, and handling errors. Here's a basic guide on how to interact with a MySQL database using PHP:

Step 1: Establish a Database Connection

To connect to a MySQL database in PHP, you typically use the mysqli or PDO (PHP Data Objects) extension. Here's an example using mysqli :

Using `mysqli`:


// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

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

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

echo "Connected successfully";
 

Using PDO:


// Database credentials
$servername = "localhost";
$username = "your_username";
$password = "your_password";
$database = "your_database";

try {
    $conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    echo "Connected successfully";
} catch (PDOException $e) {
    die("Connection failed: " . $e->getMessage());
}

 

Step 2: Executing SQL Queries

Once the connection is established, you can execute SQL queries to interact with the database. Here are examples of basic queries:

Select Query:


$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // Output data of each row
    while ($row = $result->fetch_assoc()) {
        echo "Name: " . $row["name"] . " - Email: " . $row["email"] . "<br>";
    }
} else {
    echo "0 results";
}

 

Insert Query:


$name = "John";
$email = "john@example.com";

$sql = "INSERT INTO users (name, email) VALUES ('$name', '$email')";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . $conn->error;
}

 

Step 3: Prepared Statements (Recommended for Security)

To prevent SQL injection attacks, it's recommended to use prepared statements with placeholders. Here's an example:

Using Prepared Statements:


$name = "John";
$email = "john@example.com";

// Prepare a statement
$stmt = $conn->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->bind_param("ss", $name, $email);

// Execute the statement
if ($stmt->execute()) {
    echo "New record created successfully";
} else {
    echo "Error: " . $stmt->error;
}

$stmt->close();
 

Step 4: Closing the Connection

After you're done with the database operations, close the connection to free up resources:


$conn->close(); // For mysqli
// OR
// $conn = null; // For PDO

 

Error Handling

It's important to handle errors properly, especially when dealing with database operations:


if (!$result) {
    die("Query failed: " . $conn->error);
}

 

Summary:

  • Establish Connection: Use mysqli or PDO to connect to the MySQL database.
  • Execute Queries: Use query() for simple queries and prepared statements for security.
  • Fetch Results: Use methods like fetch_assoc() to retrieve data.
  • -Close Connection: Always close the connection when done.