MySql连接。该怎么办?

时间:2018-08-02 09:59:25

标签: php mysql database mysqli insert

我真的是php的新手,我正在尝试使用从表单向MySQL数据库的简单插入。

我知道此mysql连接/插入很危险,已不再使用。所以有人可以帮我这个简单的事情吗?我试图用Google搜索,但到目前为止没有任何效果:/

<? 
$text=$_POST['name']; 
$text=$_POST['surename'];

mysql_connect("localhost", "db_name", "pass") or die(mysql_error()); 
mysql_select_db("db_name") or die(mysql_error()); 
$result = mysql_query("INSERT INTO `table` (name, surename)
VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')");
if (!$result) {
    die('Invalid query: ' . mysql_error());     
}
?>

1 个答案:

答案 0 :(得分:0)

也许会改变

$text=$_POST['name']; 
$text=$_POST['surename'];

$name = $_POST['name']; 
$surename = $_POST['surename'];

PS:而且您的列名也不匹配您的值。插入参数后进行查询

"INSERT INTO `table` (name, surename) VALUES (NOW(), '".mysql_real_escape_string($name)."', '".mysql_real_escape_string($surename)."')"

可能看起来像这样

INSERT INTO `table` (name, surename) VALUES (NOW(), 'Jhon', 'Wick')

您会看到name, surename(可能应该是surname)和(NOW(), 'Jhon', 'Wick')。因此,请添加一列(如果您的数据库中有该列):

INSERT INTO `table` (created_at, name, surename) VALUES (NOW(), 'Jhon', 'Wick')

或从您的值中删除NOW()

INSERT INTO `table` (name, surename) VALUES ('Jhon', 'Wick')