-1

I have some PHP code that takes a post request as input to a prepared statement. It is not returning any information. There are no errors.

I have tried hard coding the variables that are passed to the prepared object to no avail.

If I manually query the database with the desired query, output is received.

What am I missing here? What can I do to get output?

Heres my code:

<?php

$username = "user";
$password = "ultrasecurepassword";

try {
    $pdo = new PDO('mysql:unix_socket=/run/mysql/mysql.sock;dbname=news', $username, $password);

} catch (PDOException $e) {
    print "Error!: " . $e->getMessage() . "<br/>";
    die();
}

$query = "SELECT * FROM newsdb ORDER BY pubdate DESC LIMIT 250";
if(!empty($_POST['search'])){
    $termobusca = htmlspecialchars($_POST['search']);
    $tipobusca = htmlspecialchars($_POST['searchtype']);

    if($tipobusca == "title"){
        $stmt = $pdo->prepare("SELECT * from newsdb where title like '%:term%' ORDER BY pubdate DESC limit 5000;");
    }
    else {
        $stmt = $pdo->prepare("SELECT * from newsdb where pubdate like '%:term%' ORDER BY pubdate DESC limit 5000;");
    }

    $stmt->bindParam(1, $termobusca);

}
else {
    $stmt = $pdo->prepare("SELECT * FROM newsdb ORDER BY pubdate DESC LIMIT 250");
}


$stmt->execute();

while($row = $stmt->fetch()){
    print_r($row);
}


$pdo = null;
?>
  • 1
    it should be: `$stmt->bindParam(':term', $termobusca);` you are mixing between named and question mark placeholder. – catcon Oct 03 '19 at 01:45
  • @catcon already tried that and it failed – phpnoob12345 Oct 03 '19 at 01:48
  • By the way it doesn't already have an answer, thanks to those who tried instead of shutting it down. There were no resources for this. It has to do with the wildcards – phpnoob12345 Oct 03 '19 at 01:58

1 Answers1

0

I have seen this question before somehow try this please

if($tipobusca == "title"){
    $stmt = $pdo->prepare("SELECT * from newsdb where title like :term ORDER BY pubdate DESC limit 5000;");
}
else {
    $stmt = $pdo->prepare("SELECT * from newsdb where pubdate like :term ORDER BY pubdate DESC limit 5000;");
}
$term  = '%'.$termobusca.'%';
$stmt->bindParam(':term', $term, PDO::PARAM_STR);
nbk
  • 45,398
  • 8
  • 30
  • 47