从重复的文本字段插入数据库,如果不是空的php sql

时间:2016-02-24 13:50:57

标签: php mysql database

我有一个包含3个表的数据库 - 作者,研究和案例研究。

作者有专栏AuthorId(自动增量,PK),F_nameL_nameEmailContact

Study包含StudyID列(自动增量,PK),TitleSummary

Casestudy - AuthorIdFK,参考Author.AuthorId),StudyIdFK,参考Study.StudyId),{ {1}}(日期时间)。

我有一个声明,它将数据插入到每个表中(获取AuthorId和StudyID的ID)并插入到casestudy中。

我的问题是,如果只有一位作者,我如何避免将第二位作者的数据传递到数据库中。否则它只存储空行。作者webform https://jsfiddle.net/7un2yf9g/的一个例子。它复制整个容器并创建一个具有不同名称的相同副本。

我的代码如下:

Submitted

1 个答案:

答案 0 :(得分:1)

首先,从未定义Author_ID2时定义变量的方式:

$AuthorTitle = mysqli_real_escape_string($con, ($_POST['AuthorTitle']));
$AuthorTitle = mysqli_real_escape_string($con, ($_POST['AuthorTitle_ID2']));

您只需使用$AuthorTitle中的值覆盖$_POST['AuthorTitle_ID2'],并且根本不定义$AuthorTitle_ID2

接下来,您拥有的SQL语句只会将第二个authorstudy中的casestudy相关联,因为LAST_INSERT_ID()将仅返回上一个插入记录的ID即使一个陈述实际上插入了几条记录。

最后,有IF statement in MySQL

$AuthorTitle       = mysqli_real_escape_string($con, ($_POST['AuthorTitle']));
$AuthorTitle_ID2   = mysqli_real_escape_string($con, ($_POST['AuthorTitle_ID2']));
$F_Name            = mysqli_real_escape_string($con, ($_POST['first_name']));
$F_Name_ID2        = mysqli_real_escape_string($con, ($_POST['first_name_ID2']));
$L_Name            = mysqli_real_escape_string($con, ($_POST['last_name']));
$L_Name_ID2        = mysqli_real_escape_string($con, ($_POST['last_name_ID2']));
$Email             = mysqli_real_escape_string($con, ($_POST['email']));
$Email_ID2         = mysqli_real_escape_string($con, ($_POST['email_ID2']));
$Contactauthor     = mysqli_real_escape_string($con, ($_POST['contact']));
$Contactauthor_ID2 = mysqli_real_escape_string($con, ($_POST['contact_ID2']));
$Title             = mysqli_real_escape_string($con, ($_POST['Title']));
$Summary           = mysqli_real_escape_string($con, ($_POST['Summary']));

mysqli_multi_query($con,"
START TRANSACTION;
    INSERT INTO study(Title, Summary)
    VALUES('$Title','$Summary');
    SET @StudyId = LAST_INSERT_ID();

    INSERT INTO author(AuthorTitle, F_Name, L_Name, Email, Contact)
    VALUES('$AuthorTitle','$F_Name','$L_Name','$Email','$Contactauthor');
    SET @AuthorId = LAST_INSERT_ID();

    INSERT INTO casestudy(AuthorId, StudyId, Submitted)
    VALUES(@AuthorId, @StudyId, NOW());

    IF ('$AuthorTitle_ID2' <> '' OR '$F_Name_ID2' <> '' OR '$L_Name_ID2' <> '' OR '$Email_ID2' <> '' OR '$Contactauthor_ID2' <> '') THEN
        INSERT INTO author(AuthorTitle, F_Name, L_Name, Email, Contact)
        VALUES('$AuthorTitle_ID2','$F_Name_ID2','$L_Name_ID2','$Email_ID2','$Contactauthor_ID2');
        SET @AuthorId = LAST_INSERT_ID();

        INSERT INTO casestudy(AuthorId, StudyId, Submitted)
        VALUES(@AuthorId, @StudyId, NOW());
    END IF;
COMMIT;
");