0

I have been trying to insert data into a table(mySql) from 3 arrays using php. Each time i run the script i get a long list on unsuccesful entries. I am new to php and sql, what am i doing wrong here ? how do i get the query string to recognize these variables ? i have tried searching around but could not make sense of much.

$id=array();
$comp=array();
$mobname=array();

for($x=0;$x<$arrlength;$x++)
{

  if(mysqli_query($con,"INSERT INTO Umobile VALUES ($id[$x],$comp[$x],$mobname[$x])"))
     echo "added",$id[$x]," ",$comp[$x]," ",$mobname[$x];
  else
     echo " unsuccessful ";

    //echo $id[$x]," ",$comp[$x]," ",$mobname[$x];
   echo "<br/>";  
 }
4
  • By looking above code i assume that you are trying to put an empty array of id,com,mobname variables thats why its giving error. Do you have values in id,comp,mobname arrays ?? or they are just empty like above?? Commented May 6, 2013 at 13:17
  • or another thing is try changing your query function call to this one: mysqli_query($con,"INSERT INTO Umobile VALUES ({$id[$x]},{$comp[$x]},{$mobname[$x]})") Commented May 6, 2013 at 13:22
  • and if any field in above query you have is string type in DB then try putting single quote ' arround that variable as well. Commented May 6, 2013 at 13:23
  • Yes, They all have values, infact they have quite a few values in them. I tried using the curly braces but that didn't help and one of them is type integer and the other two are varchars. so single quote won't work Commented May 6, 2013 at 14:06

1 Answer 1

2

By using this kind of arrays, you assume that your three arrays have the same lengths: $arrlength.

If this statement is true, you could have special characters into your arrays and the query may fail.

You must see at mysqli prepare to escape your values before the insert.

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

2 Comments

yes, they are all the same length as each array takes values from the same number of rows. I'm not aware of the mysqli prepare method.
You can also use mysqli_real_escape_string like that: $idInsert = mysqli_real_escape_string($id[x]); $compInsert = mysqli_real_escape_string($comp[x]); $mobnameInsert = mysqli_real_escape_string($mobname[x]); mysqli_query($con,"INSERT INTO Umobile VALUES ($idInsert,$compInsert,$mobnameInsert)"

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.