Jump to content

Form/Foreign Keys MySQL add data through PHP help


Darkmatter5

Recommended Posts

Here's my example:

 

Table - state

state_id

state

 

Table - client

client_id

first_name

last_name

state_id

 

1. How do I make a relationship between tables client and state by way of the state_id fields of each table?

2. Using the following dropdown list of states, how would I go about storing the selected state from the list into the employee table at the field state_id?

 

<?php
  include 'library/dbconfig.php';
  include 'library/opendb.php';

  $query="SELECT state_id, state, state_abbrev
          FROM byrnjobdb.states
          ORDER BY state ASC";
  $result=mysql_query($query);
  echo "<select id='state_id' method='get' tabindex='7'>";
  echo "<option>---Select---</option>";
  while ($row=mysql_fetch_array($result)) {
    $r1=$row['state_id'];
    $r2=$row['state']. ", " .$row['state_abbrev'];
    echo "<option value='$r1'>$r2</option>";
  }
  echo "</select>";

  include 'library/closedb.php';
?>

 

When I simply do something like...

<?php
  if(isset($_POST['addclient'])) {
    include 'library/dbconfig.php';
    include 'library/opendb.php';

    $first_name=$_POST['first_name'];
    $last_name=$_POST['last_name'];
    $state_id=$_POST['state_id'];

    //put new client data from form into the clients table
    foreach (array('first_name', 'last_name','state_id') as $field) {
      if ($_POST[$field]) {
        $field_name[]=$field;
        $field_value[]="'{$_POST[$field]}'";
      }
    }

    $fields=join(", ", $field_name);
    $values=join(", ", $field_value);
    $insertdata="INSERT INTO byrnjobdb.clients ($fields) VALUES ($values)";
    mysql_query($insertdata) or die(mysql_error() . ": $insertdata");

    echo "NEW CLIENT ADDED...<br>";
    include 'library/closedb.php';
  }
?>

I get the following error.

Cannot add or update a child row: a foreign key constraint fails (`byrnjobdb/clients`, CONSTRAINT `fk_state` FOREIGN KEY(`state_id`)
REFERENCES `states` (`state_id`) ON DELETE CASCADE ON UPDATE CASCADE): INSERT INTO byrnjobdb.clients (first_name, company_name,
contact_title, address, city, zip_code, home_phone, work_phone, work_phone_extension, fax_phone, email) VALUES ('Joe', 'nothing corp', 'CEO',
'123 Anywhere St', 'anywhere', '90210', '111-111-1111', '222-222-2222', '1234', '333-333-3333', '123')

 

Can anyone help please??

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.