2017-04-08 6 views
1

Ich baue einen Studienplaner.Kind Hilfe beim Einfügen in mehrere Tabellen

Ich habe eine Entwurfsschnittstelle und die Datenbank entworfen und ich versuche derzeit, Testregistrierungsdetails in die Datenbank einzufügen, aber ich bin seit drei Tagen auf diesem jetzt ohne Erfolg gewesen. Ich werde eine Art Hilfe sehr schätzen, wenn ich darauf hinweise, was ich falsch gemacht habe.

Die Meldung/Fehler Ich erhalte ist wie so:

Connected successfully 

Error details for Result 2: Cannot add or update a child row: a foreign key constraint fails (`p00702`.`universityreferences`, CONSTRAINT `universityreferences_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`userid`) ON UPDATE CASCADE). 

Error details for Result 3: Cannot add or update a child row: a foreign key constraint fails (`p00702`.`mobiles`, CONSTRAINT `mobiles_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`userid`) ON UPDATE CASCADE). 

Error details for Result 4: Cannot add or update a child row: a foreign key constraint fails (`p00702`.`logins`, CONSTRAINT `logins_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`userid`) ON UPDATE CASCADE). 

All queries were rolled back 

Ich habe auch bemerkt, dass $id = $mysqli->insert_id; direkt nach der ersten Abfrage funktioniert auch nicht und ich weiß nicht, warum, aber ich vermute, dass es das sein kann Ursache.

Mein PHP-Code ist:

<?php 
if (isset($_POST['submitted'])) { 

    include 'serverSide/connectToServer.php'; 

    $firstName = $_POST['firstName']; 
    $lastName = $_POST['lastName']; 
    $studentId = $_POST['studentId']; 
    $mobile = $_POST['mobile']; 
    $username = $_POST['username']; 
    $password = $_POST['password']; 

    //turn off autocommit 
    $mysqli->autocommit(false); 

    $flag = true; 

    // attempt insert query executions 
    $query1 = "INSERT INTO users (firstname, lastname) VALUES ('$firstName', '$lastName');"; 
    $id = $mysqli->insert_id; 

    $query2 = "INSERT INTO universityreferences (userid, universityreference) VALUES ('$id', '$studentId');"; 
    $id2 = $mysqli->insert_id; 

    $query3 = "INSERT INTO mobiles (userid, mobile) VALUES ('$id2', '$mobile');"; 
    $id3 = $mysqli->insert_id; 

    $query4 = "INSERT INTO logins (userid, username, password) VALUES ('$id3', '$username', '$password');"; 

    $result1 = mysqli_query($mysqli, $query1); 
    if (!$result1) { 
     $flag = false; 
     echo "Error details for Result 1: " . mysqli_error($mysqli) . "."; 
    } 

    $result2 = mysqli_query($mysqli, $query2); 
    if (!$result2) { 
     $flag = false; 
     echo "Error details for Result 2: " . mysqli_error($mysqli) . "."; 
    } 

    $result3 = mysqli_query($mysqli, $query3); 
    if (!$result3) { 
     $flag = false; 
     echo "Error details for Result 3: " . mysqli_error($mysqli) . "."; 
    } 

    $result4 = mysqli_query($mysqli, $query4); 
    if (!$result4) { 
     $flag = false; 
     echo "Error details for Result 4: " . mysqli_error($mysqli) . "."; 
    } 

    if ($flag) { 
     mysqli_commit($mysqli); 
     echo "All queries were executed successfully"; 
    } else { 
     mysqli_rollback($mysqli); 
     echo "All queries were rolled back"; 
    } 

    mysqli_close($mysqli); 
} 
?> 

<!DOCTYPE html> 
<!-- 
To change this license header, choose License Headers in Project Properties. 
To change this template file, choose Tools | Templates 
and open the template in the editor. 
--> 

<html> 
    <head> 
     <meta charset="UTF-8"> 
     <link rel="shortcut icon" type="image/png" href="/images/favicon.png"/> 
     <title>Just-Read</title> 
     <link rel="stylesheet" type="text/css" href="css/styles.css"> 
    </head> 
    <body> 
     <!-- Link to external JavaScript file --> 
     <script src="javascript/validator.js"></script> 
     <div id="container"> 
      <div id="header"> 
       <!-- Web site Logo --> 
       <div class="logo"> 
        <img src="images/logo.png" width="128" height="93.5" alt="Logo"/><br><br> 
       </div> 
       <div id="logoText"> 
        <h1>Just Read</h1> 
       </div> 
      </div> 
      <div id="leftColumn"> 
       <h4>The ultimate study planner</h4> 
      </div> 
      <div id="rightColumn"> 
       <!-- Registration Form --> 
       <h3>Please fill out the form below</h3> 
       <form name="Register" action="registration.php" onsubmit="return registrationValidator()" autocomplete="on" method="POST"> 
        <!--According to YouTuber Ralph Philips, this makes sure a blank form cannot be submitted to the database--> 
        <input type="hidden" name="submitted" value="true"/> 
        <div class="register"> 
         <label><b>First Name*</b></label> 
         <input type="text" id="firstName" name="firstName" placeholder="Enter your first name" autofocus/> 
         <label><b>Last Name*</b></label> 
         <input type="text" id="lastName" name="lastName" placeholder="Enter your last name" /> 
         <label><b>Student ID*</b></label> 
         <input type="text" id="studentId" name="studentId" placeholder="Enter your university ID" /> 
         <label><b>Mobile</b></label> 
         <input type="text" id="mobile" name="mobile" placeholder="Enter your phone number" /> 
         <label><b>Email Address (Username)*</b></label> 
         <input type="email" id="username" name="username" placeholder="Enter your email address" /> 
         <label><b>Password*</b></label> 
         <input type="password" id="password" name="password" placeholder="Enter your password" /> 

         <button type="submit">Register</button> 
        </div> 
        <div id="back"> 
         <a href="index.php">Back</a> 
        </div> 
        <div id="mandatoryFields"> 
         <h4>* Mandatory Fields</h4> 
        </div> 
       </form> 
      </div> 
      <div id="footer"> 
       Copyright &copy; 2017, Chizzy Meka. 
      </div> 
     </div> 
    </body> 
</html> 

Meine volle MySQL-Code ist:

-- phpMyAdmin SQL Dump 
-- version 4.6.4 
-- https://www.phpmyadmin.net/ 
-- 
-- Host: 127.0.0.1 
-- Generation Time: Apr 08, 2017 at 06:49 PM 
-- Server version: 5.7.14 
-- PHP Version: 5.6.25 

SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; 
SET time_zone = "+00:00"; 


/*!40101 SET @[email protected]@CHARACTER_SET_CLIENT */; 
/*!40101 SET @[email protected]@CHARACTER_SET_RESULTS */; 
/*!40101 SET @[email protected]@COLLATION_CONNECTION */; 
/*!40101 SET NAMES utf8mb4 */; 

-- 
-- Database: `p00702` 
-- 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `comments` 
-- 

CREATE TABLE `comments` (
    `commentid` int(10) NOT NULL, 
    `modulecodeid` int(10) NOT NULL, 
    `comment` text, 
    `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `logins` 
-- 

CREATE TABLE `logins` (
    `loginid` int(10) NOT NULL, 
    `userid` int(10) NOT NULL, 
    `username` varchar(100) NOT NULL, 
    `password` varchar(100) NOT NULL, 
    `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `mobiles` 
-- 

CREATE TABLE `mobiles` (
    `mobileid` int(10) NOT NULL, 
    `userid` int(10) NOT NULL, 
    `mobile` varchar(10) DEFAULT NULL, 
    `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `modulecodes` 
-- 

CREATE TABLE `modulecodes` (
    `modulecodeid` int(10) NOT NULL, 
    `userid` int(10) NOT NULL, 
    `modulecode` varchar(10) NOT NULL, 
    `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `moduletitles` 
-- 

CREATE TABLE `moduletitles` (
    `moduletitleid` int(10) NOT NULL, 
    `modulecodeid` int(10) NOT NULL, 
    `moduletitle` varchar(100) NOT NULL, 
    `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `studyplans` 
-- 

CREATE TABLE `studyplans` (
    `studyplan` int(10) NOT NULL, 
    `modulecodeid` int(10) NOT NULL, 
    `studydate` date NOT NULL, 
    `numberofstudyhours` int(10) NOT NULL, 
    `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `universityreferences` 
-- 

CREATE TABLE `universityreferences` (
    `universityreferenceid` int(10) NOT NULL, 
    `userid` int(10) NOT NULL, 
    `universityreference` varchar(100) NOT NULL, 
    `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

-- -------------------------------------------------------- 

-- 
-- Table structure for table `users` 
-- 

CREATE TABLE `users` (
    `userid` int(10) NOT NULL, 
    `firstname` varchar(100) NOT NULL, 
    `lastname` varchar(100) NOT NULL, 
    `created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP 
) ENGINE=InnoDB DEFAULT CHARSET=latin1; 

-- 
-- Indexes for dumped tables 
-- 

-- 
-- Indexes for table `comments` 
-- 
ALTER TABLE `comments` 
    ADD PRIMARY KEY (`commentid`), 
    ADD KEY `modulecodeid` (`modulecodeid`); 

-- 
-- Indexes for table `logins` 
-- 
ALTER TABLE `logins` 
    ADD PRIMARY KEY (`loginid`), 
    ADD KEY `userid` (`userid`); 

-- 
-- Indexes for table `mobiles` 
-- 
ALTER TABLE `mobiles` 
    ADD PRIMARY KEY (`mobileid`), 
    ADD KEY `userid` (`userid`); 

-- 
-- Indexes for table `modulecodes` 
-- 
ALTER TABLE `modulecodes` 
    ADD PRIMARY KEY (`modulecodeid`), 
    ADD KEY `userid` (`userid`); 

-- 
-- Indexes for table `moduletitles` 
-- 
ALTER TABLE `moduletitles` 
    ADD PRIMARY KEY (`moduletitleid`), 
    ADD KEY `modulecodeid` (`modulecodeid`); 

-- 
-- Indexes for table `studyplans` 
-- 
ALTER TABLE `studyplans` 
    ADD PRIMARY KEY (`studyplan`), 
    ADD KEY `modulecode` (`modulecodeid`); 

-- 
-- Indexes for table `universityreferences` 
-- 
ALTER TABLE `universityreferences` 
    ADD PRIMARY KEY (`universityreferenceid`), 
    ADD KEY `userid` (`userid`); 

-- 
-- Indexes for table `users` 
-- 
ALTER TABLE `users` 
    ADD PRIMARY KEY (`userid`); 

-- 
-- AUTO_INCREMENT for dumped tables 
-- 

-- 
-- AUTO_INCREMENT for table `comments` 
-- 
ALTER TABLE `comments` 
    MODIFY `commentid` int(10) NOT NULL AUTO_INCREMENT; 
-- 
-- AUTO_INCREMENT for table `logins` 
-- 
ALTER TABLE `logins` 
    MODIFY `loginid` int(10) NOT NULL AUTO_INCREMENT; 
-- 
-- AUTO_INCREMENT for table `mobiles` 
-- 
ALTER TABLE `mobiles` 
    MODIFY `mobileid` int(10) NOT NULL AUTO_INCREMENT; 
-- 
-- AUTO_INCREMENT for table `modulecodes` 
-- 
ALTER TABLE `modulecodes` 
    MODIFY `modulecodeid` int(10) NOT NULL AUTO_INCREMENT; 
-- 
-- AUTO_INCREMENT for table `moduletitles` 
-- 
ALTER TABLE `moduletitles` 
    MODIFY `moduletitleid` int(10) NOT NULL AUTO_INCREMENT; 
-- 
-- AUTO_INCREMENT for table `studyplans` 
-- 
ALTER TABLE `studyplans` 
    MODIFY `studyplan` int(10) NOT NULL AUTO_INCREMENT; 
-- 
-- AUTO_INCREMENT for table `universityreferences` 
-- 
ALTER TABLE `universityreferences` 
    MODIFY `universityreferenceid` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 
-- 
-- AUTO_INCREMENT for table `users` 
-- 
ALTER TABLE `users` 
    MODIFY `userid` int(10) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; 
-- 
-- Constraints for dumped tables 
-- 

-- 
-- Constraints for table `comments` 
-- 
ALTER TABLE `comments` 
    ADD CONSTRAINT `comments_ibfk_1` FOREIGN KEY (`modulecodeid`) REFERENCES `modulecodes` (`modulecodeid`) ON UPDATE CASCADE; 

-- 
-- Constraints for table `logins` 
-- 
ALTER TABLE `logins` 
    ADD CONSTRAINT `logins_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`userid`) ON UPDATE CASCADE; 

-- 
-- Constraints for table `mobiles` 
-- 
ALTER TABLE `mobiles` 
    ADD CONSTRAINT `mobiles_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`userid`) ON UPDATE CASCADE; 

-- 
-- Constraints for table `modulecodes` 
-- 
ALTER TABLE `modulecodes` 
    ADD CONSTRAINT `modulecodes_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`userid`) ON UPDATE CASCADE; 

-- 
-- Constraints for table `moduletitles` 
-- 
ALTER TABLE `moduletitles` 
    ADD CONSTRAINT `moduletitles_ibfk_1` FOREIGN KEY (`modulecodeid`) REFERENCES `modulecodes` (`modulecodeid`) ON UPDATE CASCADE; 

-- 
-- Constraints for table `studyplans` 
-- 
ALTER TABLE `studyplans` 
    ADD CONSTRAINT `studyplans_ibfk_1` FOREIGN KEY (`modulecodeid`) REFERENCES `modulecodes` (`modulecodeid`) ON UPDATE CASCADE; 

-- 
-- Constraints for table `universityreferences` 
-- 
ALTER TABLE `universityreferences` 
    ADD CONSTRAINT `universityreferences_ibfk_1` FOREIGN KEY (`userid`) REFERENCES `users` (`userid`) ON UPDATE CASCADE; 

/*!40101 SET [email protected]_CHARACTER_SET_CLIENT */; 
/*!40101 SET [email protected]_CHARACTER_SET_RESULTS */; 
/*!40101 SET [email protected]_COLLATION_CONNECTION */; 

Sie im Voraus für Ihre Unterstützung danken.

+0

Mögliche Duplikat [Mysql Fehler 1452 - kann nicht hinzugefügt oder ein Kind Zeile aktualisieren: ein Fremdschlüssel nicht] (http: // Stackoverflow. com/questions/1253459/mysql-error-1452-kann nicht-hinzufügen-oder-update-a-Kind-Zeile-ein-Fremdschlüssel-constraint-fa) – asteriskTheServer

+0

Hallo, @asteriskTheServer, Vielen Dank für die vorgeschlagene ähnliche Frage, Allerdings hatte ich diesen Post schon gesehen und er hat mich nicht genug informiert, bevor ich mich entschied, meinen eigenen Posten zu machen. Obwohl ich der Meinung bin, dass es Ähnlichkeiten gibt, glaube ich, dass mein PHP falsch ist und die vorgeschlagene Antwort mir dabei nicht helfen kann. Außerdem habe ich es mit mehr Tischen zu tun, was die Sache schwieriger macht, also bitte, ich werde es schätzen, wenn jemand in meinen eigenen Fall schauen und Ratschläge geben kann. –

Antwort

1

Das Problem ist, dass Sie versuchen, die letzte eingefügte ID vor Abfrage auszuführen. Zum Beispiel:

$query1 = "INSERT INTO users (firstname, lastname) VALUES ('$firstName', '$lastName');"; 
$id = $mysqli->insert_id; 

In dem obigen Code definieren Sie nur die SQL-Anweisung, aber Sie es nicht ausführen. Daher wird die letzte Einfüge-ID nichts zurückgeben.

Führen Sie die insert_id() Methode nur, wenn Sie die Abfrage ausführen:

$result1 = mysqli_query($mysqli, $query1); 
+0

Vielen Dank, @Shadow, ich werde Sie wissen lassen, wie es funktioniert. –

+0

Es funktioniert jetzt. Vielen Dank und vielleicht finden Sie auch Hilfe, wenn Sie es brauchen! –

1

Das Problem ist, dass Sie mysqli->insert_id verwenden, bevor die Abfrage ausgeführt wurde. Wenn Sie die erste Abfrage definieren, hat die Datenbank die ID noch nicht generiert, da die Einfügung nicht ausgeführt wurde.

Der richtige Weg, dies zu tun ist

$query1 = "INSERT INTO users (firstname, lastname) VALUES ('$firstName', '$lastName');"; 

$result1 = mysqli_query($mysqli, $query1); 
if (!$result1) { 
    $flag = false; 
    echo "Error details for Result 1: " . mysqli_error($mysqli) . "."; 
} 

$id = $mysqli->insert_id; 

//go on with the next insert 
//defining the query, executing it and then using the generated id 

Alle, die Fehlermeldung durch die Tatsache verursacht werden, dass, wenn Sie query2 laufen, sind Sie den Fremdschlüssel verletzen Sie auf user_id definiert haben, denn du bist Einfügen einer Zeile mit einem leeren Wert.

+0

Vielen Dank, @Stefano Zanini, ich werde Sie wissen lassen, wie es funktioniert. –

+0

Es funktioniert jetzt. Vielen Dank und vielleicht finden Sie auch Hilfe, wenn Sie es brauchen! –

Verwandte Themen