mukeshdak

2025-09-29_print a table with PDO

Sep 28th, 2025
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.23 KB | None | 0 0
  1. // Database connection by using PHP PDO
  2. require_once("../config/db.php");
  3. // File containing database connection credentials.
  4. try {
  5.     $dbh = new PDO("mysql:host=" . DB_HOST . ";dbname=" . DB_NAME, DB_USER, DB_PASS);
  6. } catch (PDOException $e) {
  7.     exit("Error: " . $e->getMessage());
  8. }
  9.  
  10. // using this handler above.  
  11.     // Get the userid
  12.     $userid = intval($_GET['id']);
  13.     $sql = "SELECT FirstName,LastName,EmailId,ContactNumber,Address,PostingDate,id from tblusers where id=:uid";
  14.     //Prepare the query:
  15.     $query = $dbh->prepare($sql);
  16.     //Bind the parameters
  17.     $query->bindParam(':uid', $userid, PDO::PARAM_STR);
  18.     //Execute the query:
  19.     $query->execute();
  20.     //Assign the data which you pulled from the database (in the preceding step) to a variable.
  21.     $results = $query->fetchAll(PDO::FETCH_OBJ);
  22.        
  23.     if ($query->rowCount() > 0)
  24.     {
  25.       //In case that the query returned at least one record, we can echo the records within a foreach loop:
  26.       foreach ($results as $result)
  27.       {
  28.         // Print the rows.
  29.         echo "<br>";
  30.         echo htmlentities($result->FirstName);
  31.         echo htmlentities($result->LastName);
  32.       }
  33.     } else {
  34.         echo "No rows returned.";
  35.     }
Tags: php mysql
Advertisement
Add Comment
Please, Sign In to add comment