arrayfromquery optimizations: move double if from inside loop to outside + use directly mysqli calls to avoid function call overhead for every row retrieved from db

git-svn-id: http://piwigo.org/svn/trunk@27336 68402e56-0260-453c-a942-63ccdbb3a9ee
This commit is contained in:
rvelices 2014-02-11 21:47:44 +00:00
parent 78621a3487
commit 2d9887993c
6 changed files with 192 additions and 131 deletions

View file

@ -133,14 +133,13 @@ SELECT representative_picture_id
if ($conf['display_fromto']) if ($conf['display_fromto'])
{ {
$dates_of_category = array();
if (count($category_ids) > 0) if (count($category_ids) > 0)
{ {
$query = ' $query = '
SELECT SELECT
category_id, category_id,
MIN(date_creation) AS date_creation_min, MIN(date_creation) AS `from`,
MAX(date_creation) AS date_creation_max MAX(date_creation) AS `to`
FROM '.IMAGE_CATEGORY_TABLE.' FROM '.IMAGE_CATEGORY_TABLE.'
INNER JOIN '.IMAGES_TABLE.' ON image_id = id INNER JOIN '.IMAGES_TABLE.' ON image_id = id
WHERE category_id IN ('.implode(',', $category_ids).') WHERE category_id IN ('.implode(',', $category_ids).')
@ -155,14 +154,7 @@ SELECT
).' ).'
GROUP BY category_id GROUP BY category_id
;'; ;';
$result = pwg_query($query); $dates_of_category = query2array($query, 'category_id');
while ($row = pwg_db_fetch_assoc($result))
{
$dates_of_category[ $row['category_id'] ] = array(
'from' => $row['date_creation_min'],
'to' => $row['date_creation_max'],
);
}
} }
} }

View file

@ -760,4 +760,74 @@ function my_error($header, $die)
echo("</pre>"); echo("</pre>");
} }
/**
* Builds an data array from a SQL query.
* Depending on $key_name and $value_name it can return :
*
* - an array of arrays of all fields (key=null, value=null)
* array(
* array('id'=>1, 'name'=>'DSC8956', ...),
* array('id'=>2, 'name'=>'DSC8957', ...),
* ...
* )
*
* - an array of a single field (key=null, value='...')
* array('DSC8956', 'DSC8957', ...)
*
* - an associative array of array of all fields (key='...', value=null)
* array(
* 'DSC8956' => array('id'=>1, 'name'=>'DSC8956', ...),
* 'DSC8957' => array('id'=>2, 'name'=>'DSC8957', ...),
* ...
* )
*
* - an associative array of a single field (key='...', value='...')
* array(
* 'DSC8956' => 1,
* 'DSC8957' => 2,
* ...
* )
*
* @since 2.6
*
* @param string $query
* @param string $key_name
* @param string $value_name
* @return array
*/
function query2array($query, $key_name=null, $value_name=null)
{
$result = pwg_query($query);
$data = array();
if (isset($key_name))
{
if (isset($value_name))
{
while ($row = pwg_db_fetch_assoc($result))
$data[ $row[$key_name] ] = $row[$value_name];
}
else
{
while ($row = pwg_db_fetch_assoc($result))
$data[ $row[$key_name] ] = $row;
}
}
else
{
if (isset($value_name))
{
while ($row = pwg_db_fetch_assoc($result))
$data[] = $row[$value_name];
}
else
{
while ($row = pwg_db_fetch_assoc($result))
$data[] = $row;
}
}
return $data;
}
?> ?>

View file

@ -799,4 +799,74 @@ function my_error($header, $die)
echo("</pre>"); echo("</pre>");
} }
/**
* Builds an data array from a SQL query.
* Depending on $key_name and $value_name it can return :
*
* - an array of arrays of all fields (key=null, value=null)
* array(
* array('id'=>1, 'name'=>'DSC8956', ...),
* array('id'=>2, 'name'=>'DSC8957', ...),
* ...
* )
*
* - an array of a single field (key=null, value='...')
* array('DSC8956', 'DSC8957', ...)
*
* - an associative array of array of all fields (key='...', value=null)
* array(
* 'DSC8956' => array('id'=>1, 'name'=>'DSC8956', ...),
* 'DSC8957' => array('id'=>2, 'name'=>'DSC8957', ...),
* ...
* )
*
* - an associative array of a single field (key='...', value='...')
* array(
* 'DSC8956' => 1,
* 'DSC8957' => 2,
* ...
* )
*
* @since 2.6
*
* @param string $query
* @param string $key_name
* @param string $value_name
* @return array
*/
function query2array($query, $key_name=null, $value_name=null)
{
$result = pwg_query($query);
$data = array();
if (isset($key_name))
{
if (isset($value_name))
{
while ($row = $result->fetch_assoc())
$data[ $row[$key_name] ] = $row[$value_name];
}
else
{
while ($row = $result->fetch_assoc())
$data[ $row[$key_name] ] = $row;
}
}
else
{
if (isset($value_name))
{
while ($row = $result->fetch_assoc())
$data[] = $row[$value_name];
}
else
{
while ($row = $result->fetch_assoc())
$data[] = $row;
}
}
return $data;
}
?> ?>

View file

@ -1,4 +1,4 @@
<?php <?php
// +-----------------------------------------------------------------------+ // +-----------------------------------------------------------------------+
// | Piwigo - a PHP based photo gallery | // | Piwigo - a PHP based photo gallery |
// +-----------------------------------------------------------------------+ // +-----------------------------------------------------------------------+
@ -481,16 +481,16 @@ function dateDiff($date1, $date2)
{ {
return $date1->diff($date2); return $date1->diff($date2);
} }
$diff = new stdClass(); $diff = new stdClass();
//Make sure $date1 is ealier //Make sure $date1 is ealier
$diff->invert = $date2 < $date1; $diff->invert = $date2 < $date1;
if ($diff->invert) if ($diff->invert)
{ {
list($date1, $date2) = array($date2, $date1); list($date1, $date2) = array($date2, $date1);
} }
//Calculate R values //Calculate R values
$R = ($date1 <= $date2 ? '+' : '-'); $R = ($date1 <= $date2 ? '+' : '-');
$r = ($date1 <= $date2 ? '' : '-'); $r = ($date1 <= $date2 ? '' : '-');
@ -524,14 +524,14 @@ function dateDiff($date1, $date2)
//Reset date and record increments //Reset date and record increments
$date1->modify('-1 '.$period); $date1->modify('-1 '.$period);
} }
list($diff->y, $diff->m, $diff->d, $diff->h) = array_values($periods); list($diff->y, $diff->m, $diff->d, $diff->h) = array_values($periods);
//Minutes, seconds //Minutes, seconds
$diff->s = round(abs($date1->format('U') - $date2->format('U'))); $diff->s = round(abs($date1->format('U') - $date2->format('U')));
$diff->i = floor($diff->s/60); $diff->i = floor($diff->s/60);
$diff->s = $diff->s - $diff->i*60; $diff->s = $diff->s - $diff->i*60;
return $diff; return $diff;
} }
@ -569,12 +569,12 @@ function str2DateTime($original, $format=null)
$ymdhms[] = $tok; $ymdhms[] = $tok;
$tok = strtok('- :/'); $tok = strtok('- :/');
} }
if (count($ymdhms)<3) return false; if (count($ymdhms)<3) return false;
if (!isset($ymdhms[3])) $ymdhms[3] = 0; if (!isset($ymdhms[3])) $ymdhms[3] = 0;
if (!isset($ymdhms[4])) $ymdhms[4] = 0; if (!isset($ymdhms[4])) $ymdhms[4] = 0;
if (!isset($ymdhms[5])) $ymdhms[5] = 0; if (!isset($ymdhms[5])) $ymdhms[5] = 0;
$date = new DateTime(); $date = new DateTime();
$date->setDate($ymdhms[0], $ymdhms[1], $ymdhms[2]); $date->setDate($ymdhms[0], $ymdhms[1], $ymdhms[2]);
$date->setTime($ymdhms[3], $ymdhms[4], $ymdhms[5]); $date->setTime($ymdhms[3], $ymdhms[4], $ymdhms[5]);
@ -595,7 +595,7 @@ function str2DateTime($original, $format=null)
function format_date($original, $show_time=false, $show_day_name=true, $format=null) function format_date($original, $show_time=false, $show_day_name=true, $format=null)
{ {
global $lang; global $lang;
$date = str2DateTime($original, $format); $date = str2DateTime($original, $format);
if (!$date) if (!$date)
@ -608,11 +608,11 @@ function format_date($original, $show_time=false, $show_day_name=true, $format=n
{ {
$print.= $lang['day'][ $date->format('w') ].' '; $print.= $lang['day'][ $date->format('w') ].' ';
} }
$print.= $date->format('j'); $print.= $date->format('j');
$print.= ' '.$lang['month'][ $date->format('n') ]; $print.= ' '.$lang['month'][ $date->format('n') ];
$print.= ' '.$date->format('Y'); $print.= ' '.$date->format('Y');
if ($show_time) if ($show_time)
{ {
$temp = $date->format('H:i'); $temp = $date->format('H:i');
@ -643,10 +643,10 @@ function time_since($original, $stop='minute', $format=null, $with_text=true, $w
{ {
return l10n('N/A'); return l10n('N/A');
} }
$now = new DateTime(); $now = new DateTime();
$diff = dateDiff($now, $date); $diff = dateDiff($now, $date);
$chunks = array( $chunks = array(
'year' => $diff->y, 'year' => $diff->y,
'month' => $diff->m, 'month' => $diff->m,
@ -656,16 +656,16 @@ function time_since($original, $stop='minute', $format=null, $with_text=true, $w
'minute' => $diff->i, 'minute' => $diff->i,
'second' => $diff->s, 'second' => $diff->s,
); );
// DateInterval does not contain the number of weeks // DateInterval does not contain the number of weeks
if ($with_week) if ($with_week)
{ {
$chunks['week'] = (int)floor($chunks['day']/7); $chunks['week'] = (int)floor($chunks['day']/7);
$chunks['day'] = $chunks['day'] - $chunks['week']*7; $chunks['day'] = $chunks['day'] - $chunks['week']*7;
} }
$j = array_search($stop, array_keys($chunks)); $j = array_search($stop, array_keys($chunks));
$print = ''; $i=0; $print = ''; $i=0;
foreach ($chunks as $name => $value) foreach ($chunks as $name => $value)
{ {
@ -679,9 +679,9 @@ function time_since($original, $stop='minute', $format=null, $with_text=true, $w
} }
$i++; $i++;
} }
$print = trim($print); $print = trim($print);
if ($with_text) if ($with_text)
{ {
if ($diff->invert) if ($diff->invert)
@ -933,7 +933,7 @@ SELECT element_id
FROM '.CADDIE_TABLE.' FROM '.CADDIE_TABLE.'
WHERE user_id = '.$user['id'].' WHERE user_id = '.$user['id'].'
;'; ;';
$in_caddie = array_from_query($query, 'element_id'); $in_caddie = query2array($query, null, 'element_id');
$caddiables = array_diff($elements_id, $in_caddie); $caddiables = array_diff($elements_id, $in_caddie);
@ -1042,7 +1042,7 @@ function get_l10n_args($key, $args='')
/** /**
* returns a string formated with l10n elements. * returns a string formated with l10n elements.
* it is usefull to "prepare" a text and translate it later * it is usefull to "prepare" a text and translate it later
* @see get_l10n_args() * @see get_l10n_args()
* *
* @param array $key_args one l10n_args element or array of l10n_args elements * @param array $key_args one l10n_args element or array of l10n_args elements
* @param string $sep used when translated elements are concatened * @param string $sep used when translated elements are concatened
@ -1152,7 +1152,7 @@ SELECT param, value
} }
$conf[ $row['param'] ] = $val; $conf[ $row['param'] ] = $val;
} }
trigger_action('load_conf', $condition); trigger_action('load_conf', $condition);
} }
@ -1165,13 +1165,11 @@ SELECT param, value
function conf_update_param($param, $value) function conf_update_param($param, $value)
{ {
$query = ' $query = '
SELECT SELECT param
param,
value
FROM '.CONFIG_TABLE.' FROM '.CONFIG_TABLE.'
WHERE param = \''.$param.'\' WHERE param = \''.$param.'\'
;'; ;';
$params = array_from_query($query, 'param'); $params = query2array($query, null, 'param');
if (count($params) == 0) if (count($params) == 0)
{ {
@ -1203,7 +1201,7 @@ UPDATE '.CONFIG_TABLE.'
function conf_delete_param($params) function conf_delete_param($params)
{ {
global $conf; global $conf;
if (!is_array($params)) if (!is_array($params))
{ {
$params = array($params); $params = array($params);
@ -1212,13 +1210,13 @@ function conf_delete_param($params)
{ {
return; return;
} }
$query = ' $query = '
DELETE FROM '.CONFIG_TABLE.' DELETE FROM '.CONFIG_TABLE.'
WHERE param IN(\''. implode('\',\'', $params) .'\') WHERE param IN(\''. implode('\',\'', $params) .'\')
;'; ;';
pwg_query($query); pwg_query($query);
foreach ($params as $param) foreach ($params as $param)
{ {
unset($conf[$param]); unset($conf[$param]);
@ -1243,69 +1241,6 @@ function prepend_append_array_items($array, $prepend_str, $append_str)
return $array; return $array;
} }
/**
* Builds an data array from a SQL query.
* Depending on $key_name and $value_name it can return :
*
* - an array of arrays of all fields (key=null, value=null)
* array(
* array('id'=>1, 'name'=>'DSC8956', ...),
* array('id'=>2, 'name'=>'DSC8957', ...),
* ...
* )
*
* - an array of a single field (key=null, value='...')
* array('DSC8956', 'DSC8957', ...)
*
* - an associative array of array of all fields (key='...', value=null)
* array(
* 'DSC8956' => array('id'=>1, 'name'=>'DSC8956', ...),
* 'DSC8957' => array('id'=>2, 'name'=>'DSC8957', ...),
* ...
* )
*
* - an associative array of a single field (key='...', value='...')
* array(
* 'DSC8956' => 1,
* 'DSC8957' => 2,
* ...
* )
*
* @since 2.6
*
* @param string $query
* @param string $key_name
* @param string $value_name
* @return array
*/
function query2array($query, $key_name=null, $value_name=null)
{
$result = pwg_query($query);
$data = array();
while ($row = pwg_db_fetch_assoc($result))
{
if (isset($value_name))
{
$value = $row[ $value_name ];
}
else
{
$value = $row;
}
if (isset($key_name))
{
$data[ $row[$key_name] ] = $value;
}
else
{
$data[] = $value;
}
}
return $data;
}
/** /**
* creates an simple hashmap based on a SQL query. * creates an simple hashmap based on a SQL query.
* choose one to be the key, another one to be the value. * choose one to be the key, another one to be the value.
@ -1368,7 +1303,7 @@ function array_from_query($query, $fieldname=false)
{ {
while ($row = pwg_db_fetch_assoc($result)) while ($row = pwg_db_fetch_assoc($result))
{ {
$array[] = $row; $array[] = $row;
} }
} }
else else
@ -1493,7 +1428,7 @@ function get_parent_language($lang_id=null)
function load_language($filename, $dirname = '', $options = array()) function load_language($filename, $dirname = '', $options = array())
{ {
global $user, $language_files; global $user, $language_files;
if ( !empty($dirname) and !empty($filename) ) if ( !empty($dirname) and !empty($filename) )
{ {
if ( empty($language_files[$dirname]) or !in_array($filename,$language_files[$dirname]) ) if ( empty($language_files[$dirname]) or !in_array($filename,$language_files[$dirname]) )
@ -1573,7 +1508,7 @@ function load_language($filename, $dirname = '', $options = array())
global $lang, $lang_info; global $lang, $lang_info;
if ( !isset($lang) ) $lang=array(); if ( !isset($lang) ) $lang=array();
if ( !isset($lang_info) ) $lang_info=array(); if ( !isset($lang_info) ) $lang_info=array();
$parent_language = !empty($load_lang_info['parent']) ? $load_lang_info['parent'] : ( $parent_language = !empty($load_lang_info['parent']) ? $load_lang_info['parent'] : (
!empty($lang_info['parent']) ? $lang_info['parent'] : null ); !empty($lang_info['parent']) ? $lang_info['parent'] : null );
if (!empty($parent_language) and $parent_language != $selected_language) if (!empty($parent_language) and $parent_language != $selected_language)
@ -2065,7 +2000,7 @@ SELECT COUNT(DISTINCT(com.id))
AND ', $where); AND ', $where);
list($user['nb_available_comments']) = pwg_db_fetch_row(pwg_query($query)); list($user['nb_available_comments']) = pwg_db_fetch_row(pwg_query($query));
single_update(USER_CACHE_TABLE, single_update(USER_CACHE_TABLE,
array('nb_available_comments'=>$user['nb_available_comments']), array('nb_available_comments'=>$user['nb_available_comments']),
array('user_id'=>$user['id']) array('user_id'=>$user['id'])
); );
@ -2086,15 +2021,15 @@ SELECT COUNT(DISTINCT(com.id))
function safe_version_compare($a, $b, $op=null) function safe_version_compare($a, $b, $op=null)
{ {
$replace_chars = create_function('$m', 'return ord(strtolower($m[1]));'); $replace_chars = create_function('$m', 'return ord(strtolower($m[1]));');
// add dot before groups of letters (version_compare does the same thing) // add dot before groups of letters (version_compare does the same thing)
$a = preg_replace('#([0-9]+)([a-z]+)#i', '$1.$2', $a); $a = preg_replace('#([0-9]+)([a-z]+)#i', '$1.$2', $a);
$b = preg_replace('#([0-9]+)([a-z]+)#i', '$1.$2', $b); $b = preg_replace('#([0-9]+)([a-z]+)#i', '$1.$2', $b);
// apply ord() to any single letter // apply ord() to any single letter
$a = preg_replace_callback('#\b([a-z]{1})\b#i', $replace_chars, $a); $a = preg_replace_callback('#\b([a-z]{1})\b#i', $replace_chars, $a);
$b = preg_replace_callback('#\b([a-z]{1})\b#i', $replace_chars, $b); $b = preg_replace_callback('#\b([a-z]{1})\b#i', $replace_chars, $b);
if (empty($op)) if (empty($op))
{ {
return version_compare($a, $b); return version_compare($a, $b);

View file

@ -70,7 +70,7 @@ SELECT tag_id, COUNT(DISTINCT(it.image_id)) AS counter
).' ).'
GROUP BY tag_id GROUP BY tag_id
;'; ;';
$tag_counters = simple_hash_from_query($query, 'tag_id', 'counter'); $tag_counters = query2array($query, 'tag_id', 'counter');
if ( empty($tag_counters) ) if ( empty($tag_counters) )
{ {
@ -233,7 +233,7 @@ SELECT id
} }
$query .= "\n".(empty($order_by) ? $conf['order_by'] : $order_by); $query .= "\n".(empty($order_by) ? $conf['order_by'] : $order_by);
return array_from_query($query, 'id'); return query2array($query, null, 'id');
} }
/** /**
@ -320,13 +320,7 @@ SELECT *
WHERE '. implode( ' WHERE '. implode( '
OR ', $where_clauses); OR ', $where_clauses);
$result = pwg_query($query); return query2array($query);
$tags = array();
while ($row = pwg_db_fetch_assoc($result))
{
$tags[] = $row;
}
return $tags;
} }
?> ?>

View file

@ -92,7 +92,7 @@ if (script_basename() == 'picture')
{ {
// url compatibility with versions below 1.6 // url compatibility with versions below 1.6
if ( isset($_GET['image_id']) if ( isset($_GET['image_id'])
and isset($_GET['cat']) and isset($_GET['cat'])
and is_numeric($_GET['cat']) ) and is_numeric($_GET['cat']) )
{ {
$url = make_picture_url( array( $url = make_picture_url( array(
@ -102,7 +102,7 @@ if (script_basename() == 'picture')
) ); ) );
redirect($url); redirect($url);
} }
$token = $tokens[$next_token]; $token = $tokens[$next_token];
$next_token++; $next_token++;
if ( is_numeric($token) ) if ( is_numeric($token) )
@ -242,7 +242,7 @@ if ('categories' == $page['section'])
if (isset($page['category'])) if (isset($page['category']))
{ {
$page = array_merge( $page = array_merge(
$page, $page,
array( array(
'comment' => trigger_event( 'comment' => trigger_event(
'render_category_description', 'render_category_description',
@ -292,8 +292,8 @@ SELECT id
), ),
"\n AND" "\n AND"
); );
$subcat_ids = array_from_query($query, 'id'); $subcat_ids = query2array($query,null, 'id');
$subcat_ids[] = $page['category']['id']; $subcat_ids[] = $page['category']['id'];
$where_sql = 'category_id IN ('.implode(',',$subcat_ids).')'; $where_sql = 'category_id IN ('.implode(',',$subcat_ids).')';
// remove categories from forbidden because just checked above // remove categories from forbidden because just checked above
@ -325,7 +325,7 @@ SELECT DISTINCT(image_id)
'.$conf['order_by'].' '.$conf['order_by'].'
;'; ;';
$page['items'] = array_from_query($query, 'image_id'); $page['items'] = query2array($query,null, 'image_id');
} }
} }
// special sections // special sections
@ -416,7 +416,7 @@ SELECT image_id
$page = array_merge( $page = array_merge(
$page, $page,
array( array(
'items' => array_from_query($query, 'image_id'), 'items' => query2array($query,null, 'image_id'),
) )
); );
@ -463,7 +463,7 @@ SELECT DISTINCT(id)
array( array(
'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">' 'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
.l10n('Recent photos').'</a>', .l10n('Recent photos').'</a>',
'items' => array_from_query($query, 'id'), 'items' => query2array($query,null, 'id'),
) )
); );
} }
@ -486,7 +486,7 @@ SELECT DISTINCT(id)
{ {
$page['super_order_by'] = true; $page['super_order_by'] = true;
$conf['order_by'] = ' ORDER BY hit DESC, id DESC'; $conf['order_by'] = ' ORDER BY hit DESC, id DESC';
$query = ' $query = '
SELECT DISTINCT(id) SELECT DISTINCT(id)
FROM '.IMAGES_TABLE.' FROM '.IMAGES_TABLE.'
@ -502,7 +502,7 @@ SELECT DISTINCT(id)
array( array(
'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">' 'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
.$conf['top_number'].' '.l10n('Most visited').'</a>', .$conf['top_number'].' '.l10n('Most visited').'</a>',
'items' => array_from_query($query, 'id'), 'items' => query2array($query,null, 'id'),
) )
); );
} }
@ -528,7 +528,7 @@ SELECT DISTINCT(id)
array( array(
'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">' 'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
.$conf['top_number'].' '.l10n('Best rated').'</a>', .$conf['top_number'].' '.l10n('Best rated').'</a>',
'items' => array_from_query($query, 'id'), 'items' => query2array($query,null, 'id'),
) )
); );
} }
@ -551,7 +551,7 @@ SELECT DISTINCT(id)
array( array(
'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">' 'title' => '<a href="'.duplicate_index_url(array('start'=>0)).'">'
.l10n('Random photos').'</a>', .l10n('Random photos').'</a>',
'items' => array_from_query($query, 'id'), 'items' => query2array($query,null, 'id'),
) )
); );
} }
@ -632,7 +632,7 @@ if ( 'categories'==$page['section'] and isset($page['category']) )
if ($need_redirect) if ($need_redirect)
{ {
$redirect_url = script_basename()=='picture' ? duplicate_picture_url() : duplicate_index_url(); $redirect_url = script_basename()=='picture' ? duplicate_picture_url() : duplicate_index_url();
if (!headers_sent()) if (!headers_sent())
{ // this is a permanent redirection { // this is a permanent redirection
set_status_header(301); set_status_header(301);