Hi guys,

I am programming an Android App and I am trying to do a multiple SQL insert but it doesn't work. Can someone help me? And I also want to have the ID from the new created student. How do I get that ?

<?PHP

if($_SERVER['REQUEST_METHOD']=='POST'){

    $Name = $_POST['Name'];
    $Surname = $_POST['Surname'];
    $Street = $_POST['Street'];
    $City = $_POST['City'];


    if($Name == '' || $Surname == '' || $Street == '' || $City == ''){

        echo 'Please fill all values';

    }else{

        require_once('dbConnect.php');

        $sql = "INSERT INTO T_Student(Name,Surname,Street,City,F_ID_Teacher) VALUES('$Name','$Vorname','$Strasse', '$Plz','2')";

        $sql .= "INSERT INTO T_Class(Subjekt,Number,F_ID_Student) VALUES('','','I WANT HERE THE ID FROM THE NEW CREATED STUDENT')";

        $sql .= "INSERT INTO T_School(Name,Street,City,F_ID_Student) VALUES('','','','I WANT HERE THE ID FROM THE NEW CREATED STUDENT')";   

    if(mysqli_multi_query($con,$sql)){

        echo 'Added Student';

    }else{

        echo 'Error! Try again';

    }
    }
    mysqli_close($con);
    }

?> 

Not tested but try:

    $sql = <<<EOD
    INSERT INTO T_Student(Name, Surname, Street, City, F_ID_Teacher) VALUES('$Name', '$Vorname', '$Strasse', '$Plz', '2');
    SET @id = last_insert_id();
    INSERT INTO T_Class(Subjekt, Number, F_ID_Student) VALUES('', '', @id);
    INSERT INTO T_School(Name, Street, City, F_ID_Student) VALUES('', '', '', @id)
EOD;

Here the student id is retrived by the second query which sets a variable @id and returns the value in the following queries. It works if the student id is an auto_increment column type.

More information about the heredoc syntax:

commented: sry I take it back it worked but only with T_Student and T_Class. T_school didn't worked +0

@Natsu123 please reply with a post, not with comments. Can you show the table schema for T_school? In practice run:

show create table T_school;

And return the output here.

Check if your system is PHP5, because this query is supported in PHP5

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.