Brian Powell
Brian Powell

Reputation: 3411

remove element from array based on sql query

$_SESSION['lines'] is populated from a textbox that a user pastes into. Before I do anything with the data, I want to run it through a filter to see if any of the values they've input are NOT in the database.

foreach ($_SESSION['lines'] as $q) {
$multiSupplierQuery      = "SELECT distinct supplier from allparts where quotePartNumber = '$q'";
$multiSupplierResult    = mysqli_query($con, $multiSupplierQuery);

while ($row = mysqli_fetch_array($multiSupplierResult)) {
  $multiSupplier = $row['supplier'];
}
 if (!multiSupplier) {
  unset($_SESSION['lines'[]);
 }
}

The crux of this revolves around this statement:

 if (!multiSupplier) {
  unset($_SESSION['lines'[]);
}

What I'm trying to say is: each time we cycle through this, if multiSupplier doesn't exist, remove this particular element from the array.

my unset syntax is wrong though... how do I make it right?

Upvotes: 0

Views: 719

Answers (2)

Jo.
Jo.

Reputation: 790

You probably want to add a $ to your if statement. Change

if (!multiSupplier) {

to

if (!$multiSupplier) {  

Also, to unset from the $_SESSION you need a key. Try changing

foreach ($_SESSION['lines'] as $q) {

to

foreach ($_SESSION['lines'] as $key=>$q) {

and then

unset($_SESSION['lines'][$key]);

Upvotes: 2

V13Axel
V13Axel

Reputation: 838

It's not your unset usage, you just have an unnecessary opening square bracket.

unset($_SESSION['lines'[]);

should be

unset($_SESSION['lines']);

And you'll be good to go.

Upvotes: 1

Related Questions