我正面临一个问题。我有一个db-config
文件,一旦将该文件包含到php页面中,就无法获取输入数据。
create_user.php:
header("Access-Control-Allow-Origin: http://localhost/restapi/");
header("Content-Type: application/x-www-form-urlencoded; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// files needed to connect to database
include_once 'config/database.php';
include_once 'objects/user.php';
// get database connection
$database = new Database();
$db = $database->getConnection();
echo 'data:::'.$_POST['firstname'];exit;
// instantiate product object
$user = new User($db);
上面是我的php文件,其中包含database
文件。
config / databse.php:
<?php
// used to get mysql database connection
class Database{
// specify your own database credentials
private $host = "localhost";
private $db_name = "users";
private $username = "root";
private $password = "**********";
public $conn;
// get the database connection
public function getConnection(){
$this->conn = null;
try{
$this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
}catch(PDOException $exception){
echo "Connection error: " . $exception->getMessage();
}
return $this->conn;
}
}
?>
在包含database
文件并尝试打印post param
的空白时调用该方法之后。我正在使用PHP 7。
答案 0 :(得分:1)
您的代码绝对正确,我已经对其进行了测试,但似乎您错过了文件名中的符号。尝试使用 require_once 代替 include_once 。
并且不要在PHP文件末尾使用?>