PHP / MySQL INSERT相同数据INTO两个表

时间:2014-01-10 17:52:01

标签: php mysql sql

我有两个共享相同列的表单:NAME, EMAIL, NOMINEE, DEPT, RANK and TIMESTAMP 我想将这些相同的列存储在名为TEACHING_AWARD_ALL_NOMINATIONS的新表中。

我想出了将每个数据存储到不同表中的代码,然后应该有一些代码将共享列存储到TEACHING_AWARD_ALL_NOMINATIONS表中。

我还没有提出代码,请帮助!!!!

$srr = array_map('mysql_escape_string', $_REQUEST);

if ($srr['NOMINATIONTYPE'] == 'STUDENT')
    $fields = Array('NAME', 'EMAIL', 'NOMINEE', 'DEPT', 'COURSE', 'YEARTERM', 'REQUIRED_FOR_MAJOR', 'MAJOR_LEARNING_OBJECTIVES', 'WHAT_EXTENT_INSTRUCTOR_HELP', 'RANK', 'RANK_COMMENT', 'TEXTBOX_1', 'TEXTBOX_2', 'TEXTBOX_3', 'TEXTBOX_4', 'TEXTBOX_5');
else if ($srr['NOMINATIONTYPE'] == 'FACULTY')
    $fields = Array('NAME', 'EMAIL', 'NOMINEE', 'DEPT', 'RANK', 'TEXTBOX_1', 'TEXTBOX_2', 'TEXTBOX_3');
else die('error: no nomination type');

foreach ($fields as $f)
    $$f = $srr[$f];

$qry = "INSERT INTO TEACHING_AWARD_".$srr['NOMINATIONTYPE']."_NOMINATIONS (";
    foreach ($fields as $f) $qry .= $f . ", ";
    $qry = substr($qry, 0, -2);
    $qry .= ") VALUES (";
    foreach ($fields as $f) $qry .= "'" . $$f . "', ";
    $qry = substr($qry, 0, -2);
    $qry .= ")";

$result = mysql_query($qry) or die('An error ocurred: '.mysql_error());

echo 'Success! Thank you for submitting your nomination.';

2 个答案:

答案 0 :(得分:2)

  

警告!正如评论中所述,您的原始代码使用了已弃用的功能,并且存在潜在的安全问题。   查看使用PDO的重构解决方案,是的   也应该使用PDO(而不是你当前的方法)。

查看下面的代码,未经测试但应该完成您的工作。如上所述,它使用PDO - check the docs here

    // obviously, first set your connection parameters $DbHost, $DbName etc.

    //connect to mysql
    $dbh = new PDO("mysql:host=".$DbHost.";dbname=".$DbName, $DbUser, $DbPass, array(PDO::ATTR_PERSISTENT => true));
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbh->query('SET NAMES UTF8'); //assuming you use utf-8 encoding

    //provide values array
    $values = $YourValuesArray;

    //set field types
    $fields = array();
    $fieldsStudent = Array('NAME', 'EMAIL', 'NOMINEE', 'DEPT', 'COURSE', 'YEARTERM', 'REQUIRED_FOR_MAJOR', 'MAJOR_LEARNING_OBJECTIVES', 'WHAT_EXTENT_INSTRUCTOR_HELP', 'RANK', 'RANK_COMMENT', 'TEXTBOX_1', 'TEXTBOX_2', 'TEXTBOX_3', 'TEXTBOX_4', 'TEXTBOX_5');
    $fieldsFaculty = Array('NAME', 'EMAIL', 'NOMINEE', 'DEPT', 'RANK', 'TEXTBOX_1', 'TEXTBOX_2', 'TEXTBOX_3');
    $fieldsAll = array_intersect($fieldsStudent, $fieldsFaculty);

    //pick the proper field set or die
    $fields = ($srr['NOMINATIONTYPE'] == 'STUDENT') ? $fieldsStudent : $fieldsFaculty;
    if(empty($fields)) die('error: no nomination type');

    //set tables
    $table = 'TEACHING_AWARD_'.$srr['NOMINATIONTYPE'].'_NOMINATIONS';
    $tableAll = 'TEACHING_AWARD_ALL_NOMINATIONS';

    //construct fields string
    $strFields = implode(",", $fields);
    $strFieldsAll = implode(",", $fieldsAll);

    //construct the placeholders string
    $strIns = implode(",", array_map(function($item){ return ":".$item; }, $fields)); 
    $strInsAll = implode(",", array_map(function($item){ return ":".$item; }, $fieldsAll)); 

    //insert specific data 
    $sql = "INSERT INTO $table ($strFields) VALUES ($strIns)";
    $sth = $dbh->prepare($sql);

    //bind values to placeholders
    foreach ($fields as $f)
    {
        $sth->bindValue(':' . $f, $values[$f]);
    }

    $sth->execute();

    //insert all data
    $sql = "INSERT INTO $tableAll ($strFieldsAll) VALUES ($strInsAll)";
    $sth = $dbh->prepare($sql);

    //bind values to placeholders
    foreach ($fieldsAll as $f)
    {
        $sth->bindValue(':' . $f, $values[$f]);
    }

    $sth->execute();

编辑:

根据您的评论,要使用PDO选择一组UNIONed结果,您可以使用以下(未经测试的)代码:

    //connect to mysql
    $dbh = new PDO("mysql:host=".$DbHost.";dbname=".$DbName, $DbUser, $DbPass, array(PDO::ATTR_PERSISTENT => true));
    $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
    $dbh->query('SET NAMES UTF8'); //assuming you use utf-8 encoding

    $sql = "SELECT NAME, EMAIL, NOMINEE, DEPT, RANK, TIMESTAMP, 'STUDENT' AS TYPE FROM TEACHING_AWARD_STUDENT_NOMINATIONS 
    UNION 
    SELECT NAME, EMAIL, NOMINEE, DEPT, RANK, TIMESTAMP, 'FACULTY' AS TYPE FROM TEACHING_AWARD_FACULTY_NOMINATIONS";

    $sth = $dbh->prepare($sql);
    $sth->execute();

    //init result array
    $results = array();

    //fetch the results into an array
    while($row = $sth->fetch(PDO::FETCH_ASSOC))
        $results[] = $row;

    //show results or do whatever else you need
    print_r($results);

答案 1 :(得分:1)

您可以尝试制作两个数组,一个用于“共享”列(NAMEEMAIL等),另一个用于“类型特定”列(COURSEYEARTERM等)。然后,在构建SQL语句时,在“共享”列上执行foreach,然后立即使用“类型特定”列来模拟整个表。它可能看起来像这样:

$qry = "INSERT INTO TEACHING_AWARD_".$srr['NOMINATIONTYPE']."_NOMINATIONS (";
    foreach ($fields_shared as $f) $qry .= $f . ", ";
    foreach ($fields_typespecific as $f) $qry .= $f . ", ";
    $qry = substr($qry, 0, -2);
    $qry .= ") VALUES (";
    foreach ($fields_shared as $f) $qry .= "'" . $$f . "', ";
    foreach ($fields_typespecific as $f) $qry .= "'" . $$f . "', ";
    $qry = substr($qry, 0, -2);
    $qry .= ")";

我也同意th3falc0n关于使用更强大的工具准备SQL语句的评论。

另一个考虑因素:为什么不简单地将一个视图从每个特定于类型的表中提取所有共享列(可能使用TEACHING_AWARD_ALL_NOMINATIONS语句),而不是将冗余数据输入UNION表。这样可以防止冗余数据,并且可以更轻松地维护数据(例如,当从某个类型特定的表中删除提名时,它会自动从ALL_NOMINATIONS视图中消失等。)