Insert array to mysqldb - php

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.

Related

PHP SQL statement using REGEXP to fetch multiple values

How do I use REGEXP to fetch multiple data from the array $vall.
I referred a sample code from:
PHP sql statement where clause to multiple array values
Some of the sample data: CGCG-0025-0,CGCR-0003-0,CGRQ-0163-0
foreach ($list as $value) // this $list is from another array
{
$part = $value[3];
$vall[] = $value[3]; // $list1 is an empty array
}
$partnumber =[];
foreach($vall as $v)
{
$partnumber[] = "*.".$v.".*";
print_r(array_values($partnumber)); // these are some of the values Array ( [0] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* ) Array ( [0] => *.CGCG-0025-0.* [1] => *.CGCG-0025-0.* [2] => *.CGCR-0003-0.* )
}
foreach($partnumber as $x)
{
echo '<br>'.$partnumber; // shows 'Array' on each lines
}
$fsql="select * from Error where RptDatime = 201706091000 and partnumber REGEXP '".implode("|",$partnumber)."'";
//example 1 $fsql="select * from MPdError where RptDatime = 201706091000 and partnumber = ('CGRQ-0057-0') ";
//example 1 shows the correct data but i need multiple partnumber
$getResults = $conn->prepare($fsql);
$getResults->execute();
$results = $getResults->fetchAll(PDO::FETCH_BOTH);
foreach($results as $row)
{
$mac = $row['Machine'];
$id = $row['Id'];
echo '<br><br><br>ID:'.$id.'<br>Machine Number :'.$mac;
}
Though this may not be a good solution as it contains a huge security risk, I will still post it based on what is needed above.
REGEXP is not needed for data that are not complex in design.
$fsql = "select * from Error where RptDatime = 201706091000 and partnumber in ('" . implode("','", $vall) . "');"

PHP repeating SQL queries for each array's item efficiently

What's the best way to run SQL query for each item in an array?
I've got the $array of codes:
Array
(
[0] => 12345
[1] => 12346
[3] => 12347
)
Now I'd like to run the following SQL query for each item in the $array:
SELECT * FROM `TABLE` a WHERE a.`Code` = :code
PHP I've been using:
$results = array();
$statement = $pdo->prepare($sql);
$statement->bindParam(':code', $value);
foreach ($array as $key => $value) {
$statement->execute();
while (($results = $statement->fetch(PDO::FETCH_ASSOC)) !== false) {
echo $results;
}
}
Rather than running multiple queries, you could run one query and then loop over the results:
SELECT * FROM `TABLE` a WHERE a.`Code` IN (:codes);
Which would be something along these lines in your PHP:
$question_marks = str_repeat("?,", count($array_of_codes)-1) . "?";
$statement = $pdo->prepare($sql);
$statement->bindParam(:codes, $question_marks);
$statement->execute($array_of_codes);
while (($results = $statement->fetch(PDO::FETCH_ASSOC)) !== FALSE) {
echo $results;
}
Where $array_of_codes is your PHP array containing the Code parameter for each result you want to look up.
Credit where it's due This question helped with how to do WHERE...IN queries with PDO.

PHP: Insert array data into MySQL Database

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

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

PHP Array comes out backwards

This is my current output from a preg_match_all
Array
(
[0] => Array
(
[0] => 2 Sentence text here
)
)
Array
(
[0] => Array
(
[0] => 3 Sentence text here.
[1] => 4 Sentence text here.
[2] => 5 Sentence text here.
)
)
I'm trying to insert each output as a new row in a table but it's thinking that each [0] [1] [2] is a new column. How do I insert the array into mysql?
$query = "INSERT INTO table (col1) VALUES ";
foreach ($matches as $item) {
$query .= "('".$item[0]."'),";
}
$query = rtrim($query,",");
$result = mysql_query($query);
The above obviously only inserts the first row in of the array
Well, you have an array in other array, so...
$query = "INSERT INTO table (col1) VALUES ";
if(!empty($matches))
{
foreach ($matches as $item) {
foreach ($item[0] as $items) {
$query .= "('".$items."'),";
}
}
}
if(!empty($matches))
{
foreach ($matches[0] as $item) {
$query .= "('".$item."'),";
}
}
Depends on how you are getting your array matches.
$query = rtrim($query,",");
$result = mysql_query($query);
That way you'll get this query:
INSERT INTO table (col1) VALUES ('2 Sentence text here'), ('3 Sentence text here'), ('4 Sentence text here'), ('5 Sentence text here')
Which is a valid way to insert several values in one column with a single INSERT statement.
Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO, or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.

Categories