tags: php SQL splicing
function select($table,$cond=array()){
$sql = "select * from `{$table}` where 1";
if (!empty($cond)){
foreach ($cond as $k=>$v){
if (is_array($v)){
switch ($v[0]){
case 'eq':
$op='=';
break;
case 'lt':
$op='<';
break;
case 'gt':
$op='>';
break;
case 'lte':
case 'elt':
$op='<=';
break;
case 'gte':
case 'egt':
$op='>=';
break;
case 'neq':
$op='<>';
break;
}
$sql.= " and `{$k}`{$op}'{$v[1]}'";
}else {
$sql .= " and `{$k}`='{$v}'";
}
}
}
return $sql;
}
$table = 'goods';
$cond = array(
'name'=>'pen',
'price'=>'255.00 yuan',
'aa'=>array('lt',12),
);
echo select($table,$cond);
This is just a simple SELECT splicing
$table = 'goods';
$data = array();
$data['name']='notebook';
$data['price']='2555.00 yuan';
$data['deal']='20,000 +';
$keys = array_keys($data);
$keys = array_map(function ($k){
return "`{$k}`";
},$keys);
$keys = implode(',',$keys);
$values = implode(',',array_map(function ($v){
return "'{$v}'";
},array_values($data)));
echo "insert into `{$table}` ({$keys}) values ({$values})";
$table = 'goods';
$data = array();
$data['name']='notebook';
$data['price']='2555.00 yuan';
$data['deal']='20,000 +';
$data['id']='11';
/ / Get the primary key
function getPrimaryKey($table){
$link = mysqli_connect('127.0.0.1','root','root','data','3308');
mysqli_set_charset($link,'utf8');
$rs = mysqli_query($link,"desc `{$table}`");
while ($rows = mysqli_fetch_assoc($rs)){
if ($rows['Key']=='PRI')
return $rows['Field'];
}
}
$pk = getPrimaryKey($table);
$keys = array_keys($data);
$index = array_search($pk,$keys);
unset($keys[$index]);
//$keys=array_keys($data);
$keys = implode(',',array_map(function ($k) use($data){
return "`{$k}`='{$data[$k]}'";
},$keys));
echo "update `{$table}` set {$keys} where `{$pk}`='{$data[$pk]}'";
Array_Keys (): Get the numerical value of the array
Array_Values (): Get every value of the array
Array_map (): The callback function returns yourself set value
Implode (): Segment an array with specified symbols
Python splicing generates SQL statement Gadgets, suitable for automatically generating simple SQL...
Dynamic IF statement splicing sql statement...
mybatis common transmission parameters placeholder manner, relatively safe, sql injection can be prevented. In some cases, special logic requires some special better java query package, and then packa...
First, create a Student class: Then use reflection to splicing into a strip data operation result: student (age, name, date) Values (1, 'Zhang San', '2017-06-10')...
Hero Table: Insert statement: insert into hero values(id,name,hp,damage) Java splicing: The rules are as follows: 1. The comma is separated by each data, so there must be "double quotes" bet...
The above-mentioned single insertion parameters, if the number of parameters inserted, can be implemented using the array parameters, and the number of parameters are as follows:...