2015-12-02 85 views
0

我有一個PHP頁面,它填充了我數據庫的2個不同表格。將數據添加到表數據庫時出現外鍵問題

在我添加一個新列然後創建一個外鍵後,數據不能再被插入到該表中。如果我刪除外鍵,那麼它再次運作...任何人都經歷過這樣的事情?

這是我如何填充表都來自同一個頁面:

include("../includes/connection.php"); 

$name = mysqli_real_escape_string($link, $_POST['name']); 
$email = mysqli_real_escape_string($link, $_POST['email']); 
$number = mysqli_real_escape_string($link, $_POST['number']); 
$device = mysqli_real_escape_string($link, $_POST['device']); 
$price = mysqli_real_escape_string($link, $_POST['price']); 
$payment = mysqli_real_escape_string($link, $_POST['payment']); 
$status = mysqli_real_escape_string($link, $_POST['status']); 
$model = mysqli_real_escape_string($link, $_POST['model']); 
$problem = mysqli_real_escape_string($link, $_POST['problem']); 

// attempt insert query execution 

$sql = "INSERT INTO customer (name, mail, number, device, price, paymenttype,status,date) VALUES ('$name', '$email', '$number', '$device', '$price', '$payment','$status',NOW())"; 

if(mysqli_query($link, $sql)){ 
    // echo "Records added successfully."; 
    header("location:add-customer.php?message=The customer has been added to the database1"); 
    } else{ 
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); 
}   
$sql = "INSERT INTO job (device, model, problem, status) VALUES ('$device', '$model', '$problem', '$status')"; 

if(mysqli_query($link, $sql)){ 
    // echo "Records added successfully."; 
    header("location:add-customer.php?message=The customer has been added to the database2"); 
} else{ 
    echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); 
} mysqli_close($link);?> 

而且,這是一個照片可能更好地解釋我想達到的目標:

  1. 的一箇中背景是JOB_Table。
  2. JOB_Table的每一行都有一個「info」按鈕,而onclick應顯示從CUSTOMER_table收集的詳細信息。

舉例:第一行中
按鈕「信息」,希望得到客戶表的第一行。第二行中
按鈕「信息」,希望得到客戶表的第二行...

enter image description here

---------模式彈出代碼,收集客戶的表後點擊-----

<div class="modal fade" id="myModal" role="dialog"> 
    <div class="modal-dialog modal-lg"> 
    <!-- Modal content--> 
     <div class="modal-content"> 
     <div class="modal-header"> 
      <button type="button" class="close" data-dismiss="modal">&times;</button> 
      <h4 class="modal-title">Customer Information</h4> 
     </div> 
     <div class="modal-body"> 


     <?php 

include("../includes/connection.php"); 

if ($link->connect_errno > 0) { 
    die('Unable to connect to database [' . $link->connect_error . ']'); 
} 
$sql = "SELECT id,name,mail,number,price,paymenttype,faktura,date from customer WHERE  id = '[job_id]' "; 



if (!$result = $link->query($sql)) { 
    die('There was an error running the query [' . $link->error . ']'); 
} 
echo " 
<table class='table'> 
    <thead> 
     <tr>"; 
/* Get field information for all columns */ 
while ($finfo = $result->fetch_field()) { 
    echo " 
     <th>" . $finfo->name . "</th>"; 
} 
echo " 
     </tr> 
    </thead> 
    <tbody>"; 
while ($row = $result->fetch_assoc()) { 
    echo "<tr class='info'> 
    <td>" . $row['id'] . "</td> 
       <td>" . $row['name'] . "</td> 
       <td>" . $row['mail'] . "</td> 
       <td>" . $row['number'] . "</td> 
       <td>" . $row['price'] . "</td> 
       <td>" . $row['paymenttype'] . "</td> 

       <td>" . $row['faktura'] . "</td> 
       <td>" . $row['date'] . "</td> 
    </tr>"; 
} 
echo " 
    </tbody> 

</table>"; 

?> 
     </div> 
     <div class="modal-footer"> 
      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> 
     </div> 
     </div> 

    </div> 
    </div> 

---------用這段代碼收集作業表----

<?php 

include("../includes/connection.php"); 

if ($link->connect_errno > 0) { 
    die('Unable to connect to database [' . $link->connect_error . ']'); 
} 

if (isset($_POST['update'])) { 
    $results = $link->query("UPDATE job SET status='$_POST[status]', priority='$_POST[priority]' WHERE id='$_POST[hidden]'"); 
    $results = $link->query("UPDATE customer SET status='$_POST[status]' WHERE id='$_POST[hidden]'"); 
} 

$sql = "SELECT * from job"; 
if (!$result = $link->query($sql)) { 
    die('There was an error running the query [' . $link->error . ']'); 
} 
echo " 
<table class='table'> 
    <thead> 
     <tr>"; 
/* Get field information for all columns */ 
while ($finfo = $result->fetch_field()) { 
    echo " 
     <th>" . $finfo->name . "</th>"; 
} 
echo " 
     </tr> 
    </thead> 
    <tbody>"; 


while ($row = $result->fetch_assoc()) { 

     $job_id = $row['id']; 
    echo "<form action='' method=post>"; 

    echo "<tr class='info'> 

       <input type=hidden name=hidden value=" . $row['id'] . "> 
       <td>" . $row['id'] . "</td> 
       <td>" . $row['device'] . "</td> 
        <td>" . $row['model'] . "</td> 
       <td>" . $row['problem'] . "</td> 
       <td> 
      <select class='form-control col-sm-10' id='status' name='status'> 
       <option value='new' ". ($row['status'] == 'new'? 'selected ': '') .">New</option> 
     <option value='progress' ". ($row['status'] == 'progress'? 'selected ': '') .">Progress</option> 
      <option value='wait' ". ($row['status'] == 'wait'? 'selected ': '') .">Wait</option> 
      <option value='done' ". ($row['status'] == 'done'? 'selected ': '') .">Done</option> 
      <option value='close' ". ($row['status'] == 'close'? 'selected ': '') .">Close</option> 
    </select> 
      </td>   

       <td><select class='form-control col-sm-10' id='priority' name='priority'>     
          <option style='background-color:green;'value='low' ". ($row['priority'] == 'Low'? 'selected ': '') .">Low</option> 
           <option style='background-color:yellow; value='Medium' ". ($row['priority'] == 'Medium'? 'selected ': '') .">Medium</option> 
        <option style='background-color:red; value='High' ". ($row['priority'] == 'High'? 'selected ': '') .">High</option> 


         </select></td> 

       <td> <button type='submit' class='btn btn-primary btn-sm' name='update'>Update</button></td> 

       <td> <a class='btn btn-primary btn-sm' data-toggle='modal' data-target='#myModal' name='job_id' value='[$job_id]' > Info</a></td> 


      </tr>"; 
    echo "</form>"; 
} 
echo " 
    </tbody> 

</table>"; 

?> 
+0

我們需要看到的表。你是否也按正確的順序插入?如果你嘗試在pk之前插入fk表,那麼你將遇到問題。你在使用innoDB嗎? – bassxzero

+0

ubuntu ??或窗戶? –

+0

@bassxzero我更新了我的問題 – gigi

回答

1

這段腳本似乎有很多錯誤。

由於您的Customer表格行是先插入的,而您沒有指定job_id我認爲它試圖使用0來使外鍵約束失敗。

我不能從你的表中告訴哪個實體需要先被添加,或者如果一個依賴於另一個。所以我會給你一個適用於兩者的解決方案。我會說,雖然這個解決方案有效,它可以讓你忽略FK約束,如果你打算忽略它,那麼你最好不要把它放在第一位。

首先更改Customer表中的job_id字段以允許NULL值。

第二個變化這一行

$sql = "INSERT INTO customer (name, mail, number, device, price, paymenttype,status,date) VALUES ('$name', '$email', '$number', '$device', '$price', '$payment','$status',NOW())"; 

這一行

$sql = "INSERT INTO customer (name, mail, number, device, price, paymenttype,status,date,job_id) VALUES ('$name', '$email', '$number', '$device', '$price', '$payment','$status',NOW(),NULL)"; 

看來好像都你的頭重定向可以在執行過程中達成。

  1. 在標題重定向或腳本將繼續處理後,您應該始終調用exit()Why I have to call 'exit' after redirection through header('Location..') in PHP?

  2. 如果您回顯錯誤消息並且您沒有緩衝您的輸出,那麼您的重定向將失敗,因爲您已經發送了輸出,它將發送標題。 How to fix "Headers already sent" error in PHP

Edit after problem clarification

<?php 

    //connection includes and escaping POST data goes here. 

    // insert job first so we can use the pk as an fk for the customer table 
    $sql = "INSERT INTO job (device, model, problem, status) VALUES ('$device', '$model', '$problem', '$status')"; 

    $result = mysqli_query($link, $sql); 

    // if query fails stop script and echo error 
    if($result === false) 
    { 
     echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); 
     exit; 
    } 

    // this only works for auto-incremented fields 
    $jobPrimaryKey = mysqli_insert_id($link); 

    $sql = "INSERT INTO customer (name, mail, number, device, price, paymenttype,status,date,job_id) VALUES ('$name', '$email', '$number', '$device', '$price', '$payment','$status',NOW(),'{$jobPrimaryKey}')"; 

    $result = mysqli_query($link, $sql); 

    // if query fails stop script and echo error 
    if($result === false) 
    { 
     echo "ERROR: Could not able to execute $sql. " . mysqli_error($link); 
     exit; 
    } 

    // if we get here then both queries were successful 

    header("location:some_page.php?message=A job and customer has been added to the database"); 
    // exit now to stop the script from continuing 
    exit; 

    echo "You'll never see this"; 
?> 
+0

此解決方案正在運行。我可以在這兩個表中插入,當我按下「INFO」按鈕時,我可以實現我想要的查詢:'$ sql =「從客戶WHERE id = $ job_id中選擇*」;'只有一點我不明白。現在「CUSTOMER表」中的「JOB_ID」的值都爲NULL。他們不應該反映JOB表的相同ID? – gigi

+0

這就是我如何處理按鈕:'​​ Info' – gigi

+0

@吉吉看到我的編輯。 – bassxzero

相關問題