-1

I have this arrays of firstname and lastname, i want to insert the names into the database, the arrays looks like this:

Array(
[0] => firstname1
[1] => firstname2
[2] => firstname3
)

Array(
[0] => lastname1
[1] => lastname2
[2] => lastname3
)

I have this code to insert them but it does'nt work

         $fname = $_POST['fname'];
         $lname = $_POST['lname'];

         for($i=0, $count = count($fname); $i < $count; $i++){
         $lastname = $lname[$i];
          $firstname = $fname[$i];
         $query = mysqli_query($con,"INSERT INTO 
       persons(firstname,lastname)VALUES('$firstname','$lastname')");
    }

Printing the strings in the array is not a prolem, but when i insert it an error saying Notice: Array to string conversion in D:\xampp\htdocs\SPAC_Online_Grading_System\system\pages\addfunction.php on line 259 How can i make it work?

Rouge
  • 23
  • 5
  • Your for loop syntax is wrong – Marko Paju May 02 '18 at 08:04
  • Not only is this an under-researched duplicate. Your query is vulnerable to injection attacks. Keep researching. – mickmackusa May 02 '18 at 08:04
  • **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin May 02 '18 at 08:04
  • Possible duplicate of [Insert rows from two arrays into mysql table in php](https://stackoverflow.com/questions/26732231/insert-rows-from-two-arrays-into-mysql-table-in-php) ...this is just one of **MANY**. – mickmackusa May 02 '18 at 08:07
  • Sorry if it seems to you that it is under-researched duplicate, but asking questions here is really my last option,hehe Yeah, its vulnerable but i'm not concerned about that right now, I just want to insert these things. – Rouge May 02 '18 at 08:10
  • I foresee trouble when you insert `Mr. O'Connor`. – mickmackusa May 02 '18 at 08:10

3 Answers3

0

Your loop condition is wrong, change :

for($i=0, $count = count($fname); $i < $count; $i++)

To :

for($i=0; $i < count($fname); $i++)

Also note that you are vulnerable to SQL injections, you should prepare and bind your statements

Sébastien S.
  • 1,444
  • 8
  • 14
0

You loop is wrong. Try this code:

 <?php 
 $fname = $_POST['fname'];
 $lname = $_POST['lname'];

 for($i=0; $i < count($fname); $i++){

   $firstname = $fname[$i];
   $lastname = $lname[$i];

   $query = mysqli_query($con,"INSERT INTO 
      persons(firstname,lastname)VALUES('$firstname','$lastname')");
 }
 ?>
0
    for($i=0; $i<count($fname);$i++){
        $lastname = $lname[$i];
        $firstname = $fname[$i];
        $stmt = $conn->prepare($con,"INSERT INTO persons(firstname,lastname)VALUES(?,?)");
        $stmt->bind_param("ss", $firstname, $lastname);
        $stmt->execute();
    }

Try this code. It is secure from sql injection(using prepare statements) and fixed your for loop.

pr1nc3
  • 8,108
  • 3
  • 23
  • 36