Query in more than one mysql column with PHP

Asked

Viewed 27 times

0

I do so to make a query in the Mysql database

$keyword = strval($_POST['query']);
    $search_param = "{$keyword}%";
    $conn =new mysqli('xxx', 'xxx', 'xxx' , 'xxx');

    $sql = $conn->prepare("SELECT * FROM empresas WHERE nome LIKE ? or palavras_chave LIKE ?")
    $sql->bind_param("s",$search_param);            
    $sql->execute();
    $result = $sql->get_result();
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
        $countryResult[] = $row["nome"];
        }
        echo json_encode($countryResult);
    }
    $conn->close();

Are you just looking for the name, as I would to also search another column of mysql? For example name and keywords.

  • ("... name LIKE ? AND name = 'something'") is that what you want? I didn’t quite understand the question

1 answer

1

You can add the conditions and and or.

Example:

$sql = $conn->prepare("SELECT * FROM empresas WHERE nome  LIKE ? and palavras-chaves LIKE ?");

or

$sql = $conn->prepare("SELECT * FROM empresas WHERE nome  LIKE ? or palavras-chaves LIKE ?");

The choice will depend on your specific case.

Time to replace the ? by the parameters, make sure to be putting % before and after the value of the varieties.

Example:

SELECT * FROM empresas WHERE nome  LIKE "%$nome%"

try this code:

$keyword = strval($_POST['query']);
$search_param = "%$keyword%";
$conn =new mysqli('xxx', 'xxx', 'xxx' , 'xxx');

$sql = $conn->prepare("SELECT * FROM empresas WHERE nome LIKE ? or palavras_chave LIKE ?")
$sql->bind_param("ss",$search_param, $search_param); 

$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
    $countryResult[] = $row["nome"];
    }
    echo json_encode($countryResult);
}
$conn->close();
  • does not return anything in the search like this

  • edited the question, test again

  • is not returning anything in the search, I am doing so $sql = $Conn->prepare("SELECT * FROM companies WHERE NAME LIKE ? or palavras_key LIKE ?")

  • shows the code of the place where you replaced the ? by the proper values

  • as I said is an auto complete system, I did as you said in the answer, but does not return anything in the search, I edited my question for you see the full code

Browser other questions tagged

You are not signed in. Login or sign up in order to post.