寻求帮助使用mysqli使select语句动态化

时间:2016-01-20 13:12:55

标签: php sql mysqli

使用mysqli(PHP)制作动态选择语句
你好。我正在研究一个我可以使用的简单的crud系统 对于我的考试,我的问题是:

我想制作一个动态的选择语句,可以用 选择我要求的任何表格,与表格列相同 在我的数据库中 - 我相当新 php和面向对象的 编程所以,如果有人有一个简单的方法来做它。

到目前为止,这是我的选择课程:

   class select extends database{
    // Instance variables
    private $id;
    public $table;
    public $column;
    public $sql;
    public $result = array();

    // Methods - Behavior
    public function selectQuery($table){

        global $con;

        $sql = $this->sql;

        $sql = "SELECT * FROM {$table}";

        $result = $this->con->query($sql);

        while($row = $result->fetch_object()){
            //iterate all columns from the selected table 
            //and return it someway.
        }
    }
}
$selectQuery = new select();

这是我的数据库类

    require_once(LIB_PATH.DS."config.php");
    class database
    {
        public $con;
        public $result = array();

        public function __construct()
        {
            $this->con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB);
            if($this->con->connect_error){
                die($this->con->connect_error);
            }
        }
    }
    $db = new database();

所以到目前为止,我正在使用mysqli连接到我的数据库 然后我从我的数据库类扩展我的选择类,以便我可以得到连接
然后我想从

中选择全部

4 个答案:

答案 0 :(得分:3)

首先,您的select课程正在扩展database课程,因此在public $result = array();课程中重新声明select毫无意义,实际上甚至没有必要。

其次,既然您没有在课堂外使用对象属性,请将它们设为private

最后,由于您正在处理可变数量的参数,请使用func_get_args()函数。

以下是参考资料:

根据您的要求,解决方案是向selectQuery()方法发送可变数量的参数,并使用func_get_args()获取包含函数参数列表的数组。

  • 第一个参数是表名,其余参数是列名(如果提供)
  • 如果只有一个参数传递给函数,则SELECT查询将为SELECT * FROM table_name
  • 如果向函数传递了多个参数,则SELECT查询将为SELECT column1, column2, column3, ... FROM table_name

所以你的代码应该是这样的:

require_once(LIB_PATH.DS."config.php");

class database
{
    public $con;

    public function __construct()
    {
        $this->con = new mysqli(DB_HOST,DB_USERNAME,DB_PASSWORD,DB);
        if($this->con->connect_error){
            die($this->con->connect_error);
        }
    }
}

class select extends database{
    // Instance variables
    private $table;
    private $columns;
    private $sql;

    // Methods - Behavior
    public function selectQuery(){

        // incrementally construct the query
        $this->sql = "SELECT ";

        // get the argments passed to the function
        $this->columns = func_get_args();

        // the first argument would be the table name and rest of the arguments are coolumn names(if provided)
        $this->table = $this->columns[0];

        // if only one argument is passed to the function,
        // then SELECT query would be SELECT * FROM table_name
        if(count($this->columns) == 1){
            $this->sql .= "* ";
        }else{

            // if more than one argument is passed to the function,
            // then the SELECT query would be SELECT column1, column2, column3, ... FROM table_name
            for($i = 1; $i < count($this->columns); ++$i){
                $this->sql .= $this->columns[$i] . ",";
            }

            // remove the last , from the $sql string
            $this->sql = rtrim($this->sql, ",");
        }

        $this->sql .= " FROM $this->table";

        // execute the query
        $result = $this->con->query($this->sql);

        // return the result set
        return $result;
    }
}

$obj = new select();

$table = "YOUR_TABLE_NAME";
$column1 = "COLUMN_1";
$column2 = "COLUMN_2";

$result = $obj->selectQuery($table, $column1, $column2);
while($row = $result->fetch_assoc()){
    // display it
    echo $row[$column1] . " " . $row[$column2] . "<br />";
}

$result = $obj->selectQuery($table);
while($row = $result->fetch_assoc()){
    // display it
}

答案 1 :(得分:0)

这很简单

function conx(){

$link = new mysqli($db_host, $db_user, $db_pass, $db_name);

if ($link->connect_error) {
    die("Connection failed: " . $link->connect_error);
} 
 $sql = "SET NAMES utf8"; 
 $result = $link->query($sql); 
return $link;
}

现在你有一个连接让我们传递一个$ table值

$link = conx();
$sql = "SELECT * FROM $table";  <------ REMOVE {} from your table var!Worked for me
$result = $link->query($sql);
if(!$result) {echo 'Failed to query';};
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo $row["title"];
    }
} 
else {
    echo "0 results";
}
$link->close();
}

这是基本的!

答案 2 :(得分:0)

实际上 - 我不认为你离得很远;暂时忽略命名空间或任何特定的设计模式,有一些范围的缺点但是......

让我们假设一个目录结构,您可以将您的类和应用程序文件(例如index.php)粘合在一起:

<强> /class/Database.php

<?php

class Database {
    protected $con;

    public function __construct() {
        $this->con = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB);

        //error trapping
        if($this->con->connect_error) {
            die($this->con->connect_error);
        }

        //ok set charset; should add error trapping here too
        else {
            $this->con->set_charset('UTF8'); //probably
        }
    }
}

<强> /class/Select.php

<?php

class Select extends Database {

    // Class Members
    private $id;
    public $table;
    public $column;
    public $sql;
    public $result = array();

    // Methods - Behavior
    public function __construct() {
        parent::__construct();
    }

    public function selectQuery($table) {

        //since there's a $table class member... 
        $this->table = $this->con->real_escape_string($table);

        //query string
        $sql = "SELECT * FROM {$this->table}";

        //should be some error trapping here
        $response = $this->con->query($sql);

        //result
        while($row = $response->fetch_object()) {
            $this->result[] = $row;
        }

        //return
        return $this->result;
    }
}

<强>的index.php

<?php

//require is a language construct not a function
// - it doesn't need parentheses
require_once LIB_PATH.DS . 'config.php';
require_once '/path/to/class/Database.php';
require_once '/path/to/class/Select.php';

//build the object and run the query
$s = new Select;

// this should hold your resultset as an array of objects
// though it would also be accessible via $s->result since
// that's a public class member
$r = $s->selectQuery('my_table'); 

这虽然非常简单但并不十分实用(但你说这是考试,所以......)。

实际上,您可能不希望为每个查询启动新的数据库连接,因此可能值得查看static班级成员:http://php.net/manual/en/language.oop5.static.php

...或Singleton模式(尽管您可能想要也可能不想要Singleton数据库连接):http://www.phptherightway.com/pages/Design-Patterns.html

...也是封装,public类成员不是(通常)可取的:What is encapsulation with simple example in php?

答案 3 :(得分:-2)

db_connection.php

class db{
    private $db_host = '';
    private $db_user = 'user';
    private $db_pass = 'pass';
    private $db_name = 'your database name';
    protected $con;

    public function __construct(){
        $this->con = new mysqli($this->db_host,$this->db_user,$this->db_pass,$this->db_name);
        if ($this->con -> connect_errno) {
          echo "Failed to connect to MySQL: " . $this->con -> connect_error;
          exit();
        }
        return false;
    }

}    

query.php

require 'db_connection.php';
class query extends db{
    public function select($tableName,$column = null,$clause = null){
        $columns = null;
        if ($column == null) {
            $columns = '*';
        }else{
            $values = Array();
            foreach($column as $key => $value){
              array_push($values,"$value");
            }
            $columns = join(',',$values);
        }
        $select = null;
        $select .= "SELECT ".$columns." FROM {$tableName} ";
        if ($clause != null) {
            $select .= $clause;
        }
        $s_sql =  $this->con->prepare($select);
        $s_sql->execute();
        // It will return mysqli_stmt Object
        return $s_sql;
    }   

}

$s 将返回 mysqli_stmt 对象。

index.php

$query_ob = new query();
// The first parameter is required And other parameters is optional. 
// The second parameter must be Array[].
$s = $query_ob->select(parameter1,parameter1,parameter3);     
$r = $s->get_result();
while ($f = $r->fetch_assoc()) {
    // code here
}
$t->close();