-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?

6
  • Your for loop syntax is wrong Commented May 2, 2018 at 8:04
  • Not only is this an under-researched duplicate. Your query is vulnerable to injection attacks. Keep researching. Commented May 2, 2018 at 8:04
  • Danger: You are vulnerable to SQL injection attacks that you need to defend yourself from. Commented May 2, 2018 at 8:04
  • Possible duplicate of Insert rows from two arrays into mysql table in php ...this is just one of MANY. Commented May 2, 2018 at 8: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. Commented May 2, 2018 at 8:10

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

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')");
 }
 ?>

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.