所以我一直在尝试一些原始PHP
编码。我的意思是在不使用框架或其他帮助工具的情况下编写PHP
。
在创建一些小型创业项目后,我偶然发现了一个问题。请记住,我仍然处于学习困境中,所以如果有更好的方法来编写我的代码,请告诉我。
我遇到的问题与连接和插入数据库有关。连接工作,经过一些研究,我认为我找到了通过函数传递变量的方法。 (遗憾的是我没有)
我的代码如下:
数据库类。
<?php
/**
* Created by: PhpStorm.
* Project: Learning_projects
* File name: database.php.
* User: Niels.
* Date: 23-6-2017.
* Time: 11:25.
* File Description: ...
*/
namespace PHP_learning\Database\classes;
class database extends layout
{
/**
* @var $servername = Servername
* @var $username = Username
* @var $password = Password
* @var $db = Database
* @var $conn = Connection DB
*/
protected $servername;
protected $username;
protected $password;
protected $db;
protected $conn;
protected $content;
public function connect() {
$servername = "localhost";
$username = "..";
$password = "..";
$db = "..";
$conn = new \mysqli($servername, $username, $password, $db);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
return $this->conn;
}
public function insert() {
$conn = $this->connect();
$content = "123";
$sql = mysqli_query($conn,"INSERT INTO content (`content`) VALUES ('$content')");
var_dump($sql);
if ($sql === TRUE)
{
echo "<script>alert('Topic 1 ingevoerd.')</script>";
}
else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
}
的index.php
/**
* Require the classes, includes, etc all is set right
**/
/**
* Starting connect and insert
**/
$connection->connect();
$connection->insert();
正如您所看到的,我正在尝试为connect()
函数要求函数insert
。是的我可以在插入函数中编写连接,是的确可行,但这不是我想要的。
所以,如果有人能告诉我我做错了什么,我会非常高兴(:
PS:始终欢迎代码样式提示和排序(:
提前致谢!
答案 0 :(得分:1)
使用$this->conn
而不是再次连接:
public function connect() {
$servername = "localhost";
$username = "..";
$password = "..";
$db = "..";
$this->conn = new \mysqli($servername, $username, $password, $db);
if ($this->conn->connect_error) {
die("Connection failed: " . $this->conn->connect_error);
}
echo "Connected successfully";
return $this->conn;
}
public function insert() {
$content = "123";
$sql = mysqli_query($this->conn,"INSERT INTO content (`content`) VALUES ('$content')");
var_dump($sql);
if ($sql === TRUE)
{
echo "<script>alert('Topic 1 ingevoerd.')</script>";
}
else {
echo "Error: " . $sql . "<br>" . $this->conn->error;
}
}