php - Calling PDO inside a Function -
i following project creating spell checker. however, rather using regular mysql, decided go pdo. converted code pdo. stuck @ 1 point , not sure why can't call pdo inside function after declaring global variable. doing wrong?
purpose: have loaded 100k+ words in table , want find similar words searching 1 word.
<?php include "db.inc.php"; function spellcheck($word){ global $db; $output = array(); $word = $db->quote($word); $words = $db->prepare("select words english 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 check: <input type="text" name="word"> <input type="submit" value="check"> </form>
try following:
function spellcheck($word){ $db = new pdo ("mysql:host=localhost;dbname=splcheck", "root", ""); $db->setattribute(pdo::attr_errmode, pdo::errmode_exception ); $query = "select words english 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; } - don't use global, pass connection argument instead
- make sure prepare query properly
- your function not returning output
- remove
!== falsewhile loop redudant - avoid typos forgot
son$words_row['words'];
using statement:
$query = "select `words` english `word` = :word"; $stmt = $db->prepare($query); $stmt->execute(array(':word'=>'%'.$word.'%'));
Comments
Post a Comment