回应PHP预处理语句的最有效方法

时间:2014-09-25 10:41:20

标签: php html mysql sql prepared-statement

我有一个SQL查询,为了安全起见,我最近将其转换为准备好的语句。我有一个返回许多行的查询,每行包含许多列。我的问题是如何使用while循环回显结果。我到目前为止的例子:

$stmt = $conn->prepare("SELECT * FROM Customers 
                                  WHERE travel_Date >= ?
                                  AND   travel_Date <= ?
                                  ".$searchOption."
                                  LIMIT ? 
                                  OFFSET ?");
$todayDateFrom = $todayDate." 00:00:00";
$todayDateTo = $todayDate." 23:59:59";
$stmt->bind_param("ssii", $todayDateFrom, $todayDateTo, $limit, $offset);
$stmt->execute();

while ($stmt->fetch()) {
    //echo first name
    //echo surname
    //echo address
    //echo number
    //echo type
    //15 other things i need to print off
}

我不确定最好的方法是什么。我想过:

$stmt->bind_result($firstName, $surname, $address, //etc);

但我想知道是否还有另一种类似于毫无准备陈述的替代方案:

while($row = mysqli_fetch_array($query)){
    echo $row['firstName'];
    echo $row['surname'];
    echo $row['address'];
    //etc
}

2 个答案:

答案 0 :(得分:0)

试试这个:

$result = $stmt->get_result();
    while ($row = $result->fetch_array())
    {
        echo $row['firstName'];
        echo $row['surname'];
        echo $row['address'];
    }

答案 1 :(得分:0)

试试这个 -

$result_arr = array();
while($row = $stmt->fetch()){
  $record = array();
  $record['firstname'] = $row['firstname']; // if your db column contains firstname column other wise you can also use $row[0];
  $record['name'] = $row[1]; // end so on .......
  $result_arr[] = $record;
}

希望这对你有用......