Reputation: 181
I have a php script doing a search record from mysql database, how can i add a count for total query return from mysql? eg. i search "ABC", total search results are 3, i want to display this after the search "total search found: 3". Have been trying below code so far and not making any good progress, anyone can can assist? Thanks
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'stock');
define('DB_CHARSET', 'utf8mb4');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
try
{
$pdo = new PDO("mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET . ";dbname=" . DB_NAME, DB_USER, DB_PASSWORD, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC, PDO::ATTR_EMULATE_PREPARES => false]);
}
catch(Exception $ex)
{
die($ex->getMessage());
}
$stmt = $pdo->prepare("SELECT * FROM `data` WHERE `Name` LIKE ? OR `shopfront_signage` LIKE ? ");
$stmt->execute(["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]);
$results = $stmt->fetchAll();
if (isset($_POST['ajax']))
{
echo json_encode($results);
}
//$resultscount= $results[0];
//echo $resultscount;
$query = mysqli_query($stmt);
$resultrow = mysqli_num_rows($query);
echo 'Total search found: ' . $resultrow;
?>
Upvotes: 0
Views: 415
Reputation: 370
$count = $stmt ->rowCount();
I'd put this directly under the execute.
Upvotes: 2
Reputation: 33375
Just use count()
, e.g.
echo 'Total search found: ' . count($results);
Upvotes: 0