简体   繁体   中英

How to put part of the code in switch case to the loop to make a shorter code in php?

在此处输入图像描述

I have a part of code in php which I want to put it in to loop "It is in switch case" but I don't know how to do it. It really makes me to have a shorter code. Definitely in other items of the switch cases I have more codes like this which I can use your pattern to have a brief code.

Could anyone help me?

//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')";

The start and end pairs go from 2 to 7 . So, loop in this range and concat the current $i to the key while accessing the data.

Instead of declaring so many variables in your next foreach, use array_map to apply your escape function to each value inside it and implode it with the required single quotes.

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) . "')";            
      }

PS: As mentioned in the comments, using prepared statements is a better idea.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM