如何将switch case中的部分代码放到循环中,使PHP中的代码更短?

oxcyiej7  于 2022-12-10  发布在  PHP
关注(0)|答案(1)|浏览(108)

我在php中有一段代码,我想把它放在循环中,“It is in switch case”,但我不知道怎么做。这真的让我有一个更短的代码。当然,在其他的switch case中,我有更多这样的代码,我可以用你的模式来有一个简短的代码。
有人能帮我吗?

//Preview is the name of the button.
// The reason which I put the switch code is that when ever I take each the numbers it gives me that the column numbers.

(isset($_POST['Preview'])) {
//Prepare and bind

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
    exit;
}
// set parameters and execute
$DataArr = array();
$previewid = "1";
$clientshowid = "0";
$statusid = "0";
$country = $_POST['Sel_Country'];
$commodity = $_POST['Sel_Commodity'];
$no_col = $_POST['no_col'];
$start1 = $_POST['start1'];
$end1 = $_POST['end1'];
$DataArr[]="('$start1','$end1')";

switch ($no_col) {
    case '1':
        $stmt = $conn->prepare("INSERT INTO t3 (previewid, clientshowid, statusid,country,commodity,no_col,start1,end1) VALUES (?,?,?,?,?,?,?,?)");
        $stmt->bind_param("ssssssss", $previewid, $clientshowid, $statusid, $country, $commodity, $no_col, $start1, $end1);
        break;
    case '2':
        $start2 = $_POST['start2'];
        $end2 = $_POST['end2'];
        $stmt = $conn->prepare("INSERT INTO t3 (previewid, clientshowid, statusid,country,commodity,no_col,start1,end1,start2,end2) VALUES (?,?,?,?,?,?,?,?,?,?)");
        $stmt->bind_param("ssssssssss", $previewid, $clientshowid, $statusid, $country, $commodity, $no_col, $start1, $end1, $start2, $end2);
        $DataArr[]="('$start1','$end1','$start2','$end2')";
0qx6xfy6

0qx6xfy61#

startend对从27。因此,在此范围内循环,并在访问数据时将当前的$i连接到键。
不要在下一个foreach中声明这么多变量,而是使用array_map将转义函数应用于其中的每个值,并使用implode将其加上所需的单引号。

case '7':
      for($i = 2, $j = 7; $i <= 7; ++$i){
        $records[0][ $j++ ] = $_POST['start'. $i];
        $records[0][ $j++ ] = $_POST['end'. $i];
      }
      $DataArr = array();
      foreach($records as $row) {
          $row = array_map(fn($val) =>  mysqli_real_escape_string($conn, $val), $row);
          $DataArr[] = "('" . implode("','", $row) . "')";            
      }

**P.S:**正如评论中提到的,使用prepared statements是一个更好的主意。

相关问题