tr3online
tr3online

Reputation: 1429

Drop array values if they exist in a database?

I have a list of urls stored in a database, and I want to run a bit of code that checks an array of urls vs what is stored in the database. If the value exists, I want that value from the array dropped.

So far, I have a database that contains 3 rows:

CREATE TABLE links
(
     link_id INT(10)  NOT NULL AUTO_INCREMENT,
     url VARCHAR(255)  NOT NULL,
     last_visited TIMESTAMP,
     PRIMARY KEY (link_id),
     UNIQUE KEY (url)
)

And basically I'm just trying to insert the data vs a unique value via an INSERT command and if it fails, i'd like to remove that array value. Is this possible?

My bad code:

foreach ($urlArray as $url) {

     $sql = "INSERT INTO linkz (url, last_visited) VALUES ('".$url."', NOW())";

    if (!mysql_query($sql,$con)){
      // remove array here somehow?
    }

}

Is there a better way?

Any help would be appreciated, thanks! Tre

Upvotes: 1

Views: 169

Answers (2)

wallyk
wallyk

Reputation: 57784

I suppose that's one way to do it. There are several issues:

  • Non-normalized URL notation
  • Changing a table to test for existence

The first issue is that there are a large number of ways of expressing any given URL. For example: http://www.example.com/somepage can be written http://www.example.com/%73omepage

The other is that philosophically speaking, a pure test for some data in a database should not change the database, whether or not it already exists. A simple SELECT * FROM links WHERE url=whatever is the cleaner approach. Presumably you have an unstated goal of collecting URLs.

@mfonda has already answered the literal question.

Upvotes: 1

mfonda
mfonda

Reputation: 8003

You can drop a value from an array using unset. To do this, you need to know the key, so you might consider modifying your foreach to include the key:

foreach ($urlArray as $key => $url) {
    ...

    // Remove the item from the array
    unset($urlArray[$key]);
}

Upvotes: 3

Related Questions