Simple Database Connection using MySQLi OOP and Procedural
OOP Approach
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 $server_name = 'localhost'; $username = 'root'; $password = ''; $db_name = 'carlofontanos'; $conn = new mysqli($server_name, $username, $password, $db_name); if ($conn->connect_error) { die('Connection failed: ' . $conn->connect_error); } $sql = 'SELECT * FROM wp_posts WHERE post_type = "post"'; $result = $conn->query($sql); if ($result->num_rows > 0) { while($row = $result->fetch_object()) { echo 'Post ID: ' . $row->ID. ' - Title: ' . $row->post_title. ' Date Uploaded: ' . $row->post_date. '<br>'; } } else { echo 'No Posts Found'; } $conn->close(); |
Procedural Approach
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 26 | <?php $server_name = 'localhost'; $username = 'root'; $password = ''; $db_name = 'carlofontanos'; $conn = mysqli_connect($server_name, $username, $password, $db_name); if (!$conn) { die('Connection failed: ' . mysqli_connect_error()); } $sql = 'SELECT * FROM wp_posts WHERE post_type = "post"'; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { while($row = mysqli_fetch_object($result)) { echo 'Post ID: ' . $row->ID. ' - Title: ' . $row->post_title. ' Date Uploaded: ' . $row->post_date. '<br>'; } } else { echo 'No Posts Found'; } mysqli_close($conn); |
Do you need help with a project? or have a new project in mind that you need help with?
Contact Me