这可能是一个简单的语法错误,但我已经尝试过每一个我都知道的错误。我有一个用于选择数据的数据库类
<?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;
}
}
?>
我在index.php中实例化了这个。我做了一个查询并将其传递给select方法,然后运行if语句,如果结果的大小大于或等于1,则echo echo成功。这是我一直搞砸的地方。我试图打印出first_name的值,但无论我怎样尝试它都不会打印。这是一个二维关联数组吗?
<?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";
echo "<p>{$result[`first_name`]}</p>";
}
include 'view/footer.php';
?>
我已尝试使用不同的引号,尝试选择0位置然后选择first_name并且它不起作用。我错过了什么?
答案 0 :(得分:1)
$result
是一个二维数组。数组的每个元素都是一行结果,列是这些关联数组的元素。
所以你需要循环结果:
foreach ($result as $row) {
echo "<p>{$row['first_name'}</p>";
}
如果您只需要第一行的结果(例如,如果您知道查询不能匹配多行),则可以将其编入索引而不是循环:
echo "<p>{$result[0]['first_name']}</p>";
中的
first_name
附近也有错误的引号
$result[`first_name`]
它们应该是单引号或双引号,而不是反引号。在SQL中,你应该在clive
周围加上单引号或双引号,除非这是一个列名。见When to use single quotes, double quotes, and back ticks in MySQL