wawan Setiyawan wawan Setiyawan - 1 month ago 5
PHP Question

show num_rows and fetch assoc in prepared statment

i tried this query many many times. but, it's still error. i'm confused . please help it :



<?php
$sql = $db->prepare("SELECT nm_bahan FROM bahan WHERE nm_bahan=? ");
$sql->bind_param("s", $_POST['nm_bahan']);
$sql->execute();
$sql->store_result();
$jml = $sql->num_rows;

$result = $sql->get_result();
$data = $result->fetch_assoc();

echo $jml . "<br>" . $data['nm_bahan'];

?>




Answer

Your database returns only one result set. And so you cannot get it twice.

<?php
$sql = $db->prepare("SELECT nm_bahan FROM bahan WHERE nm_bahan=? ");
$sql->bind_param("s", $_POST['nm_bahan']);
$sql->execute();
$result = $sql->get_result();
$data = $result->fetch_assoc();
// I have no idea why you need this useless number but meh
$jml = $result->num_rows;

echo $data['nm_bahan'];