Jump to content

Cannot see the error in the function!


zid

Recommended Posts

Hi,

Trying to get a query list posts that starts with A for example.

 

straight up in the php file it works like a sharm as regular code.

$string = 'A';
 
$stmt = $db->prepare("SELECT page_id, page_title FROM pages WHERE page_title LIKE :page_title");
   
   $stmt->bindValue(':page_title', $string . '%', PDO::PARAM_STR);
 
   $stmt->execute();
 
   $result = $stmt->fetchAll();
      
   foreach($result as $row) {
      
      echo "<a href='index?page=". $row['page_id'] ."'>". $row['page_title'] ."</a>";
      
   }

but when trying to get this into a function, nothig is displayed. Please advice! What have I missed.

// calling the function
letterIndex('A');
 
// the function
function letterIndex($string) {
   
   $stmt = $db->prepare("SELECT page_id, page_title FROM pages WHERE page_title LIKE :page_title");
   
   $stmt->bindValue(':page_title', $string . '%', PDO::PARAM_STR);
 
   $stmt->execute();
 
   $result = $stmt->fetchAll();
      
   foreach($result as $row) {
      
      echo "<a href='index?page=". $row['page_id'] ."'>". $row['page_title'] ."</a>";
      
   }
   
}
Link to comment
https://forums.phpfreaks.com/topic/288187-cannot-see-the-error-in-the-function/
Share on other sites

$db is undefined. Because variables defined outside functions are not automatically defined inside functions.

 

letterIndex($db, 'A');
function letterIndex($db, $string) {
[edit] Find your php.ini and set

error_reporting = -1
display_errors = on
Restart your web server if you had to change that. PHP would have given you an error about calling a method on a non-object, cluing you into the problem with $db.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.