0

I would like to check if a given value exists in a mysql table. If yes; I would like to get the value of another column of that row.

Now I have:

$teinsertengetal=$_GET['getal'];
    
    // start
    
    $i = 0;
    $ikhadingezetArray = array();
    $result = $conn->query("SELECT getal, hoevaakingezet FROM ingezettegetallen");

    while ($row = mysqli_fetch_assoc($result))
    {
        $ikhadingezetArray[$i]['getallen'] = $row['getal'];
        $ikhadingezetArray[$i]['hoevaakingezets'] = $row['hoevaakingezet'];
        $i++;
    }
    
    foreach($ikhadingezetArray as $value)
    {
        echo $value . "<br>";
    }

My problem is that the foreach only echos "Array", not the values within the array. And then I have to check if $teinsertengetal is in the array (the field "getal" in $ikhadingezetArray). If yes; I want the value of "hoevaakingezet" from the same row number of the array.

I hope you understand what I mean. Maybe it's not the best way I could do this? Thank you in advance!

edit: the echo is just to check if the right values were inserted in the array.

For example:

Table "ingezettegetallen"

getal hoevaakingezet
6 2
48 4

$teinsertengetal = 48

Now I would like check if 48 is in the column "getal". If yes (and it is in this example) I would like to store the value "4" in a variable (like $hoevaakingezetdus).

2
  • $ikhadingezetArray is a 2-dimensional array, so $value is an array. You can't echo an array, use var_dump($value) or print the columns that you want. Commented Oct 6, 2022 at 19:22
  • 1
    If you want to test if a value exists in the table add a WHERE clause to the query instead of fetching the entire table. Commented Oct 6, 2022 at 19:23

1 Answer 1

2

Put the check in the query, rather than fetching the entire table.

$stmt = $conn->prepare("
    SELECT hoevaakingezet 
    FROM ingezettegetallen
    WHERE getal = ?");
$stmt->bind_param("s", $teinsertengetal);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
    echo $row['hoevaakingezet'] . "<br>";
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much for taking some time for me Barmar! Unfortunately I cannot check if this works for me now, but tomorrow I can. I will let you know. Thanks again!
Is it possible to do it without a while loop? Because I know it can only be max 1 result. When there are no results, I want to give $hoevaakingezetdus the value 0. If there is 1 result, I want $hoevaakingezetdus to be filled with the value of $row['hoevaakingezet'] Thank you!
If there's only one row then you don't need the loop.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.