为什么mysqli插入不起作用?

时间:2013-02-09 15:55:47

标签: php mysql sql sql-insert

我正在尝试将数据插入到我的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')");
}

连接正常,不会返回任何错误。

4 个答案:

答案 0 :(得分:4)

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

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

并且请对值进行参数化。

答案 1 :(得分:4)

您的表名具有-,如this documentation中所述,它不是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;提及here

答案 2 :(得分:1)

可能你的表名中缺少``

我会建议:

    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手动插入并检查它为什么不起作用

答案 3 :(得分:0)

试试这个:

import {DataTableModule,SharedModule} from 'primeng/primeng';

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

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