David
David

Reputation: 1191

PHP foreach loop if POST value is not empty

I have this PHP loop:

foreach($_POST['af_break_date'] as $id=>$value) {
    $update_break_date_query = "UPDATE studentdates SET student_break_date = '$value' WHERE student_date_id = '$id';";
    $update_break_date_sql = mysql_query($update_break_date_query) or die(mysql_error());
}

I want to run the $update_break_date_sql only if each $_POST['af_break_date'] is not null.

How can this be done?

Upvotes: 0

Views: 3690

Answers (6)

Kodemon
Kodemon

Reputation: 370

Alternative to isset is empty which will check if the array is empty, so since its always being posted we check if its empty before running the foreach loop.

if (!empty($_POST['af_break_date']) && is_array($_POST['af_break_date'])) {
    foreach($_POST['af_break_date'] as $id=>$value) {
        $update_break_date_sql = mysql_query("UPDATE studentdates SET student_break_date = '$value' WHERE student_date_id = '$id'") or die(mysql_error());
    }
}

Upvotes: 0

arun
arun

Reputation: 3677

use isset

if(isset($_POST['af_break_date'] && 
strlen(implode("",$_POST['af_break_date']))>0)
{
....
...
}

Upvotes: 1

Muthu Kumaran
Muthu Kumaran

Reputation: 17910

Just add a condition to check & avoid empty values

if($_POST['af_break_date']){
    foreach($_POST['af_break_date'] as $id=>$value) {
      if(!$value) continue;
      $update_break_date_query = "UPDATE studentdates SET student_break_date = '$value' WHERE student_date_id = '$id';";
      $update_break_date_sql = mysql_query($update_break_date_query) or die(mysql_error());
    }
}

Don't use mysql_* functions, they will be deprecated soon. Instead use mysqli or PDO for connecting database. Use prepared statements to avoid SQL injections and before that do validations before updating datas to database.

Upvotes: 0

Nikita Melnikov
Nikita Melnikov

Reputation: 209

Use !empty();

For Example

$value = false;

isset($value); //return true
!empty($value); //return false

Upvotes: 0

som
som

Reputation: 4656

if( isset( $_POST['af_break_date'] ) && is_array(  $_POST['af_break_date'] )) {
    foreach($_POST['af_break_date'] as $id=>$value) {
        $update_break_date_query = "UPDATE studentdates SET student_break_date = '$value' WHERE student_date_id = '$id';";
        $update_break_date_sql = mysql_query($update_break_date_query) or die(mysql_error());
    }
}

Upvotes: 0

MrCode
MrCode

Reputation: 64526

foreach($_POST['af_break_date'] as $id=>$value)
{
    if($value != '')
    {
        $update_break_date_query = "UPDATE studentdates SET student_break_date = '$value' WHERE student_date_id = '$id';";
        $update_break_date_sql = mysql_query($update_break_date_query) or die(mysql_error());
    }
 }

Don't forget to secure for SQL Injection because you are adding raw user input to the query. Have a look at PDO or MySQLi and parameterised queries.

Upvotes: 4

Related Questions