简体   繁体   中英

mysqli prepared statement bind result and loop

I have this code in purpose to search in the database :

$key = '%'.$_GET['key'].'%';
$result= $db->prepare("SELECT * FROM information WHERE stuId LIKE ? 
                                            OR stuName LIKE ? LIMIT ?,10");
$result->bind_param('ssi',$key,$key,$startpage);
$result->execute();
$result->bind_result($stuId,$stuName,$date,$stuSex,$stuAdd);
while($result->fetch()) {
    $stuDoB= $date->format('d/m/Y');
    echo "<tr>
              <td class='col1'>
                  <div>$stuId</div>
              </td>
              <td>
                  <div><a href='editStudent.php?stuId=$stuId'>" . htmlspecialchars($stuName) . "</a></div>
              </td>
              <td class='col3'>
                 <div>$stuDoB</div>
              </td>
              <td class='col4'>
                 <div>$stuSex</div>
              </td>
              <td class='col5'>
                 <div>" . htmlspecialchars($stuAdd) . "</div>
              </td>
            </tr>";
}

Im trying to learn prepared statement, so I change from normal way to above code Could you tell me :

  • Do I have to bind_result inside the $result->fetch() or just 1 time bind_result() outside the loop?
  • Is there any problem with my code ? It's always give an empty row result with any $key and a fatal error : Fatal error: Call to a member function format() on a non-object in D:\\xampp\\htdocs\\baiTapLon\\showPage.php on line 30

Line 30 is $stuDoB= $date->format('d/m/Y');

Please help me out.

  • Do I have to bind_result inside the $result->fetch() or just 1 time bind_result() outside the loop?

You have to use bind_result once means outside the loop

  • Is there any problem with my code ? It's alway give an empty row result with any $key and a fatal error : "Fatal error: Call to a member function format() on a non-object in D:\\xampp\\htdocs\\baiTapLon\\showPage.php on line 30"

You can't use format for any variable use it like this

$date1 = new DateTime($date);
$stuDoB= $date1->format('d/m/Y');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM