-1

Ok so basically I'm trying to create a simple web app

I want to check if one element is inside the table, and if inside I want to return a boolean value, like for example if "abc" is inside the table named "name" then return YES.

Here's my code, not working:

error_reporting(E_ALL);

$mysql = mysqli_connect(/* PRIVATE DATA */) or die ("ERROR CONNECTING TO THE DB");

if(isset($_POST['submit'])) {

    $theAddress = $_POST['youtubeURL'];

    $result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";

    $query = mysqli_query($mysql, $result);

    if (!$query) {
        printf("Error");
    } else {
        printf("NO ERROR");
    }

AND HERE'S THE NON-WORKING PART :

    while($row = mysqli_fetch_array($query)) {

        if ($row == 0) {

            echo "NO RESULT LIKE THIS";

        }else {

            echo "AT LEAST ONE RESULT LIKE THIS"; 
        }
    }

}
Michael
  • 43
  • 2
  • 9

3 Answers3

1

First, learn to use parameters queries. They really are no harder to use than stuffing a string value into a query.

Second, if you want to know if something exists, then write the query just to do that. The simplest query is probably:

SELECT EXISTS (SELECT 1 FROM data WHERE youtubeURL = ?) as exists_flag

This will return 1 if something matches. Just run the query and read the single value that is returned.

Note that returning select * to check for existence is an anti-pattern. You are returning way more data from the database than you need (both in terms of rows and columns). That is usually not a good idea.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

It should be like this.

//in case you want to see total of the wors
if(mysqli_num_rows($query) == 0) {
    echo "NO RESULT LIKE THIS";
} else {
    echo "AT LEAST ONE RESULT LIKE THIS"; 
}

 //in case you want to check for each of the row
 while($row = mysqli_fetch_array($query)) {
        if (empty($row)) {
            echo "NO RESULT LIKE THIS";
        } else {
            echo "AT LEAST ONE RESULT LIKE THIS"; 
        }
 }
Hari Lamichhane
  • 520
  • 5
  • 11
-1

You need to use mysqli_num_rows to count the rows ..

$result = "SELECT * FROM data WHERE youtubeURL = '" . $theAddress . "'";

$query = mysqli_query($mysql, $result);

if(mysqli_num_rows($query)) {
    echo "AT LEAST ONE RESULT LIKE THIS"; 
} else {
    echo "NO RESULT LIKE THIS";
}
Chris
  • 4,672
  • 13
  • 52
  • 93