我想创建一个动态查询,所以从表中选择一些值但由于没有单引号的列值失败。
if(isset($_POST['Filter'])) {
$filter = array('MC_SERIAL' => $_POST['mc-serial'],
'ID' => $_POST['id'],
'START_DATE' => $_POST['start-date'],
'END_DATE' => $_POST['end-date'],
);
$type = $_POST['type'];
$query_array = array();
foreach ($filter as $key => $value) {
if ($value != ''){
$query_array[] = $key.' = '.$value;
}
}
if ($type == 'AMC'){
$tableName = 'AMC';
}
if ($type == '4C'){
$tableName = '4C';
}
if ($type == 'RENTAL'){
$tableName = 'RENTAL';
}
$query = 'SELECT * FROM '.$tableName.' WHERE '.implode('AND', $query_array);
echo $query;
}
我上面的代码给了我
SELECT * FROM AMC WHERE MC_SERIAL = test001 AND ID = 001 AND START_DATE = 01-01-2017
但我想要这样的东西
SELECT * FROM AMC WHERE MC_SERIAL = 'test001' AND ID = '001' AND START_DATE = '01-01-2017'
答案 0 :(得分:0)
请不要在没有任何转义的情况下使用$_POST
值。此代码易受SQL注入攻击。如果您使用MySQLi
至少escape个值(作为优惠,您无需担心过滤器中的'
和"
)
<?php
if (isset($_POST['Filter'])) {
$filter = array(
'MC_SERIAL' => $_POST['mc-serial'],
'ID' => $_POST['id'],
'START_DATE' => $_POST['start-date'],
'END_DATE' => $_POST['end-date'],
);
$type = $_POST['type'];
$query_array = array();
foreach ($filter as $key => $value) {
if ($value != '') {
$query_array[] = $key . ' = "' . mysqli_real_escape_string($value) . '"';
}
}
if ($type == 'AMC') {
$tableName = 'AMC';
}
if ($type == '4C') {
$tableName = '4C';
}
if ($type == 'RENTAL') {
$tableName = 'RENTAL';
}
$query = 'SELECT * FROM ' . $tableName . ' WHERE ' . implode('AND', $query_array);
echo $query;
}
答案 1 :(得分:-1)
只需以这种方式更改代码
foreach ($filter as $key => $value) {
if ($value != ''){
$query_array[] = $key." = '".$value . "'";
}
}