Prepared Statements - Number of Rows

后端 未结 4 1580
旧巷少年郎
旧巷少年郎 2021-01-04 06:15

I\'m learning about prepared statements and trying to work with a query that yields multiple rows of results. Right now, I\'m just trying to figure out how to determine the

4条回答
  •  攒了一身酷
    2021-01-04 07:12

    If you are only interested in the row count instead of the actual rows of data, here is a complete query block with a COUNT(*) call in the SELECT clause.

    $conn = new mysqli("host", "user", "pass", "db");
    $stmt = $conn->prepare("SELECT COUNT(*) FROM `table` WHERE id= ?");
    $stmt->bind_param("s", $id);
    $stmt->execute()
    $stmt->bind_result($num_rows)
    $stmt->fetch()
    $num_rows;
    

    Or if you want to know the row count before iterating/processing the rows, one way is to lump the entire resultset (multi-dimensional array) into a variable and call count() before iterating.

    $conn = new mysqli("host", "user", "pass", "db");
    $sql = "SELECT field1, field2, field3
            FROM table
            WHERE id= ?
            ORDER BY id";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("s", $id);
    $stmt->execute();
    $result = $stmt->get_result();
    $resultset = $result->fetch_all(MYSQLI_ASSOC);
    echo "
    Num: " , count($resultset) , "
    "; foreach ($resultset as $row) { echo "
    Row: {$row['field1']} & {$row['field2']} & {$row['field3']}
    "; }

    *I have tested both of the above snippets to be successful on my localhost.

提交回复
热议问题