我可以从同一个语句中插入两个不同的表吗?

时间:2013-08-07 10:00:55

标签: php mysql sql

我有一个汽车应用程序,所以汽车有一堆信息可供计算 现在我把这个必需品保存在一张名为auto的桌子上,然后我为attributes制作了一个巨大的桌子 凉。 现在我希望我可以将相同的数组数据插入到同一个pdo下的两个不同的表中

$sql = "INSERT INTO auto(year, make, model, mileage, price, vin, att1, att2,
    att3, att4, picture1, picture2, picture3, picture4, picture5, picture6, picture7, picture8, 
    picture9, picture10, picture11, picture12) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

我可以执行'AND INSERT INTO attributes ('

之类的操作
$sth = $dbh->prepare($sql);
        $final = array_merge(array_values($vehicleinfo),array_values($paths));
        $sth->execute($final);
        echo '<h4 id="successMessage" style="color: red;">Vehicle added succesfully</h4>';

2 个答案:

答案 0 :(得分:2)

在插入第一个表格中添加一个触发器,将其插入第二个表格。

答案 1 :(得分:1)

我很想循环遍历要运行SQL的表;

$tables = array('auto', 'attributes');

foreach($tables as $table) {

    $sql = 'INSERT INTO '.$table.' (year, make, model, mileage, price, vin, att1, att2, att3, att4, picture1, picture2, picture3, picture4, picture5, picture6, picture7, picture8, picture9, picture10, picture11, picture12) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';

    $sth = $dbh->prepare($sql);
    $final = array_merge(array_values($vehicleinfo), array_values($paths));
    $sth->execute($final);

    echo '<h4 id="successMessage" style="color: red;">Vehicle added successfully to '.$table.'</h4>';

}

或者只是创建一个函数,以便您可以将所需的表传递给它;

insertVehicleInfo('auto');
insertVehicleInfo('attributes');

function insertVehicleInfo($table) {

    $sql = 'INSERT INTO '.$table.' (year, make, model, mileage, price, vin, att1, att2, att3, att4, picture1, picture2, picture3, picture4, picture5, picture6, picture7, picture8, picture9, picture10, picture11, picture12) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)';

    $sth = $dbh->prepare($sql);
    $final = array_merge(array_values($vehicleinfo), array_values($paths));
    $sth->execute($final);

    echo '<h4 id="successMessage" style="color: red;">Vehicle added successfully to '.$table.'</h4>';

}