【问题标题】:Foreign key issue when adding data to table database将数据添加到表数据库时的外键问题
【发布时间】:2017-01-13 17:48:09
【问题描述】:

我有一个 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 的每一行都有一个“信息”按钮,而不是 onclick 应该显示从 CUSTOMER_table 收集的详细信息。

示例:
第一行的“信息”按钮,想要获取客户表的第一行..
第二行按钮“信息”,想要获取客户表的第二行...

---------点击后收集客户表的模态弹出代码-----

<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>";

?>

【问题讨论】:

  • 我们需要查看表格。您是否也以正确的顺序插入?如果您尝试在 pk 之前插入 fk 表,那么您将遇到问题。你在使用 innoDB 吗?
  • ubuntu??还是窗户??
  • @bassxzero 我更新了我的问题
  • @Abdulla 我正在使用 Windows(如果重要的话)
  • @gigi 你在使用 ajax 来填充客户信息模式吗?

标签: php database mysqli html-table


【解决方案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";
?>

【讨论】:

  • 此解决方案有效。我可以在两个表中插入,当我按下“INFO”按钮时,我可以通过这个查询来实现我想要的:$sql = "SELECT * from customer WHERE id= $job_id "; 只有一点我不明白。现在,“CUSTOMER 表”中“JOB_ID”的所有值都为 NULL。它们不应该反映 JOB 表的相同 ID 吗?
  • 这就是我处理按钮的方式:&lt;td&gt; &lt;a class='btn btn-primary btn-sm' data-toggle='modal' data-target='#myModal' name='[$job_id]' value='[$job_id]' &gt; Info&lt;/a&gt;&lt;/td&gt;
  • 您的解决方案是正确且更清晰的。我可以看到现在 "customer_table" 的 "Job_id" 列与 "job_table" 的 "ID" 相关联,但我无法弄清楚如何将 customer_table 的每个按钮与 job_table 的每一行连接
  • 我为该行的每个按钮分配了一个数组中的值。使用&lt;td&gt; &lt;a class='btn btn-primary btn-sm' data-toggle='modal' data-target='#myModal' name='job_id' value='[$job_id]' &gt; Info&lt;/a&gt;&lt;/td&gt;,但是如何将按钮的值与customer_table的行联系起来?
  • @gigi 你将不得不展示更多代码或解释总体目标,因为我不明白。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-12-07
  • 2011-10-07
  • 2021-07-05
  • 1970-01-01
  • 2022-10-25
  • 2014-03-06
  • 1970-01-01
相关资源
最近更新 更多