function konek() {
return new PDO('mysql:host=localhost;dbname=payroll;port=3306', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
}
$pdo = konek();
$keyword = $_POST['keyword'];
$sql = "SELECT * FROM karyawan WHERE noreg LIKE '%:keyword%' OR nama LIKE '%:keyword%' ORDER BY noreg ASC LIMIT 0, 10";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, PDO::PARAM_STR);
$query->execute();
$daftar = $query->fetchAll();
foreach ($daftar as $kar) {
echo '<li>'.$kar['noreg'].'||'.$kar['nama'].'</li>';
}
?>
我的代码有问题吗?
答案 0 :(得分:4)
尝试更改您使用预准备语句将%%包含在bindParam方法中的方式,而不是查询:
$sql = "SELECT * FROM karyawan WHERE noreg LIKE :keyword OR nama LIKE :keyword ORDER BY noreg ASC LIMIT 0, 10";
然后
$query->bindParam(':keyword', '%'.$keyword.'%', PDO::PARAM_STR);
答案 1 :(得分:1)
您必须在%
中添加bindParam
个符号,而不是在查询中:
$sql = "SELECT * FROM karyawan WHERE noreg LIKE :keyword OR nama LIKE :keyword ORDER BY noreg ASC LIMIT :start, :end";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', '%'.$keyword.'%', PDO::PARAM_STR);
$query->bindParam(':start', 0, PDO::PARAM_INT);
$query->bindParam(':end', 10, PDO::PARAM_INT);