使用表单将数据插入到php表中

时间:2015-02-14 09:09:11

标签: php mysql

$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)导致这样: http://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 ] )

混合了一段时间或者什么。

1 个答案:

答案 0 :(得分:0)

<?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>
相关问题