MySQL出了什么问题?

时间:2012-12-14 22:25:58

标签: php mysql

INSERT不起作用,不确定原因。

db.php中:

function check($value)
{
    if ($value)
        return htmlspecialchars(stripslashes(trim($value)));
    else
        return null;
}

$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_name = 'cart';

$connect = mysql_connect($db_host, $db_user, $db_pass) or die ('no connect');
mysql_select_db($db_name) or die ('no db');

function add($name, $price, $description, $image)
{
    global $connect;

    $sql = "INSERT INTO items (name, price, description, image)
            values ('{$name}', '{$price}', '{$description}', '{$image}');";
    $query = mysql_query($sql, $connect);

    if (!$query)
        die(mysql_error());

    mysql_close($connect);
}

add.php:

header('Content-Type: text/html; charset=utf-8');
mb_internal_encoding('utf-8');
include_once('./db.php');

$name = check($_POST['name']);
$price = check($_POST['price']);
$description = check($_POST['description']);
$image = check($_POST['image']);

if ($name && $price && $description && $image)
{
    add($name, $price, $description, $image);
    echo 'sent';
}

当我收到sent消息时,items表中没有新行。我用phpmyadmin检查它。

使用此代码(通过安装脚本)创建数据库:

function reset_mysql()
{
    global $connect;

    $sql = "CREATE TABLE items (
        id INT AUTO_INCREMENT NOT NULL,
        name VARCHAR(50) NOT NULL,
        price VARCHAR(10) NOT NULL,
        description VARCHAR(200) NOT NULL,
        image VARCHAR(30) NOT NULL,
        primary key (id)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;";

    $query = mysql_query($sql, $connect);

    if (!$query)
        die(mysql_error());

    mysql_close($connect);
}

怎么了?

2 个答案:

答案 0 :(得分:0)

  

$ sql =“INSERT INTO items VALUES('','$ name','$ price','$ description','$ image')”;

已更新

答案 1 :(得分:0)

最后通过将mysql_connect替换为add函数来修复:

function add($name, $price, $description, $image)
{
    global $db_host, $db_user, $db_pass, $db_name;

    $connect = mysql_connect($db_host, $db_user, $db_pass) or die ('no connect');
    mysql_select_db($db_name) or die ('no db');

    $sql = "INSERT INTO items (name, price, description, image)
            values ('{$name}', '{$price}', '{$description}', '{$image}');";
    $query = mysql_query($sql, $connect);

    if (!$query)
        die(mysql_error());

    mysql_close($connect);
}

感谢所有评论,你真棒!