我在插入时遇到错误,所以我很困惑。请帮助我或建议我最好的oop教程
testdb.php page
define('DB_SERVER', 'localhost');
define ('DB_USERNAME', 'ashish');
define ('DB_PASSWORD', 'ashish33');
define ('DB_DATABASE', 'users');
class DB_Class
{
function __construct() {
$connection = mysqli_connect("localhost", "root", "","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
}}
testclass.php page
class user {
public $fname;
public $lname;
public $fullname;
public function __construct()
{
$this->fname = $fname;
$this->lname = $lname;
$this->fullname = $fullname;
$db = new DB_Class();
$result = mysqli_query($db, "INSERT INTO users(fname, lname, fullname) values ('$this->fname', '$this->lname','$this->fullname')") or die(mysqli_error());
return $result;
}
}
post.php中
$userTest = new user();
$userTest->fname = $_POST['fname'];
$userTest->lname = $_POST['lname'];
$userTest->fullname = $_POST['fullname'];
?>
答案 0 :(得分:1)
将其放在构造函数的参数中:
include 'testdb.php';
public function __construct($fname, $lname, $fullname)
{
$this->fname = $fname;
$this->lname = $lname;
$this->fullname = $fullname;
$db = new DB_Class();
$conn = $db->connect();
// $db = new mysqli('localhost', 'username', 'password', 'database');
$result = mysqli_query($conn, "INSERT INTO users(fname, lname, fullname) values ('$this->fname', '$this->lname','$this->fullname')") or die(mysqli_error());
return $result;
}
然后,初始化:
$userTest = new user($_POST['fname'], $_POST['lname'], $_POST['fullname']);
旁注:由于你使用的是mysqli,为什么不使用预备语句。
编辑:您忘记了return
上的DB_class
:
class DB_Class
{
public $conn;
public function __construct()
{
$connection = mysqli_connect("localhost", "root", "","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$this->conn = $connection; // return the mysqli instance
}
public function connect()
{
return $this->conn;
}
}
答案 1 :(得分:1)
you can try the below code in
class user extends DB_Class{
public $fname;
public $lname;
public $fullname;
public function __construct()
{
parent::__construct(); //add this line of code
}
public function insert($fname, $lname, $fullname)
{
$this->fname = $fname;
$this->lname = $lname;
$this->fullname = $fullname;
$db = new DB_Class();
$result = mysqli_query($db, "INSERT INTO users(fname, lname, fullname) values ('$this->fname', '$this->lname','$this->fullname')") or die(mysqli_error());
return $result;
}
}