我有一个名为“漫画”的文件夹和该目录中的子文件夹,其中包含漫画+问题的名称
示例:
/Comics <-- Main Folder
/Amazing Spider-Man 129 <-- Sub Folder
/Hellblazer 100 <-- Sub Folder
/Zatanna 01 <-- Sub Folder
现在我要做的是扫描Comics目录并输出每个文件夹名称作为mysql插入查询。实际的文件夹名称需要分为“漫画名称”和“ “漫画问题”。
示例查询
mysql_query("INSERT INTO comics (name, issue) VALUES ('Amazing Spider-Man', '129')");
我到目前为止,现在我想添加一个查询检查以查看漫画是否存在。
<?php
$main_folder = 'K:/Comics/'; // should be K:\Comics\ but I changed it because of the highlighting issue
$folders = glob($main_folder.'* [0-9]*', GLOB_ONLYDIR);
$comics_series = array();
foreach($folders as $folder){
$comics_series[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($comics_series as $pair){
$values[] = "('".mysql_real_escape_string($pair[0])."', '".((int) $pair[1])."')";
}
$check_query = mysql_query("SELECT * FROM comics WHERE name='".$values[0]."' AND issue='".$values[1]."'");
if ($check_query == '0'){
$query = 'INSERT INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
}
?>
是query_check的正确格式吗?
答案 0 :(得分:1)
如果您只是在分割漫画名称加上问题,请查看explode功能
如果您正在努力处理文件/文件夹,我建议您查看glob。这更容易。
<?php
if ($handle = opendir('K:\Comics')) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$comicName = null;
$pieces = explode(' ', $file); // explode the $file
// if the last element is a number..
if(is_numeric(end($pieces))) {
$comicIssue = end($pieces); // set the issue to a variable
array_pop($pieces); // remove the last element of the array
// loop through the rest of the array and put the pieces back together
foreach($pieces as $value) {
$comicName .= " $value"; // append the next array element to $comicName
}
} else {
echo "not issue number";
}
}
}
closedir($handle);
}
&GT?;
答案 1 :(得分:1)
<?php
$main_folder = './Comics'; // should be K:\Comics\ but I changed it because of the highlighting issue
$folders = glob($main_folder.'* [0-9]*', GLOB_ONLYDIR);
$comics_series = array();
foreach($folders as $folder){
$comics_series[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($comics_series as $pair){
$values[] = "('".mysql_real_escape_string($pair[0])."', '".((int) $pair[1])."')";
}
$query = 'INSERT INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>