I have the following array named $people and this is the output I get with a print_r():

Array (

[0] => "Zyzz","fitness","21","Male"

[1] => "Arnold","bodybuilder","23","Male"

[2] => "Jeff","fitness","19","Male"

)

How can I insert these values to my MySQL Database?

I have a vague idea wich is:

$sql=" INSERT INTO famous (name,type,age,sex) VALUES ($people)";

mysql_query($sql);

How can I accomplish this correctly?

Thanks in advance

share|improve this question
2  
are you sure that is your pint_r()???? – Emilio Gort Feb 9 '14 at 6:12

What if you made a foreach loop like

foreach($people as $person)

And then used the $person variable in your query. The foreach will just iterate your array. However, the values of your array don't seem right. Are you sure that is the exact print_r?

share|improve this answer
$sql = "INSERT INTO famous (name,type,age,sex) VALUES ";
foreach($people as $p)
{
$sql .= '('.$p.'),';
}
$sql = rtrim($sql,',');
mysql_query($sql);
share|improve this answer
    
@Brett Zamir Thx correction!! Can u tell me how to make new line in this editor. I just use <br> for new line – Jain Feb 9 '14 at 6:25
    
Hi I think this doesn't work, if I echo the $sql statement I get [...] VALUES ("Zyzz","fitness","21","Male")("Arnold","bodybuilder","23","‌​Male") ("Jeff","fitness","19","Male") – user3288852 Feb 9 '14 at 6:51
    
So it's not a valid query, remember that each "value" goes in a different column – user3288852 Feb 9 '14 at 6:52
    
There is a comma seprator between them check it out – Jain Feb 9 '14 at 8:36
    
VALUES ("Zyzz","fitness","21","Male"),("Arnold","bodybuilder","23",‌​"Male") ,("Jeff","fitness","19","Male") – Jain Feb 9 '14 at 8:37

Just do the following:

foreach($people as &$person) {
    $person = '('.$person.')';
}
$sql = "INSERT INTO famous (name,type,age,sex) VALUES " . implode (",", $people);
mysql_query($sql);
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.