1
$count = count(array_filter($_POST["materials"]));  
for($I = 0; $I < $count; $i++)  
{ 
    $insert = mysqli_query($con, "INSERT INTO table1 (uid, materials, num, cost)
            VALUES
            (
            '$_POST[uid]',
            '$_POST[material][$i]',
            '$_POST[num][$i]',
            '$_POST[cost][$i]',
            )");        
}

If I use echo $_post[materials][$i] it's giving me right result but in database it is inserting something like array[0].

Seems my $insert is not right. But I don't have any idea to insert it. Any ideas on how to do it?

Rubens
  • 14,478
  • 11
  • 63
  • 92

3 Answers3

0

Array to string: implode(',', $_POST[material][$i])

Allen Chak
  • 1,802
  • 1
  • 10
  • 21
0
$sql_template = "INSERT INTO table1 (uid, materials, num, cost)
        VALUES(%d, %s, %s, %s)")";

$insert = mysqli_query($con, "INSERT INTO table1 (uid, materials, num, cost) = 
sprintf($sql_template, $_POST[uid], $_POST[material][$i], $_POST[num][$i], $_POST[cost][$i]);

mysqli_query($con,$insert);

For sprintf more details visit this link for data type and etc.

Vivek Jain
  • 3,811
  • 6
  • 30
  • 47
krishna singh
  • 1,023
  • 1
  • 11
  • 15
-1

You can (and have to) use a pair of curly braces around the expressions, and also quote the array keys:

$insert = mysqli_query($con, "INSERT INTO table1 (uid, materials, num, cost)
            VALUES
            (
            '{$_POST['uid']}',
            '{$_POST['material'][$i]}',
            '{$_POST['num'][$i]}',
            '{$_POST['cost'][$i]}',
            )");

See php.net > Strings

It's because PHP's variable parsing in strings is limited to single-dimension array. For two or more dimensions you need to use the curly braces to indicate PHP the end of the variable. Same applies to accessing arrays with a string key.

You also need to quote the string array keys because they are actual strings, which you should always quote them properly


Also note that the code is fine if it is not production code. However you should be aware that your code opens a big security vulnerability called SQL Injection. If this is more serious work, you should refer to the link and fix the security vulnerability.

Community
  • 1
  • 1
Alvin Wong
  • 12,210
  • 5
  • 51
  • 77