PHP: Insert array data into MySQL Database - php

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);

Related

Insert array to to single MySQL raw with foreach

I need to insert MySQL data from array values to a single raw. I have tried code below but I am getting error: Warning: implode(): Invalid arguments passed in
How can I solve this problem? Or is there any alternative way to insert array values to single raw in MySQL using PHP?
<?php
foreach ($_POST['qty'] as $product_id => $qty) {
$product_id = implode(" ",$product_id);
$qty = implode(" ",$qty);
}
$q = mysqli_query($conn, "INSERT INTO product_order (product_id,qty) VALUES ('$product_id','$qty')");
?>
Implode function second parameters accept Array so at first check in implode function the second parameter is array.
foreach ($_POST['qty'] as $product_id => $qty)
This line says $product_id is key which is not array so implode function should not work.
Please provide $_POST['qty'] dump
Try this:
<?php
$product = [];
$qtys = [];
if(!empty($_POST['qty'])){
foreach ($_POST['qty'] as $product_id => $qty) {
array_push($product, $product_id);
array_push($qtys, $qty);
}
$qty_final = implode(',',$qtys);
$product_id_final = implode(',',$product);
$q = mysqli_query($conn, "INSERT INTO product_order (product_id,qty) VALUES ('$product_id_final','$qty_final')");
}
It is very bad idea to save comma separated values in db.
This is not a good idea. - It is a very bad idea.
That being said. Your $product_id is not an array - it is an array key (string or integer) so there is nothing to implode.
Instead of inserting csv into this table it would be a much better idea to insert new row for each id you have.
try this :
<?php
$product_data = isset(($_POST['qty'])? ($_POST['qty']: array();
if ( !empty($product_data) ){
$sql = "INSERT INTO product_order (product_id, qty) VALUES ('".implode(", ", array_keys($product_data))."','".implode(", ", array_values($product_data))."')";
$q = mysqli_query($conn, $sql);
}
?>
If you want to post array to database then use php serialize function.It is best for array type data
$serialized_data = serialize(array('Math', 'Language', 'Science'));
echo $serialized_data . '<br>';
You could do,
<?php
$product_data = isset(($_POST['qty'])? ($_POST['qty']: array();
if ( !empty($product_data) ){
$sql = "INSERT INTO product_order (product_id, qty) VALUES ('".implode(", ", array_keys($product_data))."','".implode(", ", array_values($product_data))."')";
$q = mysqli_query($conn, $sql);
}
?>
This should work.
But keeping comma seperated list in a field is not a good thing to do. You could have a new table, so that you can keep a mapping to what products are in what order.

How to return an entire column as an array using PHP

I am trying to fetch a column from a database and display the entire contents as an array. I have so far been able to fetch only one of the entries from the table. I understand that I am fetching only $row[0] which is why i am getting only 1 element. I have tried to fetch all elements but I have not succeeded yet. can someone please let me know how to do it correctly? I have attached my code below.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT `current` FROM `monitor` ORDER BY `Sno.`";
$result = mysqli_query($con,$sql);
$row = mysqli_fetch_array($result,MYSQLI_NUM);
printf("%s\n",$row[0]);
mysqli_close($con)
?>
PDO has a dedicated feature for your problem PDOStatement::fetchColumn.
So, from your question what I understand is- you want to fetch a database column and store this in a array which will make you to display the results.
<?php
$con=mysqli_connect("localhost","root","raspberry","users");
if (mysqli_connect_errno())
{
echo "failled to connect:".mysqli_connect_error();
}
$sql = "SELECT current FROM monitor ORDER BY Sno";
$result = mysqli_query($con,$sql);
$arr = array();
while ($row = mysqli_fetch_array($result)) {
$arr2 = array();
foreach ($row as $val) $arr2[] = $val;
$arr[] = $arr2;
}
$first_col = array_column($arr, 0);
print_r($first_col);
mysqli_close($con)
?>
i.e. if you have five entry to the database whose first column contains
the values like 'current1', 'current2', 'current3', 'current3' and 'current4' the result of this code will be
Array
(
[0] => current1
[1] => current2
[2] => current3
[3] => current4
[4] => current5
)

Insert array to mysqldb

I'm trying to insert the following array ( from a html form ) but i believe i'm working with this array in a very awful way
The array:
Array (
[0] => Array (
[0] => local
[1] => file
[2] => a
)
[1] => Array (
[0] => remote
[1] => image
[2] => b
)
)
Actual code:
<?php
if(isset($_POST)==true && empty($_POST)==false){
$dataa = ($_POST['code_list']);
}
$data = array_chunk($_POST['code_list'],6);
foreach ($data as $type=>$ba) {
echo "INSERT INTO table(f1, f2, f3,) values (";
foreach ($ba as $a) {
echo "'$a',";
}
echo ");<br>";
}
?>
current output:
INSERT INTO table(f1, f2, f3,) values ('local','file','a',);
INSERT INTO table(f1, f2, f3,) values ('remote','image','b',);
What would be a decent way to do it?
EDIT : No need to show how to connect to a database, i just need to deal with the array data.
A few comments:
You should switch to PDO or mysqli and use prepared statements with bound variables. Now you have a serious sql injection problem;
You can combine multiple inserts in one insert statement: INSERT ... VALUES ('local','file','a'),('remote','image','b'),(etc.).You could also prepare your statement once and then execute it multiple times but combining would be more efficient, especially with a growing number of inserts.
A simple (uncomplete and untested...) example in PDO:
$sql = 'INSERT INTO table(f1, f2, f3) VALUES ';
$values = array();
$valCount = 1;
foreach ($data as $type=>$ba) {
$row = array();
foreach ($ba as $a) {
$val = ":value{$valCount}";
$row[] = $val;
$values[$val] = $a;
$valCount++;
}
$sql .= '(' . implode(', ', $row) . '),';
}
$sql = rtrim($slq, ',');
// execute the sql statement using PDO
$stmt = $db->prepare($sql);
$stmt->execute($values);
At the end of the loop and the trim, the sql should look like:
INSERT INTO table(f1, f2, f3) VALUES (:value1, :value2, :value3),(:value4, :value5, :value6)
And the value array should have the keys of :value1 - :value6 with your values.

Array into mysql row

Hello i have a dynamic form that can change field names upon user selection. i would like for the form result to be inserted into one mysql row.. i create an array as follows:
<?php
include_once 'dbconnect.php';
if (isset($_POST['item_name'])) {
$table = $_POST['ItemTypeSelect'];
foreach ($_POST as $key => $variable) {
$chesckColumn = mysql_query("SELECT `$key` from $table");
if (!$chesckColumn) {
echo "column ".$key." does not exist <br/>";
}else{
$results = $variable;
$columnName = $key;
$array[] = array($columnName => $results);
}
}
mysql_query("INSERT INTO $table (`$columnName`) VALUES ('$results') ")or die(mysql_error());
}
?>
my array result are
(
[0] => Array
(
[Server_id] =>
)
[1] => Array
(
[Server_IP_Address] => 12345
)
[2] => Array
(
[Server_IP] => 12345
)
[3] => Array
(
[Server_Name] => dad
)
)
How can i have the array be inserted in one table row and reference the $results and the field value and $columnName as the field value.
You could use a few php built in functions:
function put_quotes(&$item){
$item = "'$item'";
}
$columns = implode(",",array_walk(array_keys($_POST),'put_quotes'));
$values = implode(",",array_walk(array_values($_POST),'put_quotes'));
mysql_query("INSERT INTO $table (columns) VALUES ($values) ")or die(mysql_error());
Where :
array_walk executes a function over all array, here put quotes over the item.
array_keys gets the keys from an array
array_values gets the values from an array
implode joins an array to a string with a separator
Use PDO because mysql_* functions are depreceated.
Connect to MySQL in PDO :
$db="database";
$host="127.0.0.1";
$usr="username";
$pass="password";
$dbh=new PDO("mysql:dbname=$db;host=$host", $usr, $pass);
First convert the array to JSON and save it on the table :
$json=json_encode($array);
$sql=$dbh->prepare("INSERT INTO ? (?) VALUES (?)");
$sql->execute(array($table,$columnName,$json));
If you want to retrieve the array back, decode the JSON data got from table:
$sql=$dbh->prepare("SELECT ? FROM ?");
$sql->execute(array($columnName,$table));
while($r=$sql->fetch()){
$array=json_decode($r[$columnName],true);
print_r($array);
}

Inserting an array into different rows in database

I'm having an issue inserting an array into my database. When i tried implode, it all inserted all the arrays into one row. What i intend to achieve is to insert a single array into different rows.
In the array i have fields such as bag,shoes,cloths and i wish to insert into one table but different rows.
$subjectArray[] =$_POST['subject'];
$all_subjects_to_insert = array();
foreach ($subjectArray as $p){
if(!empty($p)) $all_subjects_to_insert = $p;
}
$all_subjects_to_insert = array_unique($all_subjects_to_insert);
$final = implode(',',$all_subjects_to_insert);
$query = "INSERT INTO #__sch_subject (subject) VALUES ('$final')";
I'll appreciate any help i get. Thanks.
if $all_subjects_to_insert is multidimensional array then what you are looking for is
foreach($all_subjects_to_insert as $value)
{
$query = "INSERT INTO #__sch_subject (subject) VALUES ('{$value}')";
mysql_query($query);
}
Reference
Thanks everyone. Its now working. The separator for the implode function was incorrect. Here is the working code
$subjectArray[] =$_POST['subject'];
$all_subjects_to_insert = array();
foreach ($subjectArray as $p){
if(!empty($p)) $all_subjects_to_insert = $p;
}
$all_subjects_to_insert = array_unique($all_subjects_to_insert);
$inserted_values = implode("'),('",$all_subjects_to_insert);
print_r($finalvalues);
$query = "INSERT INTO #__sch_subject (subject) VALUES ('$inserted_values')";
With the separator the insert command looks like this
$query ="INSERT INTO #__sch_subject (Subject) VALUES ('a'),('b'),('c')";
Thanks for the help. I really appreciate.

Categories