php脚本写入SQL数据库

时间:2017-12-17 04:30:21

标签: php mysql

我是php的新手,并编写了以下PHP脚本来写一个FORM。但是,数据库未更新。我知道数据库连接没问题。任何帮助将不胜感激。

$name = $_POST["name"];
$lastName = $_POST["last_name"];
$email = $_POST["email"];
$location = $_POST["location"];
$timestamp = date("Y-m-d H:i:s");

$sql = "INSERT INTO club.users (name, last_name, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";

2 个答案:

答案 0 :(得分:0)

试试这个

你必须使用SQL注入来实现类似这样的安全性

$conn->real_escape_string($_POST['name']);

检查您的表名。我之前没有使用表名club.users,因为它会显示表格确实存在的错误。只需使用表格名称clubusers

即可

学习PHP的时间

https://www.w3schools.com/php/php_mysql_insert.asp

<强>的index.php

我希望你的HTML代码看起来像这样

<form action="register.php" method="POST" name="register">
    <input type="text" name="name" placeholder="Name">
    <input type="text" name="lastname" placeholder="Lastname">
    <input type="email" name="email" placeholder="Email">
    <input type="text" name="location" placeholder="Location">
    <input type="submit" name="submit" value="Register">
</form>

<强> Connection.php

如果您使用的是本地服务器,则使用的root用户名和密码应为空白。

$servername = "localhost";
$username = "root";//if you are working on local server 
$password = ""; //set blank if you are working on local server
$dbname = "myDB";//your database name

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

<强> register.php

<?php 
include('connection.php');// added the connection here
if (isset($_POST['submit'])) {
    $name = $conn->real_escape_string($_POST["name"]);
    $lastName = $conn->real_escape_string($_POST["lastname"]);
    $email =$conn->real_escape_string($_POST["email"]);
    $location = $conn->real_escape_string($_POST["location"]);
    $timestamp = date("Y-m-d H:i:s");
       $sql = "INSERT INTO club (name, lastname, email, location, created_at) VALUES ('$name', '$lastName', '$email', '$location', '$timestamp')";

        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $conn->error;
        }

        $conn->close();
        }

 ?>

答案 1 :(得分:-1)

首先在同一个php页面中定义数据库服务器连接,或者可以包含连接。用于此目的的Php文件。

其次你希望使用MySQL db简单使用musql_query($ sql,$ con)然后在插入结果后写下面的行。 对不起,如果您需要,我可以通过我的手机发布,我可以从我的电脑上发布您的整个代码示例。

相关问题