php - Prepared Statement, Fails when re-used -
i have code, works fine when looped through once.
<!-- language: php --> <?php $query = "select username users user_id = ? limit 1"; $stmt = $con->prepare($query) or die(mysqli_error($con)); $stmt->bind_param("s", $user_id); $stmt->execute(); $stmt->store_result(); $stmt->bind_result($username); ?>
when call first time on page, loads fine , data shows should.
<!-- language: php --> <?php // 1 works fine. while ($stmt->fetch()){ echo 'welcome '.$username; } ?>
if want re-use same query somewhere else, fails wihtout errors. doing wrong? correct way re-use same query multiple time on same page, since data same, don't want re-query db each time.
<!-- language: php --> <?php // when re-used somewhere else on page, fails. nothing shows. while ($stmt->fetch()){ echo 'welcome '.$username; } ?>
fetch
returns 1 row after another. once fetch rows, further call fetch()
method return false
.
you need re-execute()
query in order same result again. go call database again though. if want cache result, need put in-memory cache / global variable / whatever prefer.
if want beginning of result set again, can use mysqli_data_seek()
this:
mysqli_data_seek($stmt, 0); while ($stmt->fetch()){ echo 'welcome '.$username; }
Comments
Post a Comment