2012-09-05 21:59:15 +02:00
|
|
|
<?php
|
2012-09-05 23:45:13 +02:00
|
|
|
class Application_Common_Database
|
|
|
|
{
|
2012-09-06 22:46:22 +02:00
|
|
|
public static function prepareAndExecute($sql, array $paramValueMap,
|
2012-09-06 16:38:14 +02:00
|
|
|
$type='all', $fetchType=PDO::FETCH_ASSOC)
|
2012-09-05 23:44:09 +02:00
|
|
|
{
|
2012-09-05 22:14:08 +02:00
|
|
|
$con = Propel::getConnection();
|
2012-09-05 21:59:15 +02:00
|
|
|
$stmt = $con->prepare($sql);
|
|
|
|
foreach ($paramValueMap as $param => $v) {
|
|
|
|
$stmt->bindValue($param, $v);
|
|
|
|
}
|
2012-09-05 22:14:08 +02:00
|
|
|
$rows = array();
|
2012-09-05 21:59:15 +02:00
|
|
|
if ($stmt->execute()) {
|
|
|
|
if ($type == 'single') {
|
2012-09-05 23:52:53 +02:00
|
|
|
$rows = $stmt->fetch($fetchType);
|
|
|
|
} else if ($type == 'column'){
|
2012-09-05 21:59:15 +02:00
|
|
|
$rows = $stmt->fetchColumn();
|
2012-09-06 22:46:22 +02:00
|
|
|
} else if ($type == 'all') {
|
2012-09-05 23:52:53 +02:00
|
|
|
$rows = $stmt->fetchAll($fetchType);
|
2012-09-06 22:46:22 +02:00
|
|
|
} else if ($type == 'execute') {
|
|
|
|
$rows = null;
|
|
|
|
} else {
|
|
|
|
$msg = "bad type passed: type($type)";
|
|
|
|
throw new Exception("Error: $msg");
|
2012-09-05 22:14:08 +02:00
|
|
|
}
|
|
|
|
} else {
|
|
|
|
$msg = implode(',', $stmt->errorInfo());
|
|
|
|
throw new Exception("Error: $msg");
|
2012-09-05 21:59:15 +02:00
|
|
|
}
|
|
|
|
return $rows;
|
|
|
|
}
|
2012-09-07 23:58:16 +02:00
|
|
|
/*
|
|
|
|
Wrapper around prepareAndExecute that allows you to use multipe :xx's
|
|
|
|
in one query. Transforms $sql to :xx1, :xx2, ....
|
|
|
|
*/
|
|
|
|
public static function smartPrepareAndExecute($sql, array $params,
|
|
|
|
$type='all', $fetchType=PDO::FETCH_ASSOC)
|
|
|
|
{
|
|
|
|
$new_params = array();
|
|
|
|
$new_sql = $sql;
|
|
|
|
foreach ($params as $k => $v) {
|
|
|
|
$matches_count = substr_count($sql, $k);
|
|
|
|
if ($matches_count == 0) {
|
|
|
|
throw new Exception("Argument $k is not inside $sql");
|
|
|
|
} elseif ($matches_count == 1) {
|
|
|
|
$new_params[$k] = $new_params[$v];
|
|
|
|
} else {
|
|
|
|
foreach ( range(1,$matches_count) as $i ) {
|
2012-09-13 16:34:15 +02:00
|
|
|
preg_replace( "/$k(\D)/", "$k$i${1}", $sql, 1);
|
2012-09-07 23:58:16 +02:00
|
|
|
$new_params[ $k.$i ] = $v;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return Application_Common_Database::prepareAndExecute( $new_sql,
|
|
|
|
$new_params, $type, $fetchType);
|
|
|
|
}
|
2012-09-05 23:44:09 +02:00
|
|
|
}
|