本文介紹了使用數組鍵和值創建 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 語句的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!