0

This solution is working, but I am not sure if it is optimal & safe. I am 100% PHP newbie and not sure if I am needed to use PDO connection but I read somewhere that PDO is the safest way so I started with that.

config.php

<?php
    define('USER', '');
    define('PASSWORD', '');
    define('HOST', '');
    define('DATABASE', '');
    try {
        $connection = new PDO("mysql:host=".HOST.";dbname=".DATABASE, USER, PASSWORD);
    } catch (PDOException $e) {
        exit("Error: " . $e->getMessage());
    }
?>

index.php (there i want to display the total users)

<?php
include 'includes/config.php';
$stmt = $connection->query('SELECT * FROM users');
$row_count = $stmt->rowCount();
<?
...
HTML CODE
...
    
    <p> <?php echo $row_count; ?> </p>
aa1987ulu
  • 1
  • 2
  • 1
    Your code is fine. You should use `prepared statements` while dealing with user inputs. – Indra Kumar S Jun 13 '21 at 02:42
  • 1
    To get the count of records in SQL there's the `count()` aggregation function. You should consider to use that instead, like `SELECT count(*) FROM users`. This promises to be way more efficient. This question however doesn't really fit here. It should better be deleted here and posted at [Code Review](https://codereview.stackexchange.com/) instead. – sticky bit Jun 13 '21 at 02:45
  • I would use a `SELECT COUNT(*) FROM users` query and `$stmt->fetchColumn()` to get the result – Phil Jun 13 '21 at 03:05
  • Does this answer your question? [Row count with PDO](https://stackoverflow.com/questions/883365/row-count-with-pdo) – Phil Jun 13 '21 at 03:05
  • Looks fine to me – Strawberry Jun 13 '21 at 05:29

0 Answers0