1

我得到了这样的东西。

它可以工作,但是必须执行 40 次 mysql 查询并不是最好的事情。

有人可以帮我解决一个问题吗?

$string_unique  = 'Unique string';

$number = count($something);

for ($i=0; $i < $number; $i++) 
{

if(!empty($some_input)) {       
    $string_one     = 'Something_one' . $i;
    $string_two     = 'Something_two' . $i;

    mysql_query("INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES('$unique_string', '$string_one', '$string_two') ON DUPLICATE KEY UPDATE `string_one` = '$string_one', `string_two` = '$string_two'") or die(mysql_error());
} else {
    $string_one     = '';
    $string_two     = '';

    mysql_query("INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES('$unique_string', '$string_one', '$string_two') ON DUPLICATE KEY UPDATE `string_one` = '$string_one', `string_two` = '$string_two'") or die(mysql_error());

}
4

3 回答 3

1

您可以在该循环中生成单个查询,然后只执行一次:

$query = 'INSERT INTO `table` (`unique_string`, `string_one`, `string_two`) VALUES ';
$queryValues = array();

$string_unique  = 'Unique string';

$number = count($something);

for ($i=0; $i < $number; $i++)
{
    if(!empty($some_input)) {
        $string_one     = 'Something_one' . $i;
        $string_two     = 'Something_two' . $i;

        $queryValues[] = sprintf('("%s", "%s", "%s")', $unique_string, $string_one, $string_two);
    } else {
        // I can't understand what are you using this part for... Anyway.
        $queryValues[] = sprintf('("%s", "", "")', $unique_string);
    }
}

$query .= implode(', ', $queryValues);

// And here is the unique key updating.
// I don't know whole the structure, so I just guess you have the PRIMARY `id` row
// What you did in your ON DUPLICATE KEY was unnecessary.
$query .= ' ON DUPLICATE KEY UPDATE `id`=`id`';

// Don't use mysql_* functions in new code.
// See: http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php
mysql_query($query);
于 2013-06-22T13:16:55.777 回答
0

您可以在 MySQL 的插入语句中添加多行数据。这样,您可以在循环中构建一个大的插入语句,并在循环之后一次性执行它。这样更快,效率更高。

于 2013-06-22T13:04:45.223 回答
0

您可以使用 sql 插入多行,

这是一个例子

insert into table1 (First,Last) values ("Fred","Smith"), ("John","Smith"), ("Michael","Smith"), ("Robert","Smith");

于 2013-06-22T13:11:29.330 回答