-2
<?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. Just like a header above all data. I am farely new to php and mysqli. Can anyone help me how to get the username out of the table and echo it before the while loop ?

Bas Schreuder
  • 172
  • 1
  • 13
  • 3
    **Warning:** You are wide open to [SQL Injections](https://stackoverflow.com/a/60496/1839439) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman Oct 05 '20 at 20:23
  • 2
    You should forget about mysqli and learn PDO instead. mysqli is not suitable for beginners like you. You need to start with something simpler – Dharman Oct 05 '20 at 20:24

1 Answers1

-1

To do this you need to first fetch all the data from the result set. You can use fetch_all() if you expect multiple rows, else you can optimize with fetch_array().

Then you can access the row at index 0 and its key to get the value from the column you want. If there are no rows or the column is not part of your SQL then you can default it to an empty string.

<?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.

Dharman
  • 30,962
  • 25
  • 85
  • 135