在OOP中插入数据库不起作用

时间:2015-07-31 11:13:36

标签: php database oop object insert

我正在尝试进行面向对象的登录并插入到数据库中,但是这不起作用。它不会连接到数据库,错误:没有选择数据库。你能救我吗?

这是代码:

表单在index.php

   <form action="insert.php" method="post">
   Firstname: <input type="text" name="fname" /><br><br>
   Lastname: <input type="text" name="lname" /><br><br>
   <input type="submit" />

insert_class.php中的类:

<?php 
class Insert_class {

public $servername;
public $username;
public $password;
public $dbname;

public function __construct(){

 // Create connection
  $conn = mysqli_connect($servername, $username, $password, $dbname);
 // Check connection
 if (!$conn) {
   die("Connection failed: " . mysqli_connect_error());
 }

 // insert into database
 $sql = "INSERT INTO nametable (firstname, lastname)
 VALUES ('$_POST[fname]','$_POST[lname]')";

 if (mysqli_query($conn, $sql)) {
   echo "New record created successfully";
 } else {
   echo "Error: " . $sql . "<br>" . mysqli_error($conn);
 }

  mysqli_close($conn);

  }
}

用于登录的对象并在insert.php中的数据库中插入:     

require 'insert_class.php';

$insert = new Insert_class();

$insert->servername ='localhost';
$insert->username ='root';
$insert->password ='';
$insert->dbname ='newdatabase';

2 个答案:

答案 0 :(得分:3)

试试这个

<?php 
class Insert_class {

    private $servername;
    private $username;
    private $password;
    private $dbname;
    private $con

    public function __construct($servername,$username,$password,$dbname)
    {

        $this->servername = $servername;
        $this->username   = $username;
        $this->password   = $password;
        $this->dbname     = $dbname;
        // Create connection
        $this->conn = mysqli_connect($this->servername, $this->username,
                                     $this->password, $this->dbname);

        if ($this->con->connect_error) {
            die('Connect Error (' . $this->con->connect_errno . ') '. $this->con->connect_error);
        }

        // etc

    }

然后你可以做

require 'insert_class.php';
$insert = new Insert_class('localhost','root','','newdatabase');

注意我还将$ con作为属性捕获。你的代码会很多,因为它只能在__construct中看到,但是你可能不想在这个类中编写其他方法。

另请注意,我更改了连接成功的测试。这是检查连接是否成功的正确方法。一个简单的if( ! $con )还不够好。

答案 1 :(得分:0)

您可以使用DEFINE ..

,而不是明确定义连接详细信息
Amount

insert_class.php ...

  define("DB_HOST", "localhost");
  define("DB_USER", "root");
  define("DB_PASSWORD", "");
  define("DB_NAME", "newdatabase");