Php 从阵列加载特定数据
因此,我有一个从MySQL数据库加载数据的类:Php 从阵列加载特定数据,php,mysql,arrays,Php,Mysql,Arrays,因此,我有一个从MySQL数据库加载数据的类: class Db { protected static $connection; public function connect() { if(!isset(static::$connection)) { $config = parse_ini_file('config.ini'); static::$connection = new mysqli('lo
class Db {
protected static $connection;
public function connect() {
if(!isset(static::$connection)) {
$config = parse_ini_file('config.ini');
static::$connection = new mysqli('localhost',$config['username'],$config['password'],$config['dbname']);
}
if(static::$connection === false) {
return false;
}
return static::$connection;
}
public function query($query) {
return $this->connect()->query($query);
}
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() {
return $this->connect()->error;
}
public function quote($value) {
return "'" . $this->connect()->real_escape_string($value) . "'";
}
}
我这样使用该类:
$db = new Db();
$rows = $db -> select("SELECT name, shortlink FROM `test` WHERE id=3");
它给了我一个包含数据的数组
问题是我想提取特定的数据,例如shortlink字段
我该怎么做?我尝试了echo$rows['shortlink']
,但出现以下错误:
未定义索引:短链接
那么如何打印特定数据呢?返回的
$rows
列是一个关联数组数组,要提取查询返回的短链接
数据,必须执行以下操作:
foreach($rows as $row) {
echo $row['shortlink'];
}
我建议使用更方便的方法使用PDO(PDO::fetch_列)获取某个字段的值