在我重写PDO之前,我为我的网站创建了一个搜索功能。对于使用MySQL数据库而言,我对PHP和PDO都是一个非常新的东西,我不知道如何将这段代码翻译成PDO。我很感激有人稍微跟我说话,以帮助我学习。
我目前的代码是:
function doSearch() {
$output = '';
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM entries WHERE name LIKE '%$searchq%' or description LIKE '%$searchq%' or content LIKE '%$searchq%'";
$query = mysqli_query($connect, $sql);
$count = mysqli_num_rows($query);
if($count == 0) {
$output = '<tr><tr>No results found.</tr></td>';
} else {
while($row = mysqli_fetch_array($query)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td><a href="http://xxxx.com/xxx?id=' .$id. '" onclick="document.linkform.submit();">'.$eName.'</a></td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}
return $output;
}
}
已经建立了PDO连接,似乎是成功的。这是在我的functions.php文件中,我的connection.php文件已附加到functions.php。
提前致谢!
答案 0 :(得分:1)
应该是
$conn='';
try {
$conn = new PDO('mysql:host=localhost;dbname=xxx', 'xxx', 'xxx');
}
catch (PDOException $e) {
exit('Database error.');
}
$sql = "SELECT * FROM entries WHERE name LIKE :searchq or description LIKE :searchq or content LIKE :searchq";
$stmt = $conn->prepare($sql);
$stmt->bindParam(":searchq",$searchq,PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
if($count == 0) {
$output = '<tr><tr>No results found.</tr></td>';
} else {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$eName = $row['name'];
$eDesc = $row['description'];
$eCont = $row['content'];
$id = $row['id'];
$elvl = $row['level'];
$ehp = $row['hp'];
$output .= '<tr><td><a href="http://xxxx.com/xxx?id=' .$id. '" onclick="document.linkform.submit();">'.$eName.'</a></td><td>'.$eDesc.'</td><td>'.$elvl.'</td><td>'.$ehp.'</td></tr>';
}
}