简体   繁体   English

想要将具有唯一值的多维数组值插入 php 数据库

[英]want to insert multidimensional array value into php database with unique value

I have one multidimensional-array and i want to insert into my database, there is one issue if one entry in my database and same entry is on my multidimensional-array that value should not insert again in my database.我有一个多维数组,我想插入到我的数据库中,如果我的数据库中有一个条目,并且我的多维数组中有一个条目,则该值不应再次插入我的数据库中。

$activity[] = array('user_id'=> $_SESSION['user_id'], 'choosen_date' => $ch_date, 'distance' => $distance, 'pace' => $pace );

Array
(
    [0] => Array
        (
            [user_id] => 1200
            [choosen_date] => 2018-12-11
            [distance] => 1.72
            [pace] => 12.4812
        )
[1] => Array
    (
        [user_id] => 1200
        [choosen_date] => 2018-12-09
        [distance] => 3.17
        [pace] => 3.8736
    )

[2] => Array
    (
        [user_id] => 1200
        [choosen_date] => 2018-11-14
        [distance] => 2.26
        [pace] => 6.3504
    )

[3] => Array
    (
        [user_id] => 1200
        [choosen_date] => 2018-11-07
        [distance] => 0.53
        [pace] => 3.6576
    )

)

And following is my database entry以下是我的数据库条目

----------------------------------------------------
| S.No | user Id | choose date | distance |  Pace  |
----------------------------------------------------
|  1   |  1200   | 2018-12-09  |   3.17   | 3.8736 |
----------------------------------------------------
|  2   |  1200   | 2018-12-11  |   2.17   |  5.67  |
----------------------------------------------------

so here, in database S.no 1 and array index 1 both are the same entry so I want to insert rest value into my database.所以在这里,在数据库中 S.no 1 和数组索引 1 都是同一个条目,所以我想将 rest 值插入到我的数据库中。 So how can I insert?那么如何插入呢?

I am assuming that you are using MySQL database, you can use INSERT IGNORE INTO我假设您使用的是 MySQL 数据库,您可以使用INSERT IGNORE INTO

or INSERT ON DUPLICATE KEY UPDATE插入重复密钥更新

If you want to do it through PHP then you can try this.如果你想通过 PHP 来做,那么你可以试试这个。

$i=0;
foreach($activity as $key=>$val)
{
  $sn_check=mysqli_query($con,"SELECT id FROM table WHERE S.No='$i'");
  if(mysqli_num_rows($sn_check)==0)
  {
     $user_id=$val[$i]['user_id']; //all other values can be catch like this.
     $query_insert=mysqli_query($con,"INSERT QUERY");
  }
$i++;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM