SQL Insert Into无法正常工作

时间:2017-03-02 05:48:44

标签: php mysql

的common.php

function connection() {
    $servername = "db********.db.1and1.com";
    $username = "dbo********";
    $password = "********";
    $dbname = "db********";
    $connection = new mysqli($servername, $username, $password, $dbname);
    mysqli_set_charset($connection, "utf8");
    if ($connection->connect_error) {
        die($connection->connect_error);
    } 
}

category.php

include('../model/common.php');
connection();

$name = $_POST["catname"];

$sql = "INSERT INTO `category` (name) VALUES ('".$name."')" ;

if (mysqli_query($connection, $sql)) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "<br>" . mysqli_error($connection);
}


mysqli_close($connection);

我通过jQuery ajax提交了表单并返回此错误:

  

错误:INSERT INTO`category`(name)VALUES('some test value')

但如果我将connection()函数的整个代码放在我的查询之上,而不包括common.php,那么它可以正常工作!我猜可能存在一些全球问题。我也试过全局$connection或使用单例类但没有成功。

2 个答案:

答案 0 :(得分:2)

  1. 返回$connection

    if ($connection->connect_error) {
      die($connection->connect_error);
    }
    return $connection
    
  2. 分配给新的$连接变量

    $connection = connection();
    

答案 1 :(得分:1)

connection()函数创建上下文或范围。变量仅在函数期间存在,因此$connection下面不可用。有关变量范围的更多信息,请参阅this thread。一种解决方案是在函数顶部添加global $connection,以允许在$connection函数之外设置connection()。您可以完全省略该功能,只需包含该文件即可设置该信息。

function connection() {
    global $connection; //Add this line
    $servername = "db********.db.1and1.com";
    $username = "dbo********";
    $password = "********";
    $dbname = "db********";
    $connection = new mysqli($servername, $username, $password, $dbname);
    mysqli_set_charset($connection, "utf8");
    if ($connection->connect_error) {
        die($connection->connect_error);
    } 
}