数据未插入数据库

时间:2014-04-30 03:14:24

标签: php mysql database pdo

所以我的表单将数据发送到我的php文件,然后将其输入数据库。这是php后端部分

<?php
 $db = new mysqli('localhost','root','x','app');
 $username = $_POST['username'];

 $db->query("INSERT INTO people (first_name) VALUES ('{$username}'");

?>

但我的问题是,为什么不将username放入数据库?

1 个答案:

答案 0 :(得分:5)

您在以下行中缺少括号)

("INSERT INTO people (first_name) VALUES ('{$username}' ")
                                                       ^ // <= right there

将其更改为:

("INSERT INTO people (first_name) VALUES ('{$username}')")

然而,正如评论中指出的那样,在使用现有方法时,您可以SQL injection开放。


以下是prepared statement

的示例
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$mysqli = @mysqli_connect('localhost', 'xxx', 'xxx', 'my_db');

if (!$mysqli) {
    die('Connect Error: ' . mysqli_connect_error());
}

// $username = $_POST['username'];
$username = mysqli_real_escape_string($mysqli,$_POST['username']);

   $sql = ("INSERT INTO people (first_name) VALUES (?)");

    $stmt = $mysqli->prepare($sql) or die("Failed Execution");
    $stmt->bind_param('s', $username);

    $stmt->execute();
    echo $stmt->error;

echo "SUCCESS";

    exit();

另外,在上线之前使用错误报告非常重要。


您是否想要学习PDO,

以下是一些供您参考的教程:


以下是PDO示例:

<?php

    $mysql_hostname = 'xxx';
    $mysql_username = 'xxx';
    $mysql_password = 'xxx';
    $mysql_dbname = 'xxx';

    try{

    $db= new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname", $mysql_username, $mysql_password); 

$email = $_POST['email'];
$username = $_POST['username'];

$result_set = $db->prepare("INSERT INTO `yourTable` (`email`, `username`) 

 VALUES (:email, :username)");

$result_set->bindParam(1, $email);
$result_set->bindParam(2, $username);

$result_set->execute(array(':email' => $email, ':username' => $username));

    echo "Data successfully written.";

        return $db;
    }catch(PDOException $e){
        echo $e;
        return false;
    }

?>

PDO错误处理链接: