gpt4 book ai didi

php - 这些字符串的正确检查语法是什么?

转载 作者:行者123 更新时间:2023-11-29 04:55:48 25 4
gpt4 key购买 nike

我正在编写一个脚本来检查文件夹 K:/Comics 并将每个名称 + 数字插入数据库,表名 = comics。现在我想做的是在运行插入查询之前检查这部漫画是否已经存在。

表结构:

CREATE TABLE IF NOT EXISTS `comics` (
`id` int(100) NOT NULL AUTO_INCREMENT,
`name` varchar(255) NOT NULL,
`issue` varchar(4) DEFAULT NULL,
`bio` longtext NOT NULL,
`pages` int(10) NOT NULL,
`size` varchar(100) NOT NULL,
`price` varchar(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 ;

代码:

<?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])."')";
}

$query = 'INSERT IGNORE INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>

我认为行得通但行不通的方法(仍然将漫画添加到已经存在的数据库中):

$query = 'INSERT IGNORE INTO comics (name, issue) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';

我忘记了什么?!?文档说只需在其中添加 IGNORE 就可以了...

最佳答案

<?php
$main_folder = 'K:/Comics/';
$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){
// clean the values to protect against SQL injection
$pair = array(
mysql_real_escape_string($pair[0]),
mysql_real_escape_string($pair[1])
);
// add it to the values array, for insert
$values[] = "('".$pair[0]."', '".$pair[1]."')";
}

$query = 'INSERT INTO comics (name, issue) VALUES '.implode(',', $values).' '.
'ON DUPLICATE KEY UPDATE `issue` = VALUES(`issue`)';
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>

关于php - 这些字符串的正确检查语法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6697145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com