Otachan
Otachan

Reputation: 89

How to insert an array into the database without inserting every loop in php

I have this array from the checkbox

<?php
    $query = $handler->query("SELECT * FROM colors");
    while ($row = $query->fetch()) {?>
 <input type="checkbox" name="check_list[]" id="<?php echo $row['id']?>" value="<?php echo $row['hex'];?>">
<?php } ?>

PHP Query

<?php
    if(!empty($_POST['check_list'])) {
    foreach($_POST['check_list'] as $check) {
    $query = $handler->query("INSERT INTO images (color_tags) VALUES ('$check')");
        }
    }
        ?>

I want to insert the data's from the array without inserting it on every row I want it to be just separated in commas like data1,data2,data3 then insert it.

Upvotes: 0

Views: 1994

Answers (5)

Nouman Arshad
Nouman Arshad

Reputation: 593

I did not read your last line of require to keep it like a separated list. So, modifying my example

<?php

    if(!empty($_POST['check_list']) && is_array($_POST['check_list'])) {

      // use pipe "|" to separate values 
      $color_list = implode('|', $_POST['check_list']);

      // $handler -> mysqli or mysql
      $color_list = $handler->real_escape_string($city);
      $query = $handler->query("INSERT INTO images (color_tags) VALUES ('$color_list')");

    }
?>

Later you can use explode function to make it array again.

Sudo Example:

$DB_STRING_VALUE = "Fetch color_tags value from image table"
$list_of_colors = $DB_STRING_VALUE;

if(!empty($DB_STRING_VALUE)
  $list_of_colors = explode('|', $DB_STRING_VALUE);

Upvotes: 1

chetan.mohol
chetan.mohol

Reputation: 56

check if count of posted array is greater than 0 or not, if it has then convert values into comma separated and insert it into table.Otherwise no need of conversion and not need to insert blank values into table

if(count($_POST['check_list']) > 0)
    $list = implode(",",$_POST['check_list']);
else
    $list = '';

$query = $handler->query("INSERT INTO images (color_tags) VALUES('$list')");

Upvotes: 1

DragonSpirit
DragonSpirit

Reputation: 61

See answer in this post on how to insert multiple rows with one query in MySQL. Insert multiple rows with one query MySQL

This code will create a single insert query for all the items in your checkbox array.

if(!empty($_POST['check_list'])) {
    $insert_sql = "('".join("'),('",  $_POST['check_list'])."')";
    $query = $handler->query("INSERT INTO images (color_tags) VALUES ". $insert_sql);
}

Upvotes: 1

Ish
Ish

Reputation: 2105

Store it in json.

json_encode($array)

<?php
if(!empty($_POST['check_list'])) {

$query = $handler->query("INSERT INTO images (color_tags) VALUES ( json_encode($_POST['check_list']))");

}
?>

Upvotes: 1

Mayank Pandeyz
Mayank Pandeyz

Reputation: 26258

Use implode() function. It join array elements with a string.

string implode ( string $glue , array $pieces )
string implode ( array $pieces )

and save the string in database.

Upvotes: 1

Related Questions