1

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

2 Answers 2

3

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]);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Awesome. I was thinking of something along this line, but was unsure about the $key=>$url portion. Thanks!
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.