html - How can I insert an array of variable into a database individually in php?
Get the solution ↓↓↓How can i insert the array into the database individually, It's displaying error. I want to insert them all at once... sometimes the array may be more the 3, 5 or 10.
$roll_num = '111,222,333';
$rollnum = explode(",",$roll_num);
$sql ="INSERT INTO eyfstb(specialnum) VALUES('$rollnum[]')";
if($db->query($sql)== TRUE){
echo "true";
}else{
echo "false";
}
Answer
Solution:
The explode function converts your array into a multiple index variables, so regarding your question, it should be:
$roll_num = '111,222,333';
$rollnum = explode(",",$roll_num);
$sql ="INSERT INTO eyfstb(specialnum) VALUES('$rollnum[0]')";
if($db->query($sql)== TRUE){
echo "true";
}else{
echo "false";
}
If you want to insert all of them, you could either store it as a JSON in your table, or create additional columns.
Answer
Solution:
Firt of all, your $roll_num variable is not an array. And the explode function will split your string by a string as it said here: https://www.php.net/manual/en/function.explode.php
For that you could build your array whith your values inside like:
$roll_num = array('111', '222','333');
And INSERT INTO thanks to a loop:
for ($i = 0; $i < count($roll_num); $i++) {
$sql = "INSERT INTO eyfstb(specialnum) VALUES(" . $roll_num[$i] . ")";
$db->query($sql);
$db->execute();
}
It should work :)
Answer
Solution:
As I understand you want to insert a new row for each array cell. To do so, I would recommend:
$roll_num = '111,222,333';
$rollnum = explode(",", $roll_num);
$sql = "INSERT INTO eyfstb(specialnum) VALUES('" . implode("'),('", $rollnum) . "')";
That will produce the following SQL:
INSERT INTO eyfstb(specialnum) VALUES('111'),('222'),('333')
And will be more efficient than looping and inserting every iteration.
Answer
Solution:
You can Insert it Dynamically to yourDatabase
and this will fix your problem. :D
$roll_num = '111,222,333';
$rollnum_arr = explode(",",$roll_num);
for($x = 0; $x < count($rollnum_arr); $x++){
$sql ="INSERT INTO eyfstb(specialnum) VALUES(".$rollnum_arr[$x].")";
}
if($db->query($sql) == TRUE){
echo "true";
}else{
echo "false";
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: port 80 in use by "unable to open process" with pid 4!
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.