不能在foreach中选择和回显数组

时间:2018-04-18 14:38:46

标签: php

db有一行有4列。我选择了2列,first_name和last_name。我通过db类中的select函数传递它,得到一个结果,但它不会回显

db class

<?php
  /* this script is for creating a class to connect to the database */

  include "includes/config.php";

  class database {
    protected static $connection; // variable to hold the mysqli connection


  protected function connect(){
      if (!isset(self::$connection)){ // if the connection variable is not set
          self::$connection = new mysqli(SERVER_NAME, USERNAME, PASSWORD, DB_NAME); // set the connection
      }
      if (self::$connection === false){ //in case connection failed return false
        return false;
      }
      else {
        return self::$connection; // returns the connection
      }
    }



    protected function query($query){ // public function to take a sql query
      $connection = $this->connect(); // calls the connect function to create a connection to the database
      $result = $connection->query($query); // puts the query into the result variable
      return $result; //returns the result
    }



    public function select($query){
      $rows = array();
      $result = $this->query($query);
      if($result === false){
        return false;
      }
      while($row = $result->fetch_assoc()){
            $rows[] = $row;
            }
        return $rows;
    }



    public function error(){
      $connection = $this->connect();
      return $connection->error;
    }
  }
?>

和带有foreach循环的脚本

<?php

  include 'view/header.php';
  include 'includes/connect.php';

  $db = new database();

  $sql = "SELECT `first_name`, `last_name` FROM `pratts_db`
          WHERE `first_name` = `clive`;";

  $result = $db->select($sql);

  if (sizeof($result) >= 1){
    echo "query successful";
    foreach($result as $result){
      echo "<p>{$result[0]['first_name']}</p>"
    }
  }

  include 'view/footer.php';

?>

该错误表示&#39;期待第17行的分号,但我把它放入并仍然得到相同的错误

解析错误:语法错误,意外&#39;}&#39;,期待&#39;,&#39;或&#39;;&#39;在第17行的C:\ wamp64 \ www \ final \ index.php

0 个答案:

没有答案