1

I have a problem that is staring me in the face but I cannot seem to solve it.

First of:

1) the code is parsed prior to check for SQL injection.
2) $dbc is a reference that is part of another script that is "require_once()" called in and is working perfectly as its fine for 2 other scripts depending on it
3) the query text when pumped straight into mysql calls back exactly what Im after
4) If I put a false array into $displayBlogs, the rest of script acts as it should.

The table is populated. So why do I seem to receive no results, no errors (checked with mysqli_error($dbc) ) ? Blogs just seems to be empty.

function getSnippets()
{
  // set up the query   
  $query1 = "SELECT * FROM blogs LIMIT 0, 10";

  // action the query and save the connection
  $blogs = mysqli_query($dbc, $query1);

  // blank out the variable that will be used to save the query results
  $displayBlogs = '';

  // iterate through the query results and set up the module return
  while($blog = mysqli_fetch_array($blogs))
  {
    $displayBlogs .= "<div class='article'><a href='" . $blog['link'] ."'>" .
                     "<h1>" . $blog['title'] . "</h1>" .
                     "<h2>" . $blog['date'] . "</h2>" .
                     "<p>" . $blog['body'] . "</p>" .
                     "</a></div>";
  }      
  return $displayBlogs;
}
Johan
  • 71,222
  • 23
  • 174
  • 298
Paul Chambers
  • 301
  • 1
  • 6
  • 13

4 Answers4

3

You can declare global scope for $dbc :

function getSnippets()
{
    global $dbc;
    // declaring $dbc global to have it accessed outside the scope of the function
}

or, even better, pass it as an argument of the function, as using global variables is considered bad practice (check, among many, this SO question as for why):

function getSnippets($dbc)
{
   $connection = $dbc;
   //...
   $blogs = mysqli_query($connection, $query1);

  // rest of code...
}
Community
  • 1
  • 1
Damien Pirsy
  • 24,544
  • 6
  • 65
  • 77
1

Even though it's required, the $dbc variable shouldn't be accesable from inside a function. To make it posible, use it as a global.

In that case, it'd be written, at the start, you should write:

function getSnippets()
{
    global $dbc;
Lumbendil
  • 2,866
  • 1
  • 16
  • 24
0

Do you need to global $dbc;?

Scott C Wilson
  • 16,711
  • 9
  • 54
  • 76
0

You should be using var_dump() on each of the variables used till you nail the culprit.

$dbc
$query1
$blogs
$blog

Also, you should be monitoring your mysql logs to see what, if anything, is actually happening at the database end.

Not solving your issue I realise (pretty sure Scott got that) but hopefully leading you to isolate and identify similar errors in the future (you will make them).

Cups
  • 6,577
  • 3
  • 24
  • 29