How to get data from a database in PHP?

Member

by brisa , in category: PHP , 2 years ago

I am working on a simple blog project and I am using MySQL database and PDO driver to connect using PHP, how can I get data by a slug from a database in PHP, here is my connection and SQL query below:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
<?php

$dbName = "blog";
$username = "root";
$password = "root";

$conn = new PDO(
    "mysql:host=localhost;dbname=${dbName}",
    $username,
    $password
);

// Select * from post where slug = 'first-page'
Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

Member

by bettie , 2 years ago

@brisa you can use prepare statement to execute and get data from a database in PHP, your final code:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<?php

$dbName = "blog";
$username = "root";
$password = "root";

$conn = new PDO(
    "mysql:host=localhost;dbname=${dbName}",
    $username,
    $password
);

// prepare SQL statement
$stmt = $conn->prepare("
    Select * from blog 
    where slug = 'first-page';
");

// execute sql query
$stmt->execute();

// get result data as associated array
$result = $stmt->fetch(PDO::FETCH_ASSOC);

print_r($result);
by rachelle_funk , 7 months ago

@brisa 

The code you provided is almost correct. However, there is a small mistake in the SQL statement. You need to replace "blog" with "post" as you mentioned in your comment. Here is the corrected code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
prepare("
        SELECT * FROM post
        WHERE slug = :slug;
    ");
    
    // bind parameter
    $stmt->bindParam(':slug', $slug);
    
    // execute sql query
    $stmt->execute();
    
    // get result data as associated array
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    
    print_r($result);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}
?>


In this code, I added an exception handling block to catch any connection errors. Also, I used a bind parameter to prevent SQL injection by binding the value of $slug to the :slug placeholder. You can change the value of $slug variable to get the desired record from the database.