問題描述
我不想使用循環.我只是來自一行的一列的一個值.我用以下代碼得到了我想要的東西,但必須有一種更簡單的方法來使用 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;
這看起來像太多行,無法從數據庫中獲取一個值.:
This just looks like too many lines to get one value from the database. :
推薦答案
您可以為此創建一個函數,并在每次需要單個值時調用該函數.出于安全原因,請避免連接字符串以形成 SQL 查詢.相反,對值使用準備好的語句并對 SQL 字符串中的其他所有內容進行硬編碼.為了獲得某個列,只需在您的查詢中明確列出它.fetchColumn()
方法也可以方便地從查詢中獲取單個值
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();
}
然后你可以簡單地做:
$name = getSingleValue($conn, "SELECT name FROM login_users WHERE id=?", [$userid]);
它會給你想要的價值.
因此您只需創建該函數一次,但可以將其重用于不同的查詢.
So you need to create that function just once, but can reuse it for different queries.
此答案已由社區編輯以解決安全問題
This answer has been community edited addressing security concerns
這篇關于使用 mysql php pdo 從數據庫返回一個值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!