简体   繁体   中英

PHP prepared statement: Why is this throwing a fatal error?

Have no idea whats going wrong here. Keeps throwing...

Fatal error: Call to a member function prepare() on a non-object

...every time it gets to the $select = $dbcon->prepare('SELECT * FROM tester1'); part. Can somebody shed some light as to what I'm doing wrong?

function selectall()            //returns array $client[][]. first brace indicates the row. second indicates the field
  {
  global $dbcon;

  $select = $dbcon->prepare('SELECT * FROM tester1');
  if ($select->execute(array()))
    {
    $query = $select->fetchall();

    $i = 0;

    foreach ($query as $row)
      {
      $client[$i][0] = $row['id'];
      $client[$i][1] = $row['name'];
      $client[$i][2] = $row['age'];
      $i++;
      }
    }
  return $client;
  } 
$client = selectall();
echo $client[0][0];

The obvious answer is that $dbcon hasn't been initialized at all or is initialized after this function is called.

What code is initializing $dbcon ? Where and when is it run? You also realize that you will need to initialize it on every invocation of a script that accesses the database? The last is just to make sure that you understand what the global scope in PHP is. It means scoped to that single request. The term global is a little misleading.

make sure you define $dbcon properly. If you are using mysqli, see how the connection is setup in the doc . you can also pass the connection object to the function

function selectall($dbcon){
   ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM