search

Home  >  Q&A  >  body text

Research question on multi-column query using PHP

<p>I have a question. I need to query all text containing a substring given by using POST method on PHP. For example, if I enter an "a" or a number like "1" (a character not an integer), do I need to find everything that contains that character or substring and check every column in the table if that's possible? I've tried something like this, but the code is a bit messy. </p> <pre class="brush:php;toolbar:false;"><?php if ($_SERVER["REQUEST_METHOD"] == "POST") { $usersearch = $_POST["usersearch"]; try { require_once "includes/dbh.inc.php"; $query = "SELECT * FROM tlattine WHERE tipologia LIKE :usersearch OR nome LIKE :usersearch OR caratteristiche LIKE :usersearch OR tabstyle LIKE :usersearch OR tabcolor LIKE :usersearch OR topstyle LIKE :usersearch OR topcolor LIKE :usersearch OR provenienza LIKE :usersearch OR produttore LIKE :usersearch OR sku LIKE :usersearch ORDER BY tipologia, provenienza, year, dimensione;"; $stmt = $pdo->prepare($query); $stmt->bindParam(":usersearch", $usersearch); $stmt->execute(); $results = $stmt->fetchAll(PDO::FETCH_ASSOC); $pdo = null; $stmt = null; } catch (PDOException $e) { die("Query failed: " . $e->getMessage()); } } else{ header("Location: ../index.php"); } ?></pre> <p>Already tried using '%:usersearch%' or combining % in any form but it seems I'm missing something, I'm absolutely sure but I can't find it :(</p>
P粉242126786P粉242126786529 days ago487

reply all(1)I'll reply

  • P粉793532469

    P粉7935324692023-07-27 09:13:59

    Seeing your query, I noticed that you used the parameter: usersearch multiple times.

    Mentioned in the PHP documentation:

    I prefer to avoid enabling impersonation mode and instead change named placeholders to positional placeholders (use '?' instead of ':usersearch') , then use


    $stmt->bindParam(1, $usersearch, PDO::PARAM_STR);
    $stmt->bindParam(2, $usersearch, PDO::PARAM_STR);
    $stmt->bindParam(3, $usersearch, PDO::PARAM_STR);
    // and so on

    One last thing, if you are querying so that the column contains the $usersearch variable, you should probably add % at the beginning and end of the string.

    $usersearch = "%" . $_POST["usersearch"] . "%"

    reply
    0
  • Cancelreply