本文介绍了使用数组键和值来创建SQL SELECT语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想通过一个包含键和值的数组。
键是列和值选择的值。
我试图写一个函数在那里我可以传递一个数组,并使用键和值作为表的列和值。例如:
$阵列=阵列(用户=>中乔,USER_ID =2);
我需要的sql语句中像这样创建:
select * from表,其中$键= $价值;
解决方案
这是你想要什么:
< PHP
/ **
* @参数数组WHERE子句
* @返回字符串
* /
功能sql_select中(数组$对){
//初始化刚刚COND数组:
$条件=阵列(); 的foreach($对作为重点$ = GT; $值){
//噢,你还可以自动prevent SQL注入
$值= mysql_real_escape_string($值); $条件[] ={$ key}的='{$}价值';
} //为WHERE子句prepare:
$条件=加入(和,$条件);
//返回prepared字符串:
返回SELECT * FROM your_table其中{$}条件;
}//打印:SELECT * FROM your_table其中user ='一些'AND年龄='10'
打印sql_select中(阵列('用户'=>'有些','年龄'=> 10));
这就是所谓的ORM的方法。
I am trying to pass a array that contains keys and values.
The keys are columns and values are the values to select.
I am trying to write a function where I can pass a array and use the key and values as the column and values of a table. for example:
$array = array("user"=>"joe", user_id="2");
I need the sql statement to be created like so:
select * from table where $key = $value;
解决方案
This is what you want:
<?php
/**
* @param array for WHERE clause
* @return string
*/
function sql_select(array $pair){
//just init cond array:
$condition = array();
foreach ( $pair as $key => $value){
//oh yeah, you can also automatically prevent SQL injection
$value = mysql_real_escape_string($value);
$condition[] = "{$key} = '{$value}'";
}
//Prepare for WHERE clause:
$condition = join(' AND ', $condition);
//Return prepared string:
return "SELECT * FROM your_table WHERE {$condition}";
}
//print: SELECT * FROM your_table WHERE user = 'some' AND age = '10'
print sql_select(array('user' => 'some', 'age' => 10));
This is called ORM approach.
这篇关于使用数组键和值来创建SQL SELECT语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!