sql >> Base de Datos >  >> RDS >> Mysql

insertar en la base de datos desde un campo de texto duplicado si no está vacío php sql

En primer lugar, la forma en que tiene sus variables definidas en el momento Author_ID2 nunca se define:

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

Aquí simplemente anulas $AuthorTitle con el valor de $_POST['AuthorTitle_ID2'] y no defina $AuthorTitle_ID2 en absoluto.

A continuación, la declaración SQL tal como la tiene solo vincularía el segundo author con el study en casestudy porque LAST_INSERT_ID() devolvería la identificación del último registro insertado solo incluso si en realidad hubo varios registros insertados por una declaración.

Y finalmente, hay una sentencia IF en 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;
");