使用mysqli将输入放在数据库中

时间:2012-10-04 08:57:59

标签: php input mysqli

我正在尝试使用mysqli将表单中的数据插入数据库。但是我没有让它工作:/

这是我填写表单后您所访问的页面中的代码。表单不是问题,因为变量$ headin $ author和$ thecontent都包含数据。并且在实际代码数据库中,用户名密码和名称具有实际值:)

<html>
<head>

<title>Send!</title>
</head>

<body>

<?php

 ini_set('display_errors', 1); error_reporting(E_ALL); 
$DB_HOST = 'localhost';
$DB_USER = '**';
$DB_PASS = '***';
$DB_NAME = '***';
@ $db = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if (mysqli_connect_errno()) {
echo 'Error.';
exit();
}

$author = $_POST['author']; 
$heading = $_POST['heading'];
$thecontent = $_POST['thecontent'];

$query = 'INSERT INTO articles ('heading', 'author', 'content')
 VALUES ('$heading','$author','$thecontent')';   

$result = $db->query($query);
    if ($result) {
    echo $db->affected_rows."This was added.";
    } 
    else {
    echo "somethings gone very wrong.";
    }

$db->close();


?> 

</body>
</html>

1 个答案:

答案 0 :(得分:1)

您无法在行名称上添加单引号',并且必须为INSERT添加双引号:

$query = "INSERT INTO articles (`heading`, `author`, `content`)
 VALUES ('$heading','$author','$thecontent')"; 

也逃避你的字符串:

$author = $db->real_escape_string($_POST['author']); 
$heading = $db->real_escape_string($_POST['heading']);
$thecontent = $db->real_escape_string($_POST['thecontent']);