Jump to content

Cannot see the error in the function!


zid
Go to solution Solved by requinix,

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
Share on other sites

  • Solution

$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. Edited by requinix
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.