使用 PDO 获取数据并仅获取一次数据及其列名
Fetching data using PDO and get the data only once with its column names
当使用 PDO 从 mysql 数据库中获取值时,我得到了一些冗余信息,我想知道为什么。 return 下面的 php 函数是我希望 return 编辑的值。但是如果我 return 我的结果数组,我会得到双精度值。
public function getNames($userid) {
try {
$dbh = new PDO('mysql:host=localhost;dbname='.parent::Database(), parent::User(), parent::Password());
} catch (PDOException $e) {
var_dump("error: $e");
}
$sql = "SELECT ID, Name FROM cars WHERE userid =:UID and type=2";
$sth = $dbh->prepare($sql);
$sth->bindParam(':UID', $userid);
$sth->execute();
$result = $sth->fetchAll(); //fetches all results where there's a match
$result2 = array();
foreach($result as $res)
$result2[] = array("ID"=>$res["ID"], "Name"=>$res["Name"]);
return $result2;
}
$结果returns:
Array
(
[0] => Array
(
[ID] => 2
[0] => 2
[Name] => Volvo
[1] => Volvo
)
[1] => Array
(
[ID] => 8
[0] => 8
[Name] => Ford
[1] => Ford
)
)
$Result2 returns:
Array
(
[0] => Array
(
[ID] => 2
[Name] => Volvo
)
[1] => Array
(
[ID] => 8
[Name] => Ford
)
)
为什么 $result 会这样?就像它多次获取我的数据一样。我使用的代码错了吗?如果可能,我想使用 $result2 的结果而不指定每个 return 数组 - 以防 table 在某个时候被编辑。可能的?
您得到的结果既是关联数组又是索引数组。
只获取关联数组,可以使用:
$result = $sth->fetchAll(PDO::FETCH_ASSOC);
当使用 PDO 从 mysql 数据库中获取值时,我得到了一些冗余信息,我想知道为什么。 return 下面的 php 函数是我希望 return 编辑的值。但是如果我 return 我的结果数组,我会得到双精度值。
public function getNames($userid) {
try {
$dbh = new PDO('mysql:host=localhost;dbname='.parent::Database(), parent::User(), parent::Password());
} catch (PDOException $e) {
var_dump("error: $e");
}
$sql = "SELECT ID, Name FROM cars WHERE userid =:UID and type=2";
$sth = $dbh->prepare($sql);
$sth->bindParam(':UID', $userid);
$sth->execute();
$result = $sth->fetchAll(); //fetches all results where there's a match
$result2 = array();
foreach($result as $res)
$result2[] = array("ID"=>$res["ID"], "Name"=>$res["Name"]);
return $result2;
}
$结果returns:
Array
(
[0] => Array
(
[ID] => 2
[0] => 2
[Name] => Volvo
[1] => Volvo
)
[1] => Array
(
[ID] => 8
[0] => 8
[Name] => Ford
[1] => Ford
)
)
$Result2 returns:
Array
(
[0] => Array
(
[ID] => 2
[Name] => Volvo
)
[1] => Array
(
[ID] => 8
[Name] => Ford
)
)
为什么 $result 会这样?就像它多次获取我的数据一样。我使用的代码错了吗?如果可能,我想使用 $result2 的结果而不指定每个 return 数组 - 以防 table 在某个时候被编辑。可能的?
您得到的结果既是关联数组又是索引数组。
只获取关联数组,可以使用:
$result = $sth->fetchAll(PDO::FETCH_ASSOC);