从mysqli转换为pdo

时间:2014-11-23 13:16:22

标签: php pdo mysqli

我正在尝试从数据库中获取数组,并将结果设置为变量(在本例中,名为“$ Rate”)。使用mysqli工作的代码是:

//Getting Hire Rate
$Rate = array();
$ratequery = "SELECT HireRate FROM movie WHERE MovieID LIKE '$MovieID'";
$rate = mysqli_query($con, $ratequery)
    or die("Error: ".mysqli_error($con));
while ($row = mysqli_fetch_array($rate, MYSQLI_ASSOC)) {
$Rate[] = $row['HireRate'];
};
mysqli_free_result($rate);

我想使用PDO做同样的事情。我已阅读各种页面,但无法使其正常工作。

2 个答案:

答案 0 :(得分:0)

这不起作用?

$sql = "SELECT HireRate FROM movie WHERE MovieID LIKE '$MovieID'";
foreach ($conn->query($sql) as $row) {
    print $row['HireRate'];
}

http://php.net/manual/en/pdo.query.php

答案 1 :(得分:0)

使用PDO execute方法代替query,因为执行阻止了您SQL attack

$params = array("%$MovieID%");
$stmt = $handle->prepare("SELECT HireRate FROM movie WHERE MovieID LIKE ?");
$stmt->execute($params);
$row = $sql->fetchAll();
foreach($data as $row) {
    $Rate[] = $row['HireRate'];
}