使用MySQL将多行插入数据库

时间:2012-10-12 12:34:17

标签: php mysql pdo

我有以下代码,在数据库中插入1行:

public function fixed($fieldDay, $fieldNight) {

    $pdo = new SQL();
    $dbh = $pdo->connect(Database::$serverIP, Database::$serverPort, Database::$dbName, Database::$user, Database::$pass);

    $this->sql = "INSERT INTO tblfixedfare (SELECT NULL, MAX(FixedFareID)+1, '1', '$fieldDay' FROM tblfixedfare)";

try {
        // Query
        $stmt = $dbh->prepare($this->sql);

        $stmt->execute();

        $count = $stmt->rowCount();

        echo $count.' row(s) inserted by SQL: '.$stmt->queryString;

        $stmt->closeCursor();

    }

    catch (PDOException $pe) {
        echo 'Error: ' .$pe->getMessage(). 'SQL: '.$stmt->queryString;
        die();
    }

    // Close connection
    $dbh = null;
}

}

在执行此操作的同时,我想在同一个表中插入另一行:

$this->sql = "INSERT INTO tblfixedfare (SELECT NULL, MAX(FixedFareID)+1, '2', '$fieldNight' FROM tblfixedfare)";

我将如何做到这一点?

修改

此外,对于两个插入,MAX(FixedFareID)+1的值必须是相同的值。

1 个答案:

答案 0 :(得分:3)

将SQL查询定义更改为:

$this->sql = "
    INSERT INTO tblfixedfare 
        SELECT NULL, MAX(FixedFareID) + 1, '1', :fieldDay
        FROM tblfixedfare
        UNION
        SELECT NULL, MAX(FixedFareID) + 1, '2', :fieldNight
        FROM tblfixedfare
";

...并将execute()调用更改为:

$stmt->execute(array(
    'fieldDay' => $fieldDay,
    'fieldNight' => $fieldNight
));