Member 13411181 Ответов: 1

Как включить запрос insert внутри цикла for с помощью PHP mysql


User will enter like more than one payment card 1.00,cash 2.00,card 10,00,cash 20.00 etc...After these all values insert into payment_details table one by one along with current date.So after this i need to insert data to another table called moneybox table.
Count of total cash and total card will store into money box group by current date.

payment table looks like

    card 1.00 2018-10-18
    cash 2.00 2018-10-18
    card 10.00 2018-10-18
    cash 20.00 2018-10-18

insert record into "moneybox" table like (only two rows) 

    cash  11.00 2018-10-18 // all cash sum value 11 of 2018-10-18
    card  22.00 2018-10-18 // all card sum value 22 of 2018-10-18
    cash  200.00 2018-10-19
    card  370.00 2018-10-19

always two rows ie; card and cash will be there in money table,going to total of cash and card will be store based on current date.

Now the problem,if user enter more than one payment mode like card:10.00 cash:10.00 card:30:00 cash:20:00.Now inserting to moneybox is happening but card 10.00 only adding.When inserting more than one payment,count all cash amount and all card amount will store in moenybox table.
how to solve this issue?


Что я уже пробовал:

Here is my php code for inserting and updating

    $todayDate = date("Y-m-d");
        // flag to check whether inserted for today
    $cashMode = 0; 
    $cardMode = 0;
	
    for ($count = 0; $count < count($getamount); $count++) {
        $payamt_clean          = $getamount[$count];
        $getstorepaymode_clean = $getstorepaymode[$count];
        date_default_timezone_set('Asia/Dubai');
        $created = date("y-m-d H:i:s");    
        
        $query .= 'INSERT INTO payment_details (invoiceID,paymentMode,Amount,created)
                        VALUES ("' . $getinvoiceid . '" , "' . $getstorepaymode_clean . '", "' . $payamt_clean . '", "' . $created . '");
    ';
	
	if($last_moneybox_created_date != $todayDate)   {
                $cashMode = 0;
                $cardMode = 0;
     } 
			
	$cal_closingbalancecash = $last_moneybox_closingbalanacecash - $payamt_clean;
    $cal_closingbalancecard = $last_moneybox_closingbalanacecard - $payamt_clean;
	
    
	
	if($getstorepaymode_clean === "cash" && $cashMode === 0 && $last_moneybox_created_date != $todayDate) {
                echo 'Different Date'; //insert happen based on the type
                $last_moneybox_created_date = $todayDate;
				

                $query .= "INSERT INTO moneybox (type,inflow,date) 
                 VALUES ('cash','$payamt_clean','$todayDate');";   

				$query .= "INSERT INTO moneybox (type,inflow,date) 
                 VALUES ('bank','0.00','$todayDate');"; 
            }
            else if($getstorepaymode_clean === "cash" && $cashMode === 1 && $last_moneybox_created_date == $todayDate) {
                //echo 'Same Date'; //update happen based on type and date
                $query .= "UPDATE moneybox SET 
                        inflow = inflow + $payamt_clean, 
                        closing_balance= opening_balance + inflow - outflow 
                        WHERE type = '$getstorepaymode_clean' and date = '$todayDate';";                                           
            }

		
	if($getstorepaymode_clean === "card" && $cardMode === 0 && $last_moneybox_created_date != $todayDate) {
                echo 'Different Date'; //insert happen based on the type
                $last_moneybox_created_date = $todayDate;

					
				$query .= "INSERT INTO moneybox (type,inflow,date) 
                 VALUES ('cash','0.00','$todayDate');";     
				 
                $query .= "INSERT INTO moneybox (type,inflow,date) 
                 VALUES ('bank','$payamt_clean','$todayDate');";                      
            }
            else if($getstorepaymode_clean === "card" && $cardMode === 1 && $last_moneybox_created_date == $todayDate) {
                //echo 'Same Date'; //update happen based on type and date
                $query .= "UPDATE moneybox SET 
                        inflow = inflow + $payamt_clean, 
                        closing_balance= opening_balance + inflow - outflow 
                        WHERE type = '$getstorepaymode_clean' and date = '$todayDate';";                                           
			}
    }

1 Ответов

Рейтинг:
1

Patrice T

$query .= 'INSERT INTO payment_details (invoiceID,paymentMode,Amount,created)
                        VALUES ("' . $getinvoiceid . '" , "' . $getstorepaymode_clean . '", "' . $payamt_clean . '", "' . $created . '");

Никогда не создавайте SQL-запрос путем объединения строк. Рано или поздно вы сделаете это с помощью пользовательских вводов, и это откроет дверь к уязвимости под названием "SQL-инъекция", она опасна для вашей базы данных и подвержена ошибкам.
Одна кавычка в имени - и ваша программа выйдет из строя. Если пользователь вводит имя, например "Брайан О'Коннер", может привести к сбою вашего приложения, это уязвимость SQL-инъекции, и сбой-это наименьшая из проблем, вредоносный пользовательский ввод, и он продвигается к командам SQL со всеми учетными данными.
SQL-инъекция - Википедия[^]
SQL-инъекция[^]
Атаки SQL-инъекций на примере[^]
PHP: SQL-инъекция - руководство пользователя[^]
Шпаргалка по предотвращению инъекций SQL - OWASP[^]
Как я могу объяснить SQL-инъекцию без технического жаргона? - Обмен Стеками Информационной Безопасности[^]