数据库错误。 SQL查询未被执行

时间:2013-05-18 19:26:35

标签: php mysql sql forms

我有一个表单,它接受两个值作为输入,并使用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。我在这里做错了什么?

3 个答案:

答案 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_函数已被弃用,因此我建议您切换到mysqliPDO,确实存在sql injection的风险,看看How can I prevent SQL injection in PHP?。您应该使用准备好的法规来避免任何风险

答案 2 :(得分:1)

一些修正案:

  1. 正如其他答案/评论中已经说过的那样,请不要使用已弃用的mysql_*函数。
  2. 无需为自动增量字段传递值。
  3. 将调试输出更改为实际错误检查。
  4. 清理用户输入。
  5. 修订后的代码:

    $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();