Yamaha32088
Yamaha32088

Reputation: 4163

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. Everything has been working as intended until I tried inserting into the same table twice. I have a parent table 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. 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. 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.

Below is how I am creating the SQL statement and executing it.

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 ;

Upvotes: 1

Views: 744

Answers (3)

Tim Groeneveld
Tim Groeneveld

Reputation: 9029

The problem is rather simple

$surveyResults has the same key for decisionmaker.

If you 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.

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
  2. before foreach($table as $row => $value) { add the following code:
    if ($key == 'decisionmaker2')
    $key = 'decisionmaker';

That should resolve the issue that you are seeing :)

Upvotes: 1

sud_shan
sud_shan

Reputation: 303

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.

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/>";
    }

Upvotes: 0

willthiswork89
willthiswork89

Reputation: 617

Can you post the create statement for this table? FOREIGN KEYS require you to specify how to handle duplicates.

Upvotes: 0

Related Questions