Saya pribadi tidak pandai melakukan string kueri MySQL, saya biasanya menggunakan kelas kompiler sql yang mirip dengan ini (perlu diingat, ini hanya yang cepat). Ini memungkinkan untuk mengikat, yang Anda butuhkan, terutama dengan $_GET
nilai-nilai seperti yang Anda miliki:
class ItemQueue
{
protected $sql;
protected $wherevals;
public $bind;
public $compiled;
public function select($values = false)
{
$this->sql[] = "select";
if($values == false)
$this->sql[] = "*";
else
$this->sql[] = $values;
return $this;
}
public function from($table = false)
{
if($table ==false)
return $this;
$this->sql[] = "from `$table`";
return $this;
}
public function where($values = array(),$op = 'and')
{
if(!empty($values)) {
$this->sql[] = 'where';
foreach($values as $key => $values) {
$this->wherevals[] = $key.' = :'.$key;
// Bind values for injection protection
$this->bind[":$key"] = $values;
}
$this->sql[] = implode(" $op ",$this->wherevals);
// This part is a bit jenky but you get the idea
$this->sql[] = "and active = '1'";
}
return $this;
}
public function customsql($values = false)
{
if($values != false) {
$this->sql[] = $values;
}
return $this;
}
public function Fetch()
{
// Implode entire sql statement
$this->compiled = implode(" ", $this->sql);
return $this;
}
}
// Post/Get values
$_POST['cat'] = 'cattest';
$_POST['city'] = 'Reno';
$_POST['state'] = 'Nevada';
// Arbitrary limits
$limit = 1;
$limitvalue = 1;
// Create instance
$tester = new ItemQueue();
// Just set some array filtering/validating
if(isset($_POST['cat']) && !empty($_POST['cat']))
$array['cat'] = $_POST['cat'];
if(isset($_POST['city']) && !empty($_POST['city']))
$array['city'] = $_POST['city'];
if(isset($_POST['state']) && !empty($_POST['state']))
$array['state'] = $_POST['state'];
// Make the query
$query = $tester->select()->from("items")->where($array,"or")->customsql("ORDER BY item_id DESC LIMIT $limitvalue, $limit");
// Here is the sql statement
echo $query->Fetch()->compiled;
// Bind array
print_r($query->bind);
Memberikan Anda:
select * from `items` where cat = :cat or city = :city or state = :state and active = '1' ORDER BY item_id DESC LIMIT 1, 1
Array
(
[:cat] => cattest
[:city] => Reno
[:state] => Nevada
)
Perhatikan, ini mengharuskan Anda untuk menggunakan koneksi yang tepat (PDO berfungsi paling baik dalam kasus ini).