michelle
michelle

Reputation: 653

inserting all entries stored in an array (for statement)

I have all of my keys stored in the array $addkeys (the total amount of keys always changes). The var_dump($addkeys) outputs:

Arrayarray(9) { [0]=> string(17) "11111-11111-11111" [1]=> string(17) "22222-22222-22222" [2]=> string(17) "33333-33333-33333" [3]=> string(17) "44444-44444-44444" [4]=> string(17) "55555-55555-55555" [5]=> string(17) "66666-66666-66666" [6]=> string(17) "77777-77777-77777" [7]=> string(17) "88888-88888-88888" [8]=> string(17) "99999-99999-99999" }

I want to insert each of them into the database if they don't already exist. I understand how to check for a single existing key in a string and do an INSERT if it doesn't already exist, but the incremental loop confuses me. Any help would be appreciated. I understand people might recommend using PDO for the mysql queries, but please disregard.

My code:

for ($i = 0; $i < count($addkeys); $i++) {

// check each key in $addkeys to see if it exists already in the database to prevent a duplicate entry

$result = mysql_query("SELECT code FROM codes WHERE code = '$addkeys'")
or die(mysql_error());
$row = mysql_fetch_array($result, MYSQL_NUM);
$addkeys = $row[0];

if(!isset($addkeys)) {
// entry doesn't exist insert the key
$result = mysql_query("INSERT INTO codes (code, title) VALUES ('$addkeys', 'sample title')")
or die(mysql_error());

}
}

Upvotes: 1

Views: 40

Answers (2)

Saty
Saty

Reputation: 22532

You have to use mysql_num_rows to check data already store in your database or not. and you are use direct array addkeys in your query you have to use it like addkeys[$i]

Your code would be

for ($i = 0; $i < count($addkeys); $i++) {

// check each key in $addkeys to see if it exists already in the database to prevent a duplicate entry

    $result = mysql_query("SELECT code FROM codes WHERE code = '$addkeys[$i]]'") or die(mysql_error());
    $rows = mysql_num_rows($result);

    if ($rows < 1) {
// entry doesn't exist insert the key
        $insert = mysql_query("INSERT INTO codes (code, title) VALUES ('$addkeys[$i]]', 'sample title')") or die(mysql_error());
    }
}

Note:- mysql is depricated instead use mysqli OR PDO

Upvotes: 1

Professor Abronsius
Professor Abronsius

Reputation: 33823

if you have a keyed column you could use the on duplicate key update syntax

<?php
    foreach( $addkeys as $key ){
        $title='sample title';

        $result = mysql_query("INSERT INTO codes (`code`, `title`) VALUES ('{$key}', '{$title}')
            on duplicate key update `code`={$key}, `title`='{$title}'");    
    }
?>

Upvotes: 1

Related Questions