Using array keys and values to create sql select statement(使用数组键和值创建 sql select 语句)
本文介绍了使用数组键和值创建 sql select 语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试传递一个包含键和值的数组.
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");
我需要像这样创建 sql 语句:
I need the sql statement to be created like so:
select * from table where $key = $value;
推荐答案
您可以像这样构建一个简单的 SQL Select:
You can build a simple SQL Select like so:
<?php
/**
* @param array Column => Value pairs
* @return string
*/
function create_sql_select(array $pair){
$condition = array();
foreach ( $pair as $key => $value){
$condition[] = "{$key} = '{$value}'";
}
// Separate by AND delimiter if there are more than 1 pair
$condition = join(' AND ', $condition);
// Return prepared string:
return "SELECT * FROM your_table WHERE {$condition}";
}
//Will print: SELECT * FROM your_table WHERE user = 'some' AND age = '10'
print create_sql_select(array('user' => 'some', 'age' => 10));
这篇关于使用数组键和值创建 sql select 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:使用数组键和值创建 sql select 语句


基础教程推荐
猜你喜欢
- 使用 scandir() 在目录中查找文件夹 (PHP) 2022-01-01
- php 7.4 在写入变量中的 Twig 问题 2022-01-01
- 如何在数学上评估像“2-1"这样的字符串?产生“1"? 2022-01-01
- Yii2 - 在运行时设置邮件传输参数 2022-01-01
- Web 服务器如何处理请求? 2021-01-01
- php中的foreach复选框POST 2021-01-01
- 将变量从树枝传递给 js 2022-01-01
- 主题化 Drupal 7 的 Ubercart “/cart"页 2021-01-01
- php中的PDF导出 2022-01-01
- PHPUnit 的 Selenium 2 文档到底在哪里? 2022-01-01