note 92656 deleted from function.mysql-query by danbrown
| From: | danbrown@php.net | Date: | Mon, 03 Aug 2009 16:50:52 +0000 |
| Subject: | note 92656 deleted from function.mysql-query by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-159040@lists.php.net to get a copy of this message | ||
Note Submitter: hidendra at rs2reborn dot net
----
i made two useful functions (well to me, anyway) to build and insert a query based on an array..
instead of having long queries that could become hard to read.
example:
<?php
insert_array('users', array( 'username' => 'bob',
'password' => 'pass123' ));
?>
would return a query executed with:
INSERT INTO
users SET username='bob',
password='pass123';
<?php
select_array('users', array(), array('username' => 'bob',
'password' => 'pass123'));
?>
would return a query executed with:
SELECT * FROM users WHERE username='bob' AND
password='pass123';
an empty array for the second parameter for select_array uses *, but it can be used like so:
array('username', 'password', 'email', 'etc')
hopefully someone finds these useful!
<?php
function insert_array($table, $arr) {
$temp = null;
$arrstr = "";
$c = 0;
if(!is_array($arr)) {
return null;
}
/*
* Generate the insert clause
*/
foreach($arr as $name => $value) {
if(strlen($arrstr) == 0) {
$arrstr .= 'SET ';
}
$arrstr .= ($c > 0 ? ', ' : '') .
'' . $name . '=' . '\'' . $value .
'\'';
if($c == 0) {
$c = 1;
}
}
/*
* Now execute the query and then return it.
*/
$temp = mysql_query('INSERT INTO ' . $table . ' ' . $arrstr .
';');
return $temp;
}
function select_array($table, $arr, $where = array()) {
$temp = null;
$arrstr = "";
$wherestr = "";
$c = 0;
if(!is_array($arr) || !is_array($where)) {
return null;
}
/*
* If it's an empty array we want everything from the table (greedy har har).
*/
if(count($arr) == 0) {
$arrstr = "*";
}
/*
* Generate the values to grab from the table
*/
foreach($arr as $name) {
$arrstr .= ($c > 0 ? ',' : '') .
'' . $name . '';
if($c == 0) {
$c = 1;
}
}
$c = 0;
/*
* Generate the where clause
*/
foreach($where as $name => $value) {
if(strlen($wherestr) == 0) {
$wherestr .= 'WHERE ';
}
$wherestr .= ($c > 0 ? ' AND ' : '') .
'' . $name . '=' . '\'' . $value .
'\'';
if($c == 0) {
$c = 1;
}
}
/*
* Build the query now with the generated strings
*/
$temp = mysql_query('SELECT ' . $arrstr . ' FROM ' . $table .
' ' . $wherestr . ';');
return $temp;
}
?>