PHP与MySQL表的连接问题

时间:2018-12-18 05:57:42

标签: php mysql forms mysqli

我的问题是这样

后端的

(1)我在MySQL中有数据库。它包含7个表。 (2)在前端,我有一个HTML表单。 (3)从用户输入的数据必须填充这7个表。 (4)我使用PHP并使用mysqli将表单链接到数据库。

由于某种原因,该表单仅填充了第一个表,而其他6个没有填充数据。知道如何将表单一次连接到所有表吗?我不需要一个sql表,因为HTML表单有300多个输入字段。 谢谢。

已编辑

这是代码

<?php
$host="localhost";
$user="root";
$pass="";
$db="ao db";

$conn = new mysqli ($host, $user, $pass, $db);

if ($conn->connect_error) { 
die("Connection failed: " . $conn->connect_error);
}

$firstname = $_POST["first_name"];
$lastname = $_POST["name"]; 
$female = $_POST["female"];

$stmt = $conn->prepare("INSERT INTO table_demo (Vorname, Nachname, female) VALUES (?, ?, ?)");
$stmt->bind_param("ssi", $firstname, $lastname, $female);

$stmt->execute();
$stmt->close();
echo "New records created in Demo";
$conn->close();

$link = new mysqli ($host, $user, $pass, $db);

if ($link->connect_error) { 
die("Connection failed: " . $link->connect_error);
}

$height = $_POST["height"];
$weight = $_POST["weight"];

$stmt=$link->prepare("INSERT INTO table_pre (height, weight) VALUE (?, ?)");
$stmt->bind_param("ii", $height, $weight);

$stmt->execute();

$stmt->close();
echo "New records created in Pre";
$link->close();

>

2 个答案:

答案 0 :(得分:1)

  1. 对于您来说,首先必须创建数据库连接对象。

`

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}`
  1. 用于插入表。有了帮助,您可以在所有七个表中插入详细信息。

    $sql = "INSERT INTO MyGuests (firstname, lastname, email)VALUES ('John', 'Doe', 'john@example.com')";

  2. 使用此从表中获取详细信息。借助此功能,您可以从所有七个表中进行选择。

    $sql = "SELECT id, firstname, lastname FROM MyGuests"; $result = $conn->query($sql);

答案 1 :(得分:0)

我知道了!那里有2个问题:

问题一:表创建不正确,并且外键连接错误。我通过phpmyadmin菜单使用外键创建表时遇到问题。也许最好使用SQL数据库和表创建语法:

CREATE DATABASE IF NOT EXISTS database_name;

USE database_name;

CREATE TABLE table_1
(
    table_1_id int not null auto_increment primary key,
    variable_1 varchar(255) not null,
    variable_2 int(11),
    ...
    variable_to_be_used_as_foreign_key text,
    variable_n text,
) ENGINE=InnoDB;

CREATE TABLE table_2
(
    table_2_id int not null auto_increment primary key,
    variable_1 varchar(255) not null,
    variable_2 int(11),
    ...
    variable_n text,
    variable_to_be_used_as_foreign_key text,

    FOREIGN KEY fk_table_2(variable_to_be_used_as_foreign_key)
         REFERENCES table_1(variable_to_be_used_as_foreign_key)
              ON UPDATE CASCADE
              ON DELETE RESTRICT
) ENGINE=InnoDB;

请注意:必须在两个表中都添加外键变量(我知道这很明显,但仍然可以)。

问题#2 :php代码失败。我在准备好的语句中错过了第二个表的外键列中的输入,即:

$stmt=$link->prepare("INSERT INTO table_pre (height, weight) VALUE (?, ?)");
$stmt->bind_param("ii", $height, $weight);

代替:

$stmt=$link->prepare("INSERT INTO table_pre (height, weight, female) VALUE (?, ?, ?)");
$stmt->bind_param("iii", $height, $weight, $female);