問(wèn)題描述
我不想使用循環(huán).我只是來(lái)自一行的一列的一個(gè)值.我用以下代碼得到了我想要的東西,但必須有一種更簡(jiǎn)單的方法來(lái)使用 PDO.
Im not trying to use a loop. I just one one value from one column from one row. I got what I want with the following code but there has to be an easier way using PDO.
try {
$conn = new PDO('mysql:host=localhost;dbname=advlou_test', 'advlou_wh', 'advlou_wh');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
$userid = 1;
$username = $conn->query("SELECT name FROM `login_users` WHERE username='$userid'");
$username2 = $username->fetch();
$username3 = $username2['name'];
echo $username3;
這看起來(lái)像太多行,無(wú)法從數(shù)據(jù)庫(kù)中獲取一個(gè)值.:
This just looks like too many lines to get one value from the database. :
推薦答案
您可以為此創(chuàng)建一個(gè)函數(shù),并在每次需要單個(gè)值時(shí)調(diào)用該函數(shù).出于安全原因,請(qǐng)避免連接字符串以形成 SQL 查詢(xún).相反,對(duì)值使用準(zhǔn)備好的語(yǔ)句并對(duì) SQL 字符串中的其他所有內(nèi)容進(jìn)行硬編碼.為了獲得某個(gè)列,只需在您的查詢(xún)中明確列出它.fetchColumn()
方法也可以方便地從查詢(xún)中獲取單個(gè)值
You could create a function for this and call that function each time you need a single value. For security reasons, avoid concatenating strings to form an SQL query. Instead, use prepared statements for the values and hardcode everything else in the SQL string. In order to get a certain column, just explicitly list it in your query. a fetchColumn()
method also comes in handy for fetching a single value from the query
function getSingleValue($conn, $sql, $parameters)
{
$q = $conn->prepare($sql);
$q->execute($parameters);
return $q->fetchColumn();
}
然后你可以簡(jiǎn)單地做:
$name = getSingleValue($conn, "SELECT name FROM login_users WHERE id=?", [$userid]);
它會(huì)給你想要的價(jià)值.
因此您只需創(chuàng)建該函數(shù)一次,但可以將其重用于不同的查詢(xún).
So you need to create that function just once, but can reuse it for different queries.
此答案已由社區(qū)編輯以解決安全問(wèn)題
This answer has been community edited addressing security concerns
這篇關(guān)于使用 mysql php pdo 從數(shù)據(jù)庫(kù)返回一個(gè)值的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!