php将准备好的语句添加到数据库

时间:2016-09-10 11:15:19

标签: php mysqli prepared-statement

我想将准备好的语句实现到我的脚本中,但实际上无法让它工作。我已经有很多功能,所以我想尽可能少的改变。

我认为最好有一个准备好的声明功能?因此,当我获得用户输入时,我可以调用该函数而不是查询。

database.php类

class MySQLDB {
    var $connection; // The MySQL database connection

    /* Class constructor */
    function MySQLDB() {
        global $dbsystem;
        $this->connection = mysqli_connect ( DB_SERVER, DB_USER, DB_PASS,   DB_NAME ) or die ( 'Connection Failed (' . mysqli_connect_errno () . ') ' . mysqli_connect_error () );
    }


    /**
     * query - Performs the given query on the database and
     * returns the result, which may be false, true or a
     * resource identifier.
     */
    function query($query) {
        return mysqli_query ( $this->connection, $query );
    }
};

/* Create database connection */
$database = new MySQLDB ();

这就是我从另一个类调用数据库的方式。

    $q = "UPDATE users SET name = '$name', started = '$time' WHERE id = '$id';";
    $result = mysqli_query ( $database->connection, $q );

1 个答案:

答案 0 :(得分:2)

在你的情况下,我会做一些更清洁的事情,比如:

def insideCircle(idx: Int): Boolean = {
  val l = circleLeft.toIterator
  val r = circleRight.toIterator
  r.zip(l).find {
    case (x1, x2) =>
      idx < x1 && idx > x2
  }
  .isDefined
}

现在,要使用它,你只需要这样做:

<?php

class MySQLDB{

  private function openConnection(){

    // If you don't always use same credentials, pass them by params
    $servername = "localhost";
    $username = "username";
    $password = "password";
    $database = "database";

    // Create connection
    $conn = new mysqli($servername, $username, $password, $database);

    // Check connection
    if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
    }

    // Assign conection object
    return $conn;
  }

  private function closeConnection($conn){
    $conn->close();
  }

  function updateUserById($id, $name, $startedTime){

    $conn = $this->openConnection();

    $sqlQuery = "UPDATE users SET name = ?, started = ? WHERE id = ?";

    if ($stmt = $conn->prepare($sqlQuery)) {

      // Bind parameters
      $stmt->bind_param("ssi", $name, $startedTime, $id);

      // Execute query
      $stmt->execute();

      if ($stmt->errno) {
        die ( "Update failed: " . $stmt->error);
      }

      $stmt->close();
      }

    $this->closeConnection($conn);
  }

} // Class end