![](/img/trans.png)
[英]Php mysql search script, how to make single searched words bold if the search term wasn't the exact match to my database entry
[英]The searched words are not registered correctly in my database
我正在嘗試在數據庫中注冊用戶在我的網站上搜索的單詞。
想法如下:如果搜索到的單詞與數據庫中已經注冊的單詞匹配,我只需在搜索單詞的次數上加1。 如果在我的搜索表中找不到該詞,則將一個新詞添加到表中。
問題是我要查找一個單詞,如果該單詞已在我的表中注冊,請用您要查找的單詞的名稱修改所有記錄,並將數量增加一。 例如:我有兩個寄存器,單詞1和單詞2,如果我搜索單詞1,它返回,它將用單詞1的名稱更新兩個單詞,並用單詞1的數量更新。
我表格的字段是id,單詞和金額
我的代碼中的問題出在哪里?
我共享僅對控制器進行調用的部門,然后共享有關控制器和模型的所有信息
search.php
$response= SearchController::ctrNewSearch($word);
search.controller.php
<?php
class SearchController{
public function ctrNewSearch($word){
$table = "searchs";
$response = SearchModel::mdlShowSearchs($table);
$foundWord = 0;
$amount= "1";
foreach ($response as $key => $value) {
if ($value["word"] == $word) {
$foundSearch= 1;
$id = $value["id"];
$updatedAmount= $value["amount"] + 1;
}
}
if ($foundWord == 1){
$response1= SearchModel::mdlUpdateSearch($table, $word, $id, $updatedAmount);
return $response1;
} else {
$response0 = SearchModel::mdlAddSearch($table, $word, $amount);
return $response0;
}
}
}
search.model.php
<?php
require_once "conection.php";
class SearchModel{
static public function mdlShowSearchs($table){
$stmt = Conexion::conectar()->prepare("SELECT * FROM $table");
$stmt -> execute();
return $stmt -> fetchAll();
$stmt -> close();
$tmt =null;
}
static public function mdlAddSearch($table, $word, $amount){
$stmt = Conexion::conectar()->prepare("INSERT INTO $table (word, amount) VALUES (:word, :amount)");
$stmt->bindParam(":word", $word, PDO::PARAM_STR);
$stmt->bindParam(":amount", $amount, PDO::PARAM_INT);
if($stmt->execute()){
return "ok";
}else{
return "error";
}
$stmt->close();
$tmt =null;
}
static public function mdlUpdateSearch($table, $word, $id, $updatedAmount){
$stmt = Conexion::conectar()->prepare("UPDATE $table SET word = :word, amount = :amount WHERE $id = :id");
$stmt->bindParam(":word", $word, PDO::PARAM_STR);
$stmt->bindParam(":amount", $updatedAmount, PDO::PARAM_INT);
$stmt->bindParam(":id", $id, PDO::PARAM_INT);
if($stmt -> execute()){
return "ok";
}else{
return "error";
}
$stmt -> close();
$stmt = null;
}
}
對於每個循環都存在問題,如果條件不是檢查而是分配總是正確的。 更新查詢應該在for循環中,並且如果發現單詞,則$ foundword變量每次將其分配為0。 我進行了一些更改,請嘗試一下並嘗試解決是否存在語法問題。
public function ctrNewSearch($word){
$table = "searchs";
$response = SearchModel::mdlShowSearchs($table);
$foundWord = 0;
$amount= "1";
foreach ($response as $key => $value) {
if ($value["word"] == $word) {
$foundWord = 1;
$id = $value["id"];
$updatedAmount= $value["amount"] + 1;
}
if ($foundWord == 1){
$response1= SearchModel::mdlUpdateSearch($table, $word, $id, $updatedAmount);
$foundWord = 0;
return $response1;
} else {
$response0 = SearchModel::mdlAddSearch($table, $word, $amount);
return $response0;
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.