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
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?
$sql = "INSERT INTO famous (name,type,age,sex) VALUES ";
foreach($people as $p)
{
$sql .= '('.$p.'),';
}
$sql = rtrim($sql,',');
mysql_query($sql);
Just do the following:
foreach($people as &$person) {
$person = '('.$person.')';
}
$sql = "INSERT INTO famous (name,type,age,sex) VALUES " . implode (",", $people);
mysql_query($sql);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.