-1

I am making a search function, and I am not sure how to change this mysqli code to PDO code (Also prevent SQL injection). Hope you guys can help me.

<?php
if(isset($_POST['submit'])) {
    $search = $_POST['search'];

    $query = "SELECT * FROM posts WHERE post_tags LIKE '%$search%'";
    $search_query = mysqli_query($connection, $query);

    if(!$search_query) {
        die("QUERY FAILED" . mysqli_error($connection));
    }

    $count = mysqli_num_rows($search_query);
}
?>

Below is my PDO code:

<?php
$search = $_POST['search'];
$search = "%$search%";

$sql = 'SELECT * FROM posts WHERE post_tags LIKE :search';
$stmt = $pdo->prepare($sql);
$stmt->bindParam(':search', $search);
$stmt->execute();

if(!$stmt) {
    die("QUERY FAILED" . $pdo->errorInfo());
}

$count = $stmt->fetchColumn();
?>
RiggsFolly
  • 89,708
  • 20
  • 100
  • 143
Code Lover
  • 15
  • 6
  • 1
    There does not look like much wrong with that code. What do you think the probelms are? Does it run? – RiggsFolly Dec 30 '20 at 11:25
  • You may want to consider using `->fetchObject()` so you get a complete row with each call rather than a single column from `->fetchColumn()` although you may have done that intensionally. Or even a `->fetchAll()` so you get all rows returned into an array. – RiggsFolly Dec 30 '20 at 11:27
  • For reference: [SQL Injection](http://stackoverflow.com/questions/60174) – RiggsFolly Dec 30 '20 at 11:30
  • Thank you for enlightening me, I used rowCount() to solve my problem, thank you! – Code Lover Dec 30 '20 at 11:44
  • Ok, still not sure what your problem was, but glad its solved – RiggsFolly Dec 30 '20 at 11:46

1 Answers1

-1
if(isset($_POST['submit'])) {
    
    $search = $_POST['search'];
    $search = "%$search%";

    $sql = 'SELECT * FROM posts WHERE post_tags LIKE :search';
    $stmt = $pdo->prepare($sql);
    $stmt->bindParam(':search', $search);
    $stmt->execute();

    if(!$stmt) {
        die("QUERY FAILED" . $pdo->errorInfo());
    }

   
    $count = $stmt->rowCount();

    if($count == 0) {
        echo "<h1> NO RESULT</h1>";
    } else {
        .....
Code Lover
  • 15
  • 6