是可以把它放在循环中吗?

时间:2013-04-07 00:56:34

标签: php loops mysqli

是否有可能将其置于循环中?

if (!empty($_POST["textDE"])) {
    $mysqli = $connect->prepare("INSERT INTO `l10n-strings` (`translationID`, `languageCode`, `text`) VALUES (?, ?, ?)");
    $mysqli->bind_param('iss', $l10id, $languageCodeDE, $textDE);
    $mysqli->execute();
}

if (!empty($_POST["textEN"])) {
    $mysqli = $connect->prepare("INSERT INTO `l10n-strings` (`translationID`, `languageCode`, `text`) VALUES (?, ?, ?)");
    $mysqli->bind_param('iss', $l10id, $languageCodeEN, $textEN);
    $mysqli->execute();
}

if (!empty($_POST["textES"])) {
    $mysqli = $connect->prepare("INSERT INTO `l10n-strings` (`translationID`, `languageCode`, `text`) VALUES (?, ?, ?)");
    $mysqli->bind_param('iss', $l10id, $languageCodeES, $textES);
    $mysqli->execute();
}

if (!empty($_POST["textFR"])) {
    $mysqli = $connect->prepare("INSERT INTO `l10n-strings` (`translationID`, `languageCode`, `text`) VALUES (?, ?, ?)");
    $mysqli->bind_param('iss', $l10id, $languageCodeFR, $textFR);
    $mysqli->execute();
}

if (!empty($_POST["textIT"])) {
    $mysqli = $connect->prepare("INSERT INTO `l10n-strings` (`translationID`, `languageCode`, `text`) VALUES (?, ?, ?)");
    $mysqli->bind_param('iss', $l10id, $languageCodeIT, $textIT);
    $mysqli->execute();
}       

1 个答案:

答案 0 :(得分:2)

$languages = array('DE', 'EN', 'ES', 'FR', 'IT');

foreach ($languages as $lang) {
    $langKey = 'text' . $lang;
    if (!empty($_POST[$langKey])) {
        $mysqli = $connect->prepare(
            "INSERT INTO `l10n-strings` (`translationID`, `languageCode`, `text`) ".
            "VALUES (?, ?, ?)"
        );
        $mysqli->bind_param(
            'iss',
            $l10id,
            ${'languageCode'.$lang},
            ${$langKey}
        );
        $mysqli->execute();
    }
}

Variable variables使用查找数组使这更容易。

同样disable register globals in your PHP configuration,这是一个安全问题。