Php 无法在foreach中选择和回显阵列
数据库有一行4列。我选择了两列,名字和姓氏。我通过db类中的一个select函数传递了它,结果如何,但它不会回显 数据库类Php 无法在foreach中选择和回显阵列,php,Php,数据库有一行4列。我选择了两列,名字和姓氏。我通过db类中的一个select函数传递了它,结果如何,但它不会回显 数据库类 <?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
<?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';
?>
错误是“第17行需要分号,但我把它放进去了,仍然得到了相同的错误。”
分析错误:语法错误,意外的“}”,应为“,”或“;”在第17行的C:\wamp64\www\final\index.php中,在
clive
周围使用单引号,而不是反引号。此外,我在foreach中尝试了调用数组的不同方法。{$result[firstname]},带引号和不带引号,还有你在第一篇博文中看到的echo“{$result[0]['first_name']}”
我注意到了缺少的分号。还是不行。我是新手,所以在foreach的括号中,第一个输入是数组,在本例中,$result,第二个输入只是一个占位符,可以是我想称之为的任何内容,对吗?这是更新的版本。它给出了一个错误,表示为foreach提供的参数无效