更改查询以使用绑定参数和预准备语句

时间:2015-11-04 08:20:10

标签: php mysql data-binding pdo

我正在运行一个带有查询的php脚本,它通过回声循环一些html,其中包含嵌入其中的数据库的信息。我想知道如何编写它以便它使用预处理语句和bind_param()...

<?php
               mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
               error_reporting(E_ALL);
               ini_set("display_errors", 1);
               // error reporting is now turned on

               require_once 'dbconfig.php';

               try {
                   $mysqli= new mysqli($host, $username, $password, $dbname); 
                   if ($mysqli->connect_error) {
                       die('Connect Error (' . $mysqli->connect_errno . ') '
                           . $mysqli->connect_error);
                    }
                }
                catch (mysqli_sql_exception $e) { 
                    throw $e; 
                } 

                if($_POST['food'] == "No") {
                    $sql = "SELECT name, description FROM pubs WHERE food LIKE '%Yes%' OR food LIKE '%No%'";
                }
                else {
                    $sql = "SELECT name, description FROM pubs WHERE food LIKE '%Yes%'";
                }

                $result = $mysqli->query($sql);

                while ($row = $result->fetch_assoc()) {
                    if($row["name"] != "name" && $row["description"] != "description") {
                       echo
                       "<div class='col-sm-4 col-lg-4 col-md-4'>
                           <div class='thumbnail'>
                               <img src='images/mug-icon.png' alt=''>
                               <div class='caption'>
                                   <h4><a href='#'>" . $row["name"] . "</a>
                                   </h4>
                                   <p>" . substr($row["description"],0, 175) . "...</p>
                               </div>
                               <div class='ratings'>
                                   <p>
                                       <span class='glyphicon glyphicon-star'></span>
                                       <span class='glyphicon glyphicon-star'></span>
                                       <span class='glyphicon glyphicon-star'></span>
                                       <span class='glyphicon glyphicon-star'></span>
                                       <span class='glyphicon glyphicon-star'></span>
                                   </p>
                               </div>
                           </div>
                       </div>";
                     }
                }
                $mysqli->close();
               ?>

0 个答案:

没有答案