對不起我的英文不好我講法語通常:)PHP MYSQL PDO getColumnMeta
目前我使用的MySQLi和我嘗試我所有的MySQLi轉化爲PDO。
中的MySQLi我有這樣的代碼,它做工非常精細:
// connection string in MySQLi
if ($query = $connection->prepare("SELECT u.ID as ID,
u.Username as Username,
u.Firstname as Firstname,
u.Lastname as Lastname,
// ... many more
FROM Users u
INNER JOIN Gender g ON u.Gender = g.id
// ... many more
WHERE u.ID = ?")) {
$query->bind_param('s', $_SESSION['ID']);
$query->execute();
$metaResults = $query->result_metadata();
$fields = $metaResults->fetch_fields();
$statementParams = '';
foreach ($fields as $field) {
if (empty($statementParams)) {
$statementParams.="\$column['" . $field->name . "']";
} else {
$statementParams.=", \$column['" . $field->name . "']";
}
}
$statment = "\$query->bind_result($statementParams);";
eval($statment);
$query->store_result();
$affected = $query->num_rows;
// this request return me only ONE row
if ($affected == 1) {
while ($query->fetch()) {
foreach ($column as $key => $value) {
if ($key == "lookingFor") {
$row_tmb[$key] = formatLookingFor($value, $language, "");
} else {
$row_tmb[$key] = utf8_encode($value);
$row_tmb[$key] = $value;
}
}
$results[] = $row_tmb;
}
$query->free_result();
$query->close();
$profileData = $results[0];
// ... other code
}
這是迴歸到我所有的列名和全1個數據行,我很高興檸。所以,我嘗試這種代碼轉換爲PDO的新PDO代碼:
// good connection string without error in PDO code and the same query as you see up.
if ($query = $connection->prepare($sql)) {
$query->execute();
$metaResultsColNumber = $query->columnCount();
for ($i = 0; $i < $metaResultsColNumber; $i++) {
$metaResults[] = $query->getColumnMeta($i, ['name']);
}
var_dump($metaResults);
$fields = $metaResults->fetchColumn();
var_dump($fields);
$statementParams = '';
foreach ($fields as $field) {
if (empty($statementParams)) {
$statementParams.="\$column['" . $field->name . "']";
} else {
$statementParams.=", \$column['" . $field->name . "']";
}
}
$statment = "\$query->bind_result($statementParams);";
eval($statment);
$query->store_result();
$affected = $query->num_rows;
// TRACE
printf("SQL %d row(s) return", $affected);
if ($affected == 1) {
while ($query->fetch()) {
foreach ($column as $key => $value) {
if ($key == "lookingFor") {
$row_tmb[$key] = formatLookingFor($value, $language, "");
} else {
$row_tmb[$key] = utf8_encode($value);
}
}
$results[] = $row_tmb;
}
$query->free_result();
$query->close();
$profileData = $results[0];
,我無法獲得1)右側的列名2)返回行
我嘗試讀取數據從很多小時幫助到這個網站和PHP MYSQL PDO文檔。
非常感謝您的幫助!
'getColumnMeta'只接受一個參數,第二個參數是什麼?我認爲你的意思是' - > getColumnMeta($ i)['name']'。我不知道你要用'$ fields = $ metaResults-> fetchColumn()'來做什麼。 '$ metaResults'是一個數組,不是一個PDO對象。 – Barmar
PDO沒有'store_result()'方法,爲什麼要調用它? – Barmar
'$ query-> num_rows'應該是'$ query-> rowCount()'。似乎你幾乎沒有試圖用PDO等價物取代mysqli函數。 – Barmar