为什么mysqli insert不起作用


why is mysqli insert not working?

我正试图将数据插入MySQL表,但没有成功。我的代码看起来像:

$mysqli = mysqli_connect("localhost","login info");
if ($mysqli->connect_errno) {
    echo "Failed to connect to MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
if (isset($_POST['submit'])) {
    $number = $_POST['number'];
    $road = $_POST['road'];
    $postcode=$_POST['postcode'];
    $price=$_POST['price'];
    $type=$_POST['type'];
    $bedrooms=$_POST['bedrooms'];
    $agent=$_POST['agent'];
    $featured=$_POST['featured'];
    $keywords=$_POST['keywords'];
    $mysqli->query("
        INSERT INTO listings-rent
            (number, road, postcode, price, type, bedrooms, agent, featured, keywords)
        VALUES
            ('$number','$road','$postcode','$price','$type','$bedrooms','$agent','$featured','$keywords')");
}

连接正常,没有返回错误。

您的表名应该用反勾号括起来,因为它包含非字母数字字符。

INSERT INTO `listings-rent` (...) VALUES (...)

同时请将这些值参数化。

您的表名有一个-,如本文档所述,它不是MySQL中未引用表名所支持的字符。试试这个:

$mysqli->query("INSERT INTO `listings-rent` (number, road, postcode, price, type, bedrooms, agent, featured, keywords) VALUES ('$number','$road','$postcode','$price','$type','$bedrooms','$agent','$featured','$keywords')");

要查看错误,可以使用此处提到的echo $mysqli->error;

您的表名中可能缺少"

我建议:

    if (TRUE == $mysqli->query("INSERT INTO `listings-rent` (number, road, postcode, price, type, bedrooms, agent, featured, keywords) VALUES ('$number','$road','$postcode','$price','$type','$bedrooms','$agent','$featured','$keywords')"))
        echo "its working!"
    else
         echo $mysqli->error;

这样你就会看到问题

另一个选项,我建议它打印失败的查询,并使用phpmyadmin手动插入它,并检查它为什么不工作

请尝试以下操作:

$mysqli = mysqli_connect("localhost", "your_db_username" , "your_db_password" , "database_name")

对于本地服务器,通常用户名为root,密码为null。所以在这种情况下,复制粘贴这个:

$mysqli = mysqli_connect("localhost", "root" , "" , "login info")