Re: SQL Readability.. (was Re: most powerful php editor)
| From: | Jon Anderson | Date: | Fri, 26 Jan 2007 16:54:59 +0000 |
| Subject: | Re: SQL Readability.. (was Re: most powerful php editor) | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-247838@lists.php.net to get a copy of this message | ||
This may not be an option for many people, 'cause ISPs and web hosts may not be forward-thinking enough to install PDO or recent PHP, but...
PDO can do do this in a very database independant way, without having to do the equivalent of "mysql_real_escape_string":
$table = 'xyz';
$data = array(
'Field1' => "Data1",
'Field2' => "Data2"
);
$fields = implode(',',array_keys($data));
$placeholders = ':' . implode(',:',array_keys($data));
$stmt = $dbh->prepare("INSERT INTO $table ($fields) VALUES($placeholders)");
$stmt->execute($data);
With the added bonus that you can insert multiple rows quickly without having to rebuild any queries...
$stmt->execute($data1);
$stmt->execute($data2);
...
$stmt->execute($dataN);
(And PDO is super-fast compared to some other similar PHP-based libraries.)
jon
tg-php@gryffyndevelopment.com wrote:My contribution to the insanity.. INSERT statements made easy: $genericQY = "INSERT INTO MOD_LMGR_Leads ("; $genericQYvalues = " VALUES (";You call that readable?? $vals = array(); $vals['FirstName'] = 'John'; $vals['LastName'] = 'Smith'; $query = mysql_query(BuildInsert('MOD_LMGR_Leads', $vals)); function BuildInsert($table, $values) {$genericQY .= " FirstName,"; $genericQYvalues .= " 'John',"; $genericQY .= " LastName"; $genericQYvalues .= " 'Smith'"; $genericQY .= " )"; $genericQYvalues .= " );";$genericQY .= $genericQYvalues; $genericRS = mysql_query($genericQY);foreach (array_keys($values) as $key) $values[$key] = mysql_real_escape_string($values[$key]);$sql = 'insert into'.$table.'(`'; $sql.= implode(',', array_keys($values)); $sql.= '`) values ("'; $sql.= implode('","', array_values($values)); $sql.= '")';return $sql;} Note that this is a *very* cut down and untested version of BuildInsert. -Stut