I am trying to register in my database, the words that the user searches on my website.
The idea is the following: If the searched word matches one already registered in my database, I simply add 1 to the number of times the word was searched. If the word is not found in my search table, I add a new word to my table.
The problem is what do I look for a word, if it is registered in my table, modify all the records with the name of the word you are looking for and increase the quantities by one. For example: I have two registers, word 1 and word 2, if I search for word 1 it returns, it updates the two words with the name of the word 1 and the quantities with the word 1
The fields of my table are the id, the word and the amount
Where is the problem in my code?
I share the sector where the call is made to the controller only, and then everything about the controller and the model
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;
}
}