user4747366
user4747366

Reputation:

Returning Number of Rows in mySQL Using Prepared Statements

I'm just starting to learn prepared statements for returning data from mySQL. I'm trying to get a count of rows that are returned when a query runs and display the row count however when I run the following not only does it not return the number of rows but it doesn't show the rest of the html code after the end of the php tag either.

  <ul class="list-group">
<li class="list-group-item list-group-item-success">Currently Open: 
<?php require('db/config/mysql_connect.php'); 

$query = "SELECT * from ost_ticket WHERE status_id = 1";
if ($stmt = $mysqli->prepare($query)) {

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

    /* store result */
    $stmt->store_result();

    printf($stmt->num_rows);

    /* close statement */
    $stmt->close();
}

/* close connection */
$mysqli->close();


?>
<strong> Tickets</strong> | Opened Today:
<?php



?>
<strong> Tickets </strong>| Closed Today: <strong>### Tickets</strong></li></ul>

Upvotes: 2

Views: 1062

Answers (2)

Norukh
Norukh

Reputation: 364

If you only want to display the number of rows, you can simply replace your query with this:

$query = "SELECT count(*) from ost_ticket WHERE status_id = 1";

With this query you display the number of rows from the table ost_ticketwhich is the table you're looking for.

Upvotes: 4

Jeff Cashion PhD
Jeff Cashion PhD

Reputation: 674

The Printf function is expecting a format string, then the arguments. You have only passed in one argument, so it is likely that the printf function is failing and killing your php.

In your php where you presently have the printf statement, replace it with the following:

$numResults = $stmt->num_rows;

And down in your html, where you want to display the number of rows, place:

<?php print $numResults ?>

Upvotes: 2

Related Questions