Home > Net >  Check if given value exists in array or mysql table
Check if given value exists in array or mysql table

Time:10-07

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

CodePudding user response:

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>";
}
  • Related