简体   繁体   English

数据未使用外键插入数据库

[英]Data not getting inserted into database with foreign key

I have built a multidimensional array that contains the Table name, Column name and values to be inserted. 我建立了一个多维数组,其中包含表名,列名和要插入的值。 I convert this array into an INSERT command and then execute it. 我将此数组转换为INSERT命令,然后执行它。 Everything has been working as intended until I tried inserting into the same table twice. 一切都按预期进行,直到我尝试两次插入同一张表。 I have a parent table company . 我有一家母餐桌company All of the other 19 tables in the database contain a column named CompanyID which is a foreign key that references the CompanyID column in the company table. 数据库中的所有其他19个表都包含一个名为CompanyID的列,这是一个外键,它引用了company表中的CompanyID列。 What I need to do is be able to insert into one of the child tables twice for an additional address or contact people for that company. 我需要做的是能够两次插入其中一个子表以获取其他地址,或与该公司的联系人联系。 For some reason if I duplicate the array so that it should add into a certain table twice it will only insert once. 由于某种原因,如果我复制数组,以便它应该两次添加到某个表中,则只会插入一次。 No errors are thrown either. 也不会引发任何错误。 Can someone help me sort this out. 有人可以帮我解决这个问题吗?

Here is the array: 这是数组:

$surveyResults = array(
                    'additionallocations' => array(
                            'CompanyID' => $CompanyID,
                            'Address' => $Address,
                            'City' => $City,
                            'State' => $State,
                            'Zip' => $Zip,
                            'Country' => $Country,
                        ),
                    'sales' => array(
                        'CompanyID' => $CompanyID,
                        'FirstName' => $FirstName,
                        'LastName' => $LastName,
                        'Email' => $Email,
                        'Phone' => $Phone
                        ),
                    'owner' => array(
                        'CompanyID' => $CompanyID,
                        'FirstName' => $FirstName,
                        'LastName' => $LastName,
                        'Email' => $Email,
                        'Phone' => $Phone
                        ),
                    'decisionmaker' => array(
                        'CompanyID' => $CompanyID,
                        'FirstName' => $FirstName,
                        'LastName' => $LastName,
                        'Email' => $Email,
                        'Phone' => $Phone
                        ),
                    'decisionmaker' => array(
                        'CompanyID' => $CompanyID,
                        'FirstName' => $FirstName,
                        'LastName' => $LastName,
                        'Email' => $Email,
                        'Phone' => $Phone
                        )
                    );

Notice decisionmaker is listed twice. 通知decisionmaker被列出两次。 This should insert into the database identical information but it only inserts once. 这应该将相同的信息插入数据库,但只能插入一次。 I have even tried hard coding the last decisionmaker array values so they are all different besides the CompanyID and it still will not insert. 我什至尝试对最后一个decisionmaker数组值进行硬编码,因此除了CompanyID以外,它们都不同,并且仍然不会插入。

Below is how I am creating the SQL statement and executing it. 下面是我创建和执行SQL语句的方式。

foreach($surveyResults as $key => $table){
                $sql1 = null;
        $keys = array_keys($table);
            $values = null;
            $x = 1;

            foreach($table as $row => $value) {
                $values .= "'$value'";
                if($x < count($keys)) {
                    $values .= ', ';
                }
                $x++;
            }

        $sql1 = $conn->prepare("INSERT INTO {$key} (`" . implode('`, `', $keys) . "`) VALUES ({$values});");
        $sql1->execute();

        echo $CompanyID;
        echo "Successful  <br/>";
    }

Table creation query: 表创建查询:

CREATE TABLE IF NOT EXISTS `decisionmaker` (
  `id` int(3) NOT NULL AUTO_INCREMENT,
  `CompanyID` int(3) NOT NULL,
  `FirstName` varchar(30) NOT NULL,
  `LastName` varchar(30) NOT NULL,
  `Email` varchar(50) NOT NULL,
  `Phone` varchar(15) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `CompanyID` (`CompanyID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=24 ;

--
-- Constraints for dumped tables
--

--
-- Constraints for table `decisionmaker`
--
ALTER TABLE `decisionmaker`
  ADD CONSTRAINT `DecisionMaker_ibfk_1` FOREIGN KEY (`CompanyID`) REFERENCES `company` (`CompanyID`) ON DELETE CASCADE ON UPDATE CASCADE;

This is the table dump for company: 这是公司的表转储:

CREATE TABLE IF NOT EXISTS `company` (
  `CompanyID` int(3) NOT NULL AUTO_INCREMENT,
  `Name` varchar(50) NOT NULL,
  `Address` varchar(50) NOT NULL,
  `City` varchar(50) NOT NULL,
  `State` varchar(30) NOT NULL,
  `Zip` int(5) NOT NULL,
  `Country` varchar(20) NOT NULL,
  `Website` varchar(50) NOT NULL,
  `NOL` int(2) NOT NULL DEFAULT '1',
  PRIMARY KEY (`CompanyID`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=35 ;

The problem is rather simple 问题很简单

$surveyResults has the same key for decisionmaker. $ surveyResults具有与决策者相同的密钥。

If you print_r($surveyResults); 如果您print_r($surveyResults); before your foreach for inserting data into your database, you will realise that there is not two decisionmaker keys, but only one. 您之前foreach将数据插入到数据库中,你会发现,有不是两个decisionmaker键,但只有一个。

This is because an array can not contain the same key twice. 这是因为数组不能两次包含相同的键。 For example 例如

    $array = array( 'key' => 'for', 'key' => 'example' );
    print_r($array);

will only output 只会输出

Array (
    [key] => example
)

A simple way to fix this: 解决此问题的简单方法:

  1. on the second decisionmaker inside surveyResults , change the key to decisionmaker2 第二decisionmaker内部surveyResults ,改变关键decisionmaker2
  2. before foreach($table as $row => $value) { add the following code: foreach($table as $row => $value) {添加以下代码:
     if ($key == 'decisionmaker2') 如果($ key =='decisionmaker2') 
    $key = 'decisionmaker'; $ key ='决策者';

That should resolve the issue that you are seeing :) 那应该可以解决您看到的问题:)

Can you post the create statement for this table? 您可以为该表发布create语句吗? FOREIGN KEYS require you to specify how to handle duplicates. 外国密钥要求您指定如何处理重复项。

Try the following code and just check how many times insert is being done. 请尝试以下代码,然后检查插入次数。

And also set error mode on in your php settings so that you can see the error message. 并在您的php设置中设置错误模式,以便您可以看到错误消息。

After doing reply with your result. 在对您的结果进行回复之后。

foreach($surveyResults as $key => $table){
                $sql1 = null;
        $keys = array_keys($table);
            $values = null;
            $x = 1;

            foreach($table as $row => $value) {
                $values .= "'$value'";
                if($x < count($keys)) {
                    $values .= ', ';
                }
                $x++;
            }

        $sql1 = $conn->prepare("INSERT INTO {$key} (`" . implode('`, `', $keys) . "`) VALUES ({$values});");
        if($sql1->execute())//changed code
          echo $CompanyID;

        echo "Successful  <br/>";
    }

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

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