自动在前键中设置值

时间:2018-06-22 00:05:04

标签: php mysql sql xampp

我创建两个表

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>

1 个答案:

答案 0 :(得分:0)

我假设您要使用名称为$_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->real_escape_string()也不安全,无法进行SQL注入。