【问题标题】:set value in foregin key automatically自动在外键中设置值
【发布时间】:2018-12-01 09:38:29
【问题描述】:

我创建了两个表

Table brand

Brand_id(primary key),Brand_name
1                      gucci

Table Product

Product_id, Brand_id(foeign_key),   Product_name
1                                   holand

两个表都使用键链接,我希望在更新品牌表中的品牌名称后,品牌表中的主键 id 自动插入产品brand_id。每当我输入产品名称时,是否有可能,外键brand_id与主键brand_id一样,

我也尝试添加与外键 id 匹配的主键 id 的代码,但它不起作用。

<?php
session_start();
$_SESSION['message']=''; 
$mysqli=new MySQLi('127.0.0.1','root','','demo');
if(isset($_POST["login"])) {
    $product_name = $mysqli->real_escape_string($_POST['product_name']);
    $brand_id = 'brand.brand_id';

    $sql ="INSERT INTO product(product_name,brand_id)"
        ."VALUES ('$product_name','brand_id')";     

    if($mysqli->query($sql)=== true) {

        $_SESSION['message'] =  "Registration successful!
                                                  Added  to the database!";
        header("location:multiple_table.php");
    }
}
else {
    $_SESSION['message'] = "User could not be added to the database!";      
}

?> 


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>form in Design</title>
<link rel="stylesheet" type="text/css" href="mystyle.css" />
<link rel="stylesheet" type="text/css" href="form.css" />
</head>
<body>
<h1><?=$_SESSION['brand_name']?></h1>
<form method="POST" action=""><?=$_SESSION['message']?>

<div class="form_input">
<input type="text" name="product_name" placeholder="Enter your Product name"/>
</div>
<input type="submit" name="login" value="login" class="btn-login" />
</form>

</body>
</html>

【问题讨论】:

  • 您的代码对brand 表没有任何作用。它应该如何知道使用哪个brand_id 作为外键?

标签: php mysql sql xampp


【解决方案1】:

我假设您想使用名称在 $_SESSION['brand_name'] 中的品牌。您可以使用它来获取brand_id

<?php
session_start();
$_SESSION['message']=''; 
$mysqli=new MySQLi('127.0.0.1','root','','demo');
if(isset($_POST["login"])) {
    $sql ="INSERT INTO product(product_name,brand_id)
           SELECT ?, brand_id
           FROM brand
           WHERE brand_name = ?";
    $stmt = $mysqli->prepare($sql);
    $stmt->bind_param("ss", $_POST['product_name'], $_SESSION['brand_name']);
    if($stmt->execute()) {
        $_SESSION['message'] =  "Registration successful!
                                                  Added  to the database!";
        header("location:multiple_table.php");
    }
}
else {
    $_SESSION['message'] = "User could not be added to the database!";      
}
?> 

如果您将品牌 ID 放入另一个会话变量(例如 $_SESSION['brand_id'])中会更容易。那么你就不需要进行查询来获取 ID。

您还应该学习使用准备好的语句而不是替换变量。即使使用$mysqli-&gt;real_escape_string() 也无法避免 SQL 注入。

【讨论】:

    猜你喜欢
    • 2012-09-11
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    • 2018-08-30
    • 1970-01-01
    • 2016-08-13
    • 2015-08-22
    • 2010-10-02
    相关资源
    最近更新 更多