我有一个表单,它接受两个值作为输入,并使用post方法将它们解析到我有这段代码的下一个文件。这应该保存MySQL数据库中的两个值。但奇怪的是它没有...而且在输出错误中我得到的是: 0:0:
$service_name = $_POST['service_name'];
$service_price = $_POST['service_price'];
$link = mysql_connect("localhost", "db_user", "pa$$");
mysql_select_db("database", $link);
echo mysql_errno($link) . ": " . mysql_error($link). "\n";
mysql_select_db("database", $link);
mysql_query("INSERT INTO service_tbl(id_service, service_name, service_price) VALUES(NULL,'$service_name','$service_price')", $link);
echo mysql_errno($link) . ": " . mysql_error($link) . "\n";
在我的数据库表service_tbl
中,id_service
是auto_increment,其他两列是VARCHAR。我在这里做错了什么?
答案 0 :(得分:1)
mysql_query("INSERT INTO service_tbl( service_name, service_price) VALUES('{$service_name}','{$service_price}')", $link);
使用此项,因为Id_service
是自动递增的,您无法插入它。
答案 1 :(得分:1)
您正试图在自动增量列中插入NULL
,这是不可能的,只需更改为
mysql_query("INSERT INTO service_tbl( service_name, service_price) VALUES('$service_name','$service_price')", $link);
然后我想要记住,mysql_
函数已被弃用,因此我建议您切换到mysqli
或PDO
,确实存在sql injection
的风险,看看How can I prevent SQL injection in PHP?。您应该使用准备好的法规来避免任何风险
答案 2 :(得分:1)
一些修正案:
mysql_*
函数。修订后的代码:
$service_name = $_POST['service_name'];
$service_price = $_POST['service_price'];
$mysqli = new MySQLi('localhost', 'db_user', 'pa$$', 'database');
if ($mysqli->connect_errno) {
throw new ErrorException("Failed to connect to MySQL: " . $mysqli->connect_error);
}
$query = sprintf("INSERT INTO service_tbl (service_name, service_price) VALUES ('%s', $f)",
$mysqli->real_escape_string($service_name),
(float)$service_name
);
// At this point, you can echo the query to test it in eg. phpMyAdmin
$result = $mysqli->query($query);
if ($result === false) {
throw new ErrorException("Query failed: " . $mysqli->error);
}
printf("Select returned %d rows.\n", $result->num_rows);
while ($obj = $result->fetch_object()) {
print_r($obj);
}
// Free result set
$result->close();