简体   繁体   English

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

[英]Echo variable from mysqli query before while loop

<?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)) {

This is my code.这是我的代码。 I want show the username of the user and in the while loop all the data that has been collected over the years.我想显示用户的用户名,并在 while 循环中显示多年来收集的所有数据。 Just like a header above all data.就像所有数据之上的标题一样。 I am farely new to php and mysqli.我是 php 和 mysqli 的新手。 Can anyone help me how to get the username out of the table and echo it before the while loop ?任何人都可以帮助我如何从表中获取用户名并在 while 循环之前回显它?

To do this you need to first fetch all the data from the result set.为此,您需要首先从结果集中获取所有数据。 You can usefetch_all() if you expect multiple rows, else you can optimize with fetch_array() .如果需要多行,可以使用fetch_all() ,否则可以使用fetch_array()进行优化。

Then you can access the row at index 0 and its key to get the value from the column you want.然后您可以访问索引 0 处的行及其键以从所需的列中获取值。 If there are no rows or the column is not part of your SQL then you can default it to an empty string.如果没有行或列不是 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) {

}

For a beginner, you should really look into learning PDO instead of mysqli.对于初学者,您应该真正考虑学习 PDO 而不是 mysqli。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM