我是PHP OOP的初学者,我正在尝试使用我的代码。所以我想做的第一件事就是为数据库编写一个带有连接和插入函数的基类。所以我想要的情况是:
-我想创建一个类来控制连接和插入函数。问题是,我的$connect变量在另一个函数中不起作用,那么我该怎么做才能实现呢?您将通过提供的代码了解更多信息。
<?php
class DB {
protected $dbhost = 'localhost';
protected $dbuser = 'root';
protected $dbpass = '';
protected $dbname = 'newdb';
public function connect()
{
$connect = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if($connect->error)
{
echo "Failed to connect";
}
else
{
echo "connected";
}
}
public function insert($name, $second)
{
$insert = "INSERT INTO posts (name, second) VALUES ('$name', '$second')";
if ($connect->query($insert) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_connect_error();
}
}
}
require_once 'classes/DB.php';
$db = new DB;
if(isset($_POST['submit']))
{
$name = $_POST['name'];
$second = $_POST['second'];
$db->insert($name, $second);
}
?>
<form method="POST">
Add smth<input type="text" name="name"><br>
Also omg<input type="text" name="second"><br>
<input type="submit" name="submit">
</form>
添加$connect
作为类的属性,这样您就可以使用$this->connect
:在类中的任何地方重用它
class DB
{
protected $dbhost = 'localhost';
protected $dbuser = 'root';
protected $dbpass = '';
protected $dbname = 'newdb';
protected $connect;
public function connect()
{
$this->connect = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if ($this->connect->error)
{
echo "Failed to connect";
}
else
{
echo "connected";
}
}
public function insert($name, $second)
{
$insert = "INSERT INTO posts (name, second) VALUES ('$name', '$second')";
if ($this->connect->query($insert) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_connect_error();
}
}
}
我已经重写了您的类一段时间,因此您可以在构造函数中插入数据库设置。所以它实际上是一个对象,您可以使用多个数据库。您在类中所做的错误是使用变量$connect,而没有将其声明为可在整个类中使用的变量。
类别
<?php
class DB {
protected $dbhost;
protected $dbuser;
protected $dbpass;
protected $dbname;
protected $connection;
public function __construct($dbhost, $dbuser, $dbpass, $dbname)
{
$this->dbhost = $dbhost;
$this->dbuser = $dbuser;
$this->dbpass = $dbpass;
$this->dbname = $dbname;
$connection = new mysqli($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
if($connection->error)
die('Could not connect with the database!');
$this->connection = $connection;
}
public function connect()
{
$this->__construct($this->dbhost, $this->dbuser, $this->dbpass, $this->dbname);
}
public function insert($name, $second)
{
$insert = "INSERT INTO posts (name, second) VALUES ('$name', '$second')";
if ($this->connection->query($insert) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . mysqli_connect_error();
}
}
public function getConnection()
{
return $this->connection;
}
}
用法
$db = new DB('localhost', 'root', '', 'newdb');
$db->insert('name', 'second');
我希望这能帮助你在你的日记中通过OOP,很抱歉我的英语不好。