只有当您解释为什么不可能/非常不推荐时,我才接受sprintf
的替代
(下面的代码)
我想将数组中的动态数据插入到mysql数据库中。我也试着尝试sprintf
,我最近听说过并希望开始使用它。
如何从第二个foreach获取数据并通过sprintf将其存储在查询中?
数组:
############################################################
$csv->titles
############################################################
Array
(
[0] => rating
[1] => title
[2] => author
[3] => type
[4] => asin
[5] => tags
[6] => review
)
############################################################
$csv->data
############################################################
Array
(
[0] => Array
(
[rating] => 0
[title] => The Killing Kind
[author] => John Connolly
[type] => Book
[asin] => 0340771224
[tags] =>
[review] => i still haven't had time to read this one...
)
[1] => Array
(
[rating] => 0
[title] => The Third Secret
[author] => Steve Berry
[type] => Book
[asin] => 0340899263
[tags] =>
[review] => need to find time to read this book
)
...
代码我正在:
$query = "CREATE TABLE IF NOT EXISTS XXX (";
$query .= "ID int(11) NULL AUTO_INCREMENT,";
$query2 = "SELECT * FROM XXX WHERE";
foreach($titlesArray as $keyTitles => $valuesTitles){
$query .= cleanForShortURL($valuesTitles)." varchar(255),";
$query2 .= cleanForShortURL($valuesTitles)." = '%s' AND ";
}
$query2 = substr($query2,0 ,-5);
$query .= " PRIMARY KEY (`ID`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=0 ";
$mysqli->query($query);
foreach($dataArray as $key => $values){
################## PROBLEM HERE ####################
}
我的一次尝试:
foreach($dataArray as $key => $values){
sprintf($query, eval(implode(",",$values)));
}
万一有人问(来自php.net):
function cleanForShortURL($toClean) {
$normalizeChars = array(
'Š'=>'S', 'š'=>'s', 'Ð'=>'Dj','Ž'=>'Z', 'ž'=>'z', 'À'=>'A', 'Á'=>'A', 'Â'=>'A', 'Ã'=>'A', 'Ä'=>'A',
'Å'=>'A', 'Æ'=>'A', 'Ç'=>'C', 'È'=>'E', 'É'=>'E', 'Ê'=>'E', 'Ë'=>'E', 'Ì'=>'I', 'Í'=>'I', 'Î'=>'I',
'Ï'=>'I', 'Ñ'=>'N', 'Ò'=>'O', 'Ó'=>'O', 'Ô'=>'O', 'Õ'=>'O', 'Ö'=>'O', 'Ø'=>'O', 'Ù'=>'U', 'Ú'=>'U',
'Û'=>'U', 'Ü'=>'U', 'Ý'=>'Y', 'Þ'=>'B', 'ß'=>'Ss','à'=>'a', 'á'=>'a', 'â'=>'a', 'ã'=>'a', 'ä'=>'a',
'å'=>'a', 'æ'=>'a', 'ç'=>'c', 'è'=>'e', 'é'=>'e', 'ê'=>'e', 'ë'=>'e', 'ì'=>'i', 'í'=>'i', 'î'=>'i',
'ï'=>'i', 'ð'=>'o', 'ñ'=>'n', 'ò'=>'o', 'ó'=>'o', 'ô'=>'o', 'õ'=>'o', 'ö'=>'o', 'ø'=>'o', 'ù'=>'u',
'ú'=>'u', 'û'=>'u', 'ý'=>'y', 'ý'=>'y', 'þ'=>'b', 'ÿ'=>'y', 'ƒ'=>'f'
);
$toClean = str_replace('&', '-and-', $toClean);
$toClean = trim(preg_replace('/[^\w\d_ -]/si', '', $toClean));//remove all illegal chars
$toClean = str_replace(' ', '_', $toClean);
$toClean = str_replace('--', '-', $toClean);
return strtr($toClean, $normalizeChars);
}
答案 0 :(得分:6)
尽可能避免使用eval。试试vsprintf
:
foreach($dataArray as $key => $values){
vsprintf($query, $values);
}