vhdz04 vhdz04 - 2 months ago 13
PHP Question

Search function with flags

I am trying to implement a quick search bar to search a table populated by an SQL database. The search will not search the table, but will generate SQL statements and search the database. I need to implement a search function using PHP that will use flags to stop the search. This is my code so far:

//THIS CODE WILL EXECUTE WHEN THE SEARCH BUTTON IS PRESSED
if($_REQUEST['btnsearch']){

if(isset($_POST['quicksearch']) and !empty($quicksearch)){

$sql = "SELECT column_name FROM information_schema.columns WHERE table_name ='alerts_table'
AND column_name IN('name', 'year','make','model','alert','date')";

$retvalues = mysqli_query($conn, $sql);
$data = array();
//LOOP POPULATES THE ARRAY WITH THE CURRENT COLUMN NAMES.
for($counter = 0; $counter <= $row=mysqli_fetch_array($retvalues, MYSQL_ASSOC); $counter++){

$string = $row["column_name"];

$data[$counter] = $string;
}

$length = count($data);

$flag = 1;

while($flag == 1){

for($x = 0; $x <= $length - 1; $x++){

$sql3="SELECT * FROM alerts_table WHERE $data[$x] = $quicksearch";
$retvalues2=mysqli_query($conn, $sql3);

if(!empty($retvalues2))
{
//POPULATE THE TABLE WITH RESULTS HERE !!!!!!!!!

$flag = -1; ///HOW CAN I BREAK THE LOOP???

}
}
}
}else{

Answer

From the PHP break documentation:

(PHP 4, PHP 5, PHP 7)

break ends execution of the current for, foreach, while, do-while or switch structure.

break accepts an optional numeric argument which tells it how many nested enclosing structures are to be broken out of. The default value is 1, only the immediate enclosing structure is broken out of.

In your case you have two loops; a while loop and an inner for loop. You can set your flag in your inner loop to a value that will stop the while loop, and then use a break to stop the for loop.

$flag = 1;

while($flag == 1){
    for($x = 0; $x <= $length - 1; $x++){
        // ...
        if(!empty($retvalues2))
        {
            $flag = -1; // set while condition to false
            break; // break out of for loop
        }
    }

    // execution continues here after break
    // end of while body, start next loop iteration
    // $flag == 1 => false, and the while loop will end
}