php - PDO returns empty array as result -


i have simple search form, use send post request php script using ajax. want script search database keyword in title column, , return rows finds it. posted data looks "searchword=test1", test1 in content of text input.

i have 2 rows in database, 1 has title of test1, , of test2. if select * articles can see results fine. if type select * articles title 'test1'; console, correct result, php script returns empty array.

no idea i'm doing wrong here, appreciated.

my php:

try {     $hostname = "localhost";     $username = "root";     $password = "";      $db = new pdo("mysql:host=$hostname;dbname=topdecka_ptc",$username, $password);      if (!empty($_post["searchword"])) {         $searchword = $_post["searchword"];         $query = $db->prepare("select * articles title %:seachword%");         $query->execute(array(':searchword' => $searchword));          $result = $query->fetchall(pdo::fetch_assoc);         echo json_encode($result);         die();     }      else {         $query = $db->prepare('select * articles');         $query->execute();          $result = $query->fetchall(pdo::fetch_assoc);         echo json_encode($result);         die();     } } catch (pdoexception $e) {     echo "error!: " . $e->getmessage() . "<br/>";     die(); } 

firstly, forgot $ sign %:seachword% per assignment:

sidenote: there's typo noticed in seachword should read searchword per ':searchword' => $searchword

$searchword = $_post["searchword"]; 

however, i'd instead:

like :seachword 

then

$query->execute(array(":searchword" => "%" . $searchword . "%")); 

example syntax:

$sqlprep = $conn->prepare("select `column` `table` `column` :word"); $sqlprep->bindvalue(':word', '%value%'); 

also make sure form have post method , element indeed named , no typos.

add error reporting top of file(s) find errors.

<?php  error_reporting(e_all); ini_set('display_errors', 1);  // rest of code 

sidenote: error reporting should done in staging, , never production.

  • add $db->setattribute(pdo::attr_errmode, pdo::errmode_exception); right after connection opened, catch potential errors, if any.

Comments

Popular posts from this blog

javascript - oscilloscope of speaker input stops rendering after a few seconds -

javascript - gulp-nodemon - nodejs restart after file change - Error: listen EADDRINUSE events.js:85 -

Fatal Python error: Py_Initialize: unable to load the file system codec. ImportError: No module named 'encodings' -