mysqli_query不运行查询?

时间:2014-12-10 17:22:27

标签: php mysql sql

我有这些.php文件:

db_functions中的

saveData不运行sqliquery。它没有将参数插入数据库 - 我已经在phpmyadmin上测试了相同的查询(带有随机值) - 它可以工作 - 但是这里没有......代码中是否有任何错误? db_config数据是正确的 - 只将它们更改为xxx:D

DB_CONFIG:

    <?php


define("DB_HOST", "xxx");
define("DB_USER", "xxx");
define("DB_PASSWORD", "xxx");
define("DB_DATABASE", "xxx");

?>

db_connect:

    <?php

class DB_CONNECT {

    private $conn;

    // constructor
    function __construct() {


    }


    /**
     * Function to connect with database
     */
    function connect() {
        // import database db variables
        require_once __DIR__ . '/db_config.php';

        // Connecting to mysql database
       $this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD);

        if (mysqli_connect_errno()) {
            echo "Failed to connect to MySQL: " . mysqli_connect_error();
        }
        // Selecing database

        // returing connection cursor
        return $this->conn;
    }



}

?>

db_functions

class DB_Functions {

    private $conn;

    //put your code here
    // constructor
    function __construct() {
        include_once './db_connect.php';
        // connecting to database
        $db = new DB_Connect();
          $this->conn = $db->connect();
    }






    public function saveData($name, $id) {


    if (mysqli_connect_errno()) {
  printf("Connect failed: %s\n", mysqli_connect_error());
  exit();
}
        // insert user into database
            $query = "INSERT INTO data(name, id) VALUES('$name','$id')";
            echo $query;
        $result = mysqli_query($this->conn,$query);

...}

1 个答案:

答案 0 :(得分:2)

你有这一行

$this->conn = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD);

其中未定义DB_SERVER并且您未传递数据库名称

所以它应该是

$this->conn = new mysqli(DB_HOST, DB_USER, DB_PASSWORD, DB_DATABASE);

我的代码中没有发现任何其他明显的错误。 但是我强烈建议使用预准备语句,而不是将数据直接注入查询。

请参阅mysqli::prepare