Hello! Help solve the problem. As I understand it, it is fairly simple, but I'm only trying to figure out PHP.

The essence of the question / task: I have input fields in the form, which, depending on the conditions, can be up to 30. And they may not all be filled (i.e. 1-12, 14,15 with entries 13, 16 without , then again with records, etc.).

I process each field as follows:

// если заполнена первая кнопка if ($_POST['BT1_pair']) { if ( $_POST['distribution_board'] == 'ШР') $_POST['BT1_distribution'] = 'Р'.$_POST['BT1_distribution']; else if ( $_POST['distribution_board'] == 'MJ21V00' || $_POST['distribution_board'] == 'MJ22V00' || $_POST['distribution_board'] = 'MJ23V00' ) { $_POST['BT1_distribution'] = 'ПК'.$_POST['BT1_distribution']; } // добавляем к индексу № $_POST['distribution_board'] = $_POST['block'].''.$_POST['distribution_board']; //$_POST['code_connections'] = $_POST['btn_two_index'].'.'.$_POST['btn_two'].':'.$_POST['btn_one_index'].'.'.$_POST['btn_one']; // формируем шифр $_POST['code_btn'] = $_POST['distribution_board'].'.'.$_POST['BT1_distribution'].'.'.$_POST['BT1_pair']; //делаем запись в базу mysqli_query($CONNECT, "INSERT INTO `GGS_btn` VALUES ('', '$_POST[index]', '1', '$_POST[distribution_board]', '$_POST[BT1_distribution]', '$_POST[BT1_pair]', '$_POST[code_btn]' )"); } 

So far I have written only for one button, but I understand that it is possible to make a cycle and to BT (BT1) increase the number to 30 and thus process all the fields. But until he could realize it, there is not enough knowledge ...

I would be extremely grateful for the help in the implementation of the task!

  • For each field will be the same check? - Kernel Panic
  • Well, for($i=1;$i<=30;$i++) { if ($_POST['BT'.$i.'_pair']) ... } In general, fields in the form would BT_pair[0], BT_pair[1] , etc. And would you have at the entrance of the finished array - Mike
  • @KernelPanic yes, the same. - Vasily UK
  • @Mike take it back. Your option more than suits me! So he assumed that everything should be extremely simple. The only thing that even fails is to stick together this line VALUES ('', '$_POST[index]', '$i', '$_POST[distribution_board]', '$_POST[BT1_distribution]', '$_POST[BT1_pair]', '$_POST[code_btn]' )"); - Vasily UK
  • Basil, about SQL injection heard? - Ipatiev

2 answers 2

Never substitute variable values ​​directly into the query text. It is necessary to use a binding of variables. In addition, it is more efficient to prepare a query once and then call it several times inside the loop. Thus, we avoid the compilation stage of each query in the database.

With that said, it might look something like this:

 // Подготавливаем запрос. Вместо переменных ставим знаки "?" $stmt = mysqli_prepare($CONNECT, "INSERT INTO `GGS_btn` VALUES ('', ?, ?, ?, ?, ?, ?)"); if(! $stmt) { обработка ошибки создания запроса } // Привязываем переменные (в порядке следования "?" в запросе) // Буквы в первой строке - типы параметров 's'-строка, 'i' - integer $stmt->bind_param("sissss",$_POST['index'], $i, $dboard, $dist, $pair, $cbtn); // Заполняем фиксированные параметры $dboard = $_POST['block'].''.$_POST['distribution_board']; for($i=1; $i<=30; $i++) { if ($_POST['BT'.$i.'_pair']) { if ( $_POST['distribution_board'] == 'ШР') $dist = 'Р'.$_POST['BT'.$i.'_distribution']; else if ( $_POST['distribution_board'] == 'MJ21V00' || $_POST['distribution_board'] == 'MJ22V00' || $_POST['distribution_board'] = 'MJ23V00' ) { $dist = 'ПК'.$_POST['BT'.$i.'_distribution']; } else { $dist=$_POST['BT'.$i.'_distribution']; } // формируем шифр $cbtn = $_POST['distribution_board'].'.'.$_POST['BT'.$i.'_distribution'].'.'.$_POST['BT'.$i.'_pair']; $pair = $_POST['BT'.$i.'_pair']; // Выполняем запрос. // Будут использованы текущие значения из переменных, привязанных перед циклом. if( ! $stmt->execute() ) { обработка ошибки вставки } } } $stmt->close(); 

I also highly recommend always listing the column names in INSERT INTO GGS_btn(col1, col2, ...) VALUES(..) . First of all, you immediately see in the code which variable in which column you actually insert into which column. Do not check with the structure of the table each time reading the code. Secondly, when changing the structure of the table, you will not have difficult errors caught throughout the application.

As for the form fields, you'd better call them like <input ... name='BT_pair[1]'> , then in the code you can use much readable $_POST['BT_pair'][1] .

  • Thank!! But I do not write this option to the database, although there are no errors. - Vasily UK
  • I did this: for( $i=1; $i<=30; $i++ ) { if ($_POST['BT'.$i.'_pair']) { if ( $_POST['distribution_board'] == 'ШР') $_POST['BT'.$i.'_distribution'] = 'Р'.$_POST['BT'.$i.'_distribution']; // присваиваем значения переменным $pair = $_POST['BT'.$i.'_pair']; $distribution = $_POST['BT'.$i.'_distribution']; // делаем запись в базу mysqli_query($CONNECT, "INSERT INTO for( $i=1; $i<=30; $i++ ) { if ($_POST['BT'.$i.'_pair']) { if ( $_POST['distribution_board'] == 'ШР') $_POST['BT'.$i.'_distribution'] = 'Р'.$_POST['BT'.$i.'_distribution']; // присваиваем значения переменным $pair = $_POST['BT'.$i.'_pair']; $distribution = $_POST['BT'.$i.'_distribution']; // делаем запись в базу mysqli_query($CONNECT, "INSERT INTO for( $i=1; $i<=30; $i++ ) { if ($_POST['BT'.$i.'_pair']) { if ( $_POST['distribution_board'] == 'ШР') $_POST['BT'.$i.'_distribution'] = 'Р'.$_POST['BT'.$i.'_distribution']; // присваиваем значения переменным $pair = $_POST['BT'.$i.'_pair']; $distribution = $_POST['BT'.$i.'_distribution']; // делаем запись в базу mysqli_query($CONNECT, "INSERT INTO GGS_btn` VALUES ('', '$ _POST [index]', '$ i', '$ _POST [distribution_board]', '$ distribution', '$ pair ',' $ _POST [code_btn] ') "); }} `The code is shortened to fit into the comment. - Vasily UK
  • @VasilyUK Check for more errors when bind_param, maybe your column types do not match there (number-line) (the letters 's' are lines, they should also be the same as "?"). I see you still have the $ i variable in the request passed. Did you put the corresponding letter 'i' in bind? I checked something similar before publication, I inserted it normally. It should learn to work with bind_param. For it will be easier to base and SQL injections will be excluded. - Mike
  • Yes, my friends said that this is easier. But somehow there is little information, lessons on bind_param ... The number s is the same, i set. Yes, and did not put it either, just otherwise it should write "1", but should be "i", that is, the corresponding number of the button (input fields in the form). Most likely, I need to delve into the bind and deal specifically with this query. Thank!! - Vasily UK
  • @VasilyUK I corrected the example given $ i in the query. Practice on cats. make a test plate with multiple columns. and a simple script, as in the examples for bind_param, (it is better to run from the console, so as not to miss errors). php.net/manual/ru/mysqli-stmt.bind-param.php - Mike
 $keys = preg_grep("/BT[0-9]+_pair/",array_keys($_POST)); foreach($keys as $key){ $value = $_POST[$key]; ..... }