我正在关注创建拼写检查程序的项目。但是,我决定使用PDO,而不是使用常规的mysql。所以我将代码转换为PDO。我被困在一点,不知道为什么即使在声明全局变量之后我也无法在任何函数内部调用PDO。我做错了什么?
目的:我在表格中加载了100k +单词,想通过搜索一个单词找到相似的单词。
<?php
include "db.inc.php";
function spellcheck($word){
global $db;
$output = array();
$word = $db->quote($word);
$words = $db->prepare("SELECT words FROM english WHERE SUBSTRING(word, 0, 1) = '.substr ($word, 1, 2)'");
$words->execute();
while (($words_row = $words->fetch(PDO::FETCH_ASSOC)) !== false){
echo $words_row['word'];
}
}
if (isset($_GET["word"]) && trim($_GET["word"]) !== null){
$word = $_GET["word"];
$spellcheck = spellcheck($word);
}
?>
<form action="" method="GET">
Please type word to check: <input type="text" name="word">
<input type="submit" value="Check">
</form>
答案 0 :(得分:3)
尝试以下方法:
function spellcheck($word){
$db = new PDO ("mysql:host=localhost;dbname=splcheck", "root", "");
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$query = "SELECT words FROM english WHERE SUBSTRING(word, 0, 1) = :word";
$stmt = $db->prepare($query);
$stmt->execute(array(':word'=> substr ($word, 1, 2)));
$output = array();
while ($words_row = $stmt->fetch(PDO::FETCH_ASSOC)){
$output[] = $words_row['words'];
}
return $output;
}
!== false
其redudant s
$words_row['words'];
的拼写错误
使用like语句:
$query = "SELECT `words` FROM english WHERE `word` = LIKE :word";
$stmt = $db->prepare($query);
$stmt->execute(array(':word'=>'%'.$word.'%'));