在while循环之前从mysqli查询中回显变量

时间:2020-10-05 20:19:46

标签: php sql mysqli

<?php
if (isset($_GET['cid'])) {
    $id = ($_GET['cid']);
} else {
    echo 
    "Deze client is nog niet juist aangemaakt.";
}
$sql = "SELECT * FROM forms WHERE Client_ID ='$id'";
$result = $con->query($sql);
if (mysqli_num_rows($result) > 0) {
$username = 'how to get this value here ?';
echo $username; 
            while($row = mysqli_fetch_array($result)) {

这是我的代码。我想显示用户的用户名,并在while循环中显示多年来收集的所有数据。就像所有数据上方的标头一样。我是php和mysqli的新手。谁能帮助我如何从表中获取用户名并在while循环之前回显它?

1 个答案:

答案 0 :(得分:-1)

为此,您需要首先从结果集中获取所有数据。如果期望有多行,则可以使用fetch_all(),否则可以使用fetch_array()进行优化。

然后,您可以访问索引0处的行及其键,以从所需的列中获取值。如果没有行或列不属于SQL,则可以将其默认为空字符串。

<?php
if (isset($_GET['cid'])) {
    $id = $_GET['cid'];
} else {
    echo "Deze client is nog niet juist aangemaakt.";
}

$stmt = $con->prepare("SELECT * FROM forms WHERE Client_ID = ?");
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC);

// if there is at least one row and there is a key username then use it else empty string
$username = $data[0]['username'] ?? '';

echo $username;

// if you need to loop the rows:
foreach($data as $row) {

}

对于初学者,您应该真正学习PDO而不是mysqli。