如何从数据库中获取特定部分?

时间:2018-12-13 13:14:07

标签: php database pdo

是否有一种方法只能从“ vragen_wrts”中获取“ vraag_naam”?

    $servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "nl_naar_eng";

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT vraag_naam, vraag_antwoord FROM vragen_wrts");
$stmt->execute();

$result = $stmt->setFetchMode(PDO::FETCH_ASSOC);

$words = $stmt->fetchAll();
//$engels = $words["vraag_antwoord"];
//var_dump($words ["vraag_naam"]);

我已经进行了// // p无效的尝试

2 个答案:

答案 0 :(得分:1)

fetchAll()将返回一个数组。您可能要迭代这个。

例如:

$words = $stmt->fetchAll();
foreach ($words as $word)
    var_dump($word["vraag_naam"]);
//                ^---------------notice the missing s

答案 1 :(得分:1)

您可以使用fetch()代替fetchall()

fetch()从与PDOStatement对象关联的结果集中获取一行。

<?php

$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "nl_naar_eng";

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$words = $conn->query("SELECT vraag_naam, vraag_antwoord FROM vragen_wrts")->fetch(PDO::FETCH_ASSOC);

echo $words["vraag_naam"];
?>

更新:

如果您只需要提取1行,则只需选择该行并使用fetchColumn()即可。

<?php

$servername = "127.0.0.1";
$username = "root";
$password = "";
$dbname = "nl_naar_eng";

$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$words = $conn->query("SELECT vraag_naam FROM vragen_wrts")->fetchColumn();

echo $words["vraag_naam"];
?>