使用表单将数据插入 PHP 表中


insert data into php table using form

$servername = "localhost";
$username = "******";
$password = "*****";
$dbname = "*****";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
} else {

$sql = "SELECT * from actor";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    echo "<table border='0'><tr><th>ID</th><th>Nombre</th> <th>Apellidos</th></tr>";
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr>"."<td>".$row["cod_actor"]."</td>"."<td>".$row["nombre"]."</td>" ."<td>".$row["apellidos"]."</td>"."</tr>";
    }
    echo "</table>";
} else {
    echo "0 results";
}

这 ,当执行时(以及我端的一些 CSS(会导致:https://i.stack.imgur.com/okrVe.jpg我想做的是一个有 3 个字段的表单:

id: <input type="text" name="id"><br>
nombre: <input type="text" name="nombre">
apellidos: <input type="text" name="apellido"><br>

形成这个,我知道我必须这样做:

$id=$_POST['id'];
$nombre=$_POST['nombre'];
$apellido=$_POST['apellido'];

所以我使用用户在这些字段上写的内容进行查询:

$sql = "INSERT INTO actores (id, nombre, apellido)
VALUES ('$id', '$nombre', '$apellido')";
if (mysqli_query($conexion, $sql)) {
    echo "Insert successful";
} else {
    echo "there was an error " . mysqli_error($conexion);
}

现在,我的问题是当用户输入表单时这些变量为空我想我必须对 isset 做点什么,但我尝试做一个 IF ,但无济于事你会推荐什么?

我也试图在我认为我必须使用的数组中获取查询结果

mysqli_fetch_array ( mysqli_result $result [, int $resulttype = MYSQLI_BOTH ] )

混了一会儿什么的。

<?php
if (isset($_POST['id'],$_POST['nombre'], $_POST['apellido'])) {
$id=mysql_real_escape_string($_POST['id']);
$nombre=mysql_real_escape_string($_POST['nombre']);
$apellido=mysql_real_escape_string($_POST['apellido']);
}
?>
<form action="" method="POST">
            <p>
                <input type="text" name="id" />
                <input type="text" name="nombre" />
                <input type="text" name="apellido" />

  <input type="submit" value="Submit" />
            </p>
</form>