How to insert the sum of PHP MYSQL variables

0

I have a problem with a code that allows you to insert multiple data from php, and what I need is that for each record the amount of the entered values is inserted in the DB. Code:

//insert.php
$connect = mysqli_connect("localhost", "root", "", "testing");
if(isset($_POST["item_valor1"]))
{
 $item_valor1 = $_POST["item_valor1"];
 $item_valor2 = $_POST["item_valor2"];
 $item_valor3 = $_POST["item_valor3"];
 $item_valor4 = $_POST["item_valor4"];
 $query = '';
 for($count = 0; $count<count($item_valor1); $count++)
 {
  $item_valor1_clean = mysqli_real_escape_string($connect, $item_valor1[$count]);
  $item_valor2_clean = mysqli_real_escape_string($connect, $item_valor2[$count]);
  $item_valor3_clean = mysqli_real_escape_string($connect, $item_valor3[$count]);
  $item_valor4_clean = mysqli_real_escape_string($connect, $item_valor4[$count]);
  if($item_valor1_clean != '' && $item_valor2_clean != '' && $item_valor3_clean != '' && $item_valor4_clean != '')
  {
   $query .= '
   INSERT INTO item(item_valor1, item_valor2, item_valor3, item_valor4) 
   VALUES("'.$item_valor1_clean.'", "'.$item_valor2_clean.'", "'.$item_valor3_clean.'", "'.$item_valor4_clean.'"); 
   ';
  }
 }
 if($query != '')
 {
  if(mysqli_multi_query($connect, $query))
  {
   echo 'Item Data Inserted';
  }
  else
  {
   echo 'Error';
  }
 }
 else
 {
  echo 'All Fields are Required';
 }
}
    
asked by outsider 03.09.2018 в 09:00
source

1 answer

1

You can add what you need in the insert line

$query .= '
   INSERT INTO item(item_valor1, item_valor2, item_valor3, item_valor4, ITEM5) 
   VALUES("'.$item_valor1_clean.'", "'.$item_valor2_clean.'", "'.$item_valor3_clean.'", "'.$item_valor4_clean.'", "'.($item_valor1_clean+$item_valor2_clean+$item_valor3_clean+$item_valor4_clean).'"); 

Although you can also do it directly axis

INSERT INTO tabla SET a='a', b='b'; INSERT INTO tabla SET a='a', b='b';

Just separate them with;

I'll give you an example in PHP if it helps

$link = new PDO('mysql:host='.$host.';dbname='.$dbname, $user, $password);
$link->query("INSERT INTO tabla SET a='a', b='b'; INSERT INTO tabla SET a='a', b='b';");

Greetings:)

    
answered by 03.09.2018 / 09:09
source