如何在php中基于外键获取数据

时间:2015-03-30 13:19:02

标签: php mysql

我有两张桌子。表1和表2。

  

表1 - fieldmapping

     

Id(pk),FormField,SFields,Sobject

     

表2 -formfieldmapping

     

form_number和form_id(fk)。

当我使用csv文件将数据插入table1时,值将被插入到table2中,表单编号字段中的表单编号和field_id字段中的Id。当我重复插入值时,然后在table1中不应该插入它应该转到表2,表格编号和表1(“Id”)的引用。请帮忙。

<?php
error_reporting( E_ALL );
if(isset($_POST["Import"]))
{
$host="localhost"; 
$db_user="root";
$db_password="password";
$db='excel'; 
$conn=mysql_connect($host,$db_user,$db_password,$db) or die (mysql_error());
mysql_select_db($db) or die (mysql_error());

echo $filename=$_FILES["file"]["tmp_name"];

 if($_FILES["file"]["size"] > 0)
 {

  $file = fopen($filename, "r");
   while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
   {
         $index=0;

        $query = "SELECT id FROM fieldmapping WHERE FormField ='$emapData[1]'";
    $result = mysql_query($query,$conn) or die(mysql_error());

    while($row = mysql_fetch_array($result)) {
             $index =$row["id"];
        $field=$row["fieldname"];

        }
        echo "index".$index;
        if($index <= 0){
            $sql = "INSERT into fieldmapping(FormField,SFField,SFObject) values('$emapData[1]','$emapData[2]','$emapData[3]')";
echo $sql;
        mysql_query($sql);
        $index=  $conn->insert_id;
        echo "last =".$index;
     }
    if(!$index){
    //$sql = "INSERT into formfieldmapping(form_number) values(1)";
    $sql = "INSERT into formfieldmapping(form_number)values('$emapData[0]')";
        mysql_query($sql); 
    }
else
{
//$sql = "INSERT into formfieldmapping(form_number,field_id) values(1,$index)";
$sql = "INSERT into formfieldmapping(form_number,field_id)values('$emapData[0]',$index)";
mysql_query($sql); 
}
        //mysql_query($sql);
echo $sql;
echo "<br>";


  }
    echo "CSV File has been successfully Imported";
}
    else
    {
     echo "Invalid File:Please Upload CSV File";
    }
  } 
   fclose($file);
mysql_close($conn);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Import CSV/Excel file</title>
</head>
<body>
<form enctype="multipart/form-data" method="post">
<table border="1" width="40%" align="center">
<tr >
<td colspan="2" align="center"><strong>Import CSV/Excel file</strong></td>
</tr>

<tr>
<td align="center">CSV/Excel File:</td><td><input type="file" name="file" id="file"></td></tr>
<tr >
<td colspan="2" align="center"><input type="submit" name="Import" value="Import"></td>
</tr>
</table>
</form>
</body>
</html>

0 个答案:

没有答案