1

I was wondering how I could compare a value/varchar in my database to a string in my own PHP script. Below is a picture of my database if it helps and I just want to compare the value inside the ThunderOrNot column (ID = 1) to a string of "Thunder". Neither of my bottom 2 'if' statements work. What am I doing wrong? Thanks! Picture of DB

    <?php

$link = mysqli_connect('.....', '.....', '.....', '.....');

$query = "select * from thunderDemo";
$result = mysqli_query($link, $query);

while($row = mysqli_fetch_array($result))
{
         echo $row["ThunderOrNot"];
}

if($row[ThunderOrNot] == 'Thunder')
{
         echo "The Value equals Thunder";
}

if($row == 'Thunder')
{
         echo "The Value equals Thunder";
}

mysqli_close($link);

?>
2
  • Quotes my friend, quotes...$row["ThunderOrNot"] Commented May 4, 2016 at 16:34
  • The only issue I have with this @PedroLobito is that PHP will try to resolve ThunderOrNot as a constant, and on finding none throws a notice and then tries to place quotes around the 'constant' itself. The warning should not stop processing the of the code, depending on how the OP's server is set up. "E_NOTICE : type 8 -- Use of undefined constant ThunderOrNot - assumed 'ThunderOrNot' The Value equals Thunder" Commented May 4, 2016 at 16:41

3 Answers 3

2
  1. Put the if inside the while loop
  2. Add quotes to $row["ThunderOrNot"] (not as important, because an unquoted string will be interpreted as a constant by php and, in this case, its value will be ThunderOrNot (kudos:Jay Blanchard), i.e. :

while($row = mysqli_fetch_array($result))
{
    if($row["ThunderOrNot"] == 'Thunder'){
        echo "The Value equals Thunder";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

Your main problem is that you put your conditions after there are no more records returned. Move them inside your while loop.

Note that you should add a second parameter to mysqli_fetch_array(): MYSQLI_ASSOC for it to return an associative array.

The condition would then be: if ($row['ThunderOrNot'] == 'Thunder')

3 Comments

PHP already fetches an associative: " Fetch a result row as an associative, a numeric array, or both."
It defaults to MYSQLI_BOTH which can be confusing and slower.
Why do you argue for nothing? Look at the code. He loops through the records and just checks the conditions after the loop.
-1
if($row["ThunderOrNot"] == 'Thunder')

Index is a text.

Comments

Your Answer

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