我有下面的代码,几乎是相同的所有时间(约50次):
if ($product=='product1' || $product=='product1 + extra')
{
mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO downloads (key, file, expires)VALUES ('{$strKey}', 'test.zip', '".(time()+(60*60*24*7))."')");
}
else if ($product=='product2' || $product=='product2 + extra')
{
mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO downloads (key, file, expires)VALUES ('{$strKey}', 'test2.zip', '".(time()+(60*60*24*7))."')");
}
//else if () {}
唯一改变的是产品和文件名(product1, product2, ecc..)+ test.zip, test2.zip,ecc…).
所以我在考虑用产品名和文件名制作两个数组,然后循环这些数组,但我不知道是否可能以及如何正确更改代码。
有谁知道一个好的解决方案吗?谢谢你的帮助,很抱歉我的英语不太好。
编辑
product1, product2, ecc, test1.zip, test2.zip, ecc。只是真实名字的占位符,真实名字在不断变化,而且总是不同的。
product1, product2来自$_POST,该$_POST是通过一些选项从用户中选择的
大致上您需要如下内容…
$count = 50;//This should be set using something such as count() on an object.
$i = 0;
while ($i<$count)
{
if ($product=='product'.$i || $product=='product'.$i.' + extra')
{
$filename1 = strrev($product);
$file = explode('.',$filename,2);
$file_name = mysqli_real_escape_string($GLOBALS["___mysqli_ston"],strrev($file[1]));
$file_ext = mysqli_real_escape_string($GLOBALS["___mysqli_ston"],strrev($file[0]));
mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO downloads (key, file, expires) VALUES ('{$strKey}', $file_name.$i.'.'.$file_ext, '".(time()+(60*60*24*7))."')");
}
$i++;
}
您必须确保您将$count
分配给决定您将处理多少项的东西。还要确保while
循环迭代尽可能多的项目(有些人最终想知道为什么最后一个项目没有被处理)。如果你提供更多的代码,我将能够给你一个更现场的例子,虽然我认为你将能够处理它从这里。确保您在那些INSERT
查询中转义数据,再次您只提供了有限数量的代码,因此您可以是转义,尽管确保代码安全很重要。最后,您可能需要根据您的编号方案将$i
更改为1而不是0。
我找到了自己的解决方案:
$files = array(
'product1' => 'test.zip',
'product2' => 'test2.zip'
//other products and files
);
创建数组之后,创建一个像
这样的循环就足够了foreach($files as $file => $name){
if($product == $file || $product == $file . ' + extra' ){
mysqli_query($GLOBALS["___mysqli_ston"], "INSERT INTO downloads (key, file, expires) VALUES ('{$strKey}', '$name', '".(time()+(60*60*24*7))."')");
}
};