An easy way to write INSERT INTO table VALUES (value1, value2, ...valueN) - php

I need to insert values from an array using PHP into my database. The array has 40 positions, each position is a value I have to insert into a table of my database.
I need a quick way to write it down and not write $1,$2,$3 ... $39
I tried:
$query = 'INSERT INTO table VALUES($1,$2, ..... $39)';
$result = pg_query_params($dbh, $s, $a[0]); //$a[0] array with 39 positions
But it's too long to write it down. I have another piece of code where I have 140 positions.

Just build an array range from 1 to the length of the array and add the $ and commas:
$values = '$' . implode(',$', range(1, count($array)));
$query = "INSERT INTO table VALUES($values)";
$result = pg_query_params($dbh, $query, $array);

Related

PHP dynamically add new column and value in existing Query

My application performs INSERT queries like this:
INSERT INTO table (`col1`, `col2`, `col3`) VALUES ('oneVal', 'twoVal', 'threeVal')
Now I want to rebuild my application so it will ALWAYS SELECT, INSERT, DELETE and UPDATE with a specific id.
Let's say the unique id is called: companyId
I don't want to rewrite all my queries manually, so I am trying to write a function that rewrites the existing SQL queries with PHP so it will include the companyId inside the query.
Desired outcome if companyId would be '1' (companyId IS NOT ALWAYS '1'!):
INSERT INTO table (`col1`, `col2`, `col3`, `companyId`) VALUES ('oneVal', 'twoVal', 'threeVal', '1')
My question(s) is/are:
Is there a way in PHP so I can dynamically rewrite the query so
it would include the companyId column and the matching id value?
Is there a better way to do this? Like some trick setting MySQL
server to ALWAYS use an extra value (in this case companyId='1'
?
I've tried option (1) by searching for the string
) VALUES
Once I found that string, I add companyId before the ).
Now get to the end of the query, get the most right ) and add the value before that.
But is this for a generic case? I think there might be a better way to solve this.
Thanks in advance community!
EDIT 1 with more clarification
Currently I've already built a function that modifies my SELECT statements.
Function code:
//If current query = SELECT query
if (containsString($sql, 'select')) {
//Check if contains WHERE
if (containsString($sql, 'where')) {
//Yes
//Add companyId after WHERE
$sql = substr_replace($sql, '(companyId=?) AND ', strpos($sql, 'WHERE') + 6, 0);
//Explanation:
//SELECT * FROM table WHERE deleted='No'; becomes -->
//SELECT * FROM table WHERE (companyId=?) AND deleted='No';
}else{
//No
//Get table , and after that INSERT WHERE companyId=?
$tableName = explode(' from ', strtolower($sql))[1]; //Get part AFTER 'from'
//First word after $tableName = tablename
$tableName = explode(' ', $tableName)[0]; //First word after 'from' = tablename
$sql = substr_replace($sql, 'WHERE (companyId=?) ', strpos($sql, $tableName) + strlen($tableName) + 1, 0);
//Explanation:
//SELECT * FROM table ORDER BY id; becomes -->
//SELECT * FROM table WHERE (companyId=?) ORDER BY id;
}
}
So this code dynamically adds an extra condition to the query statement.
This is also easily possible with DELETE and UPDATE statements (same as SELECT)
But Iam trying to come up with something like this for INSERT INTO queries.
How can I modify the original query using the new companyId?
I guess If you have an associative array with the column names and values then you easily can make it more dynamic for future also. Let's say you've an array of column names with value of it e.g
$data = ['col1'=>'val1','col2'=>'val2','col3'=>'val3','companyId'=>1];
$query = "INSERT INTO `yourtable` ( ".implode(' , ', array_keys($data)).") VALUES ('".implode("' , '", array_values($data))."')";
echo $query;
DEMO: https://3v4l.org/udt1i
Then you can do with regex replace way globally to add column and value to all of your 100 query.
<?php
$re = '/\) VALUES (.+?(?=\)))/m';
$str = 'INSERT INTO table (`col1`, `col2`, `col3`) VALUES (\'oneVal\', \'twoVal\', \'threeVal\')';
$subst = ',`col4`) VALUES $1 , \'1\'';
$result = preg_replace($re, $subst, $str);
echo $result;
?>
DEMO: https://3v4l.org/rOQDG

Inserting data into a MySQL table with PHP when the values being inserted do not match the number of columns in the table

I have a mysql table with over 100 columns, but I've shortened it to 6 for this example:
col0(autoincrement), col1, col2, col3, col4, col5, col6
I'm getting data from external sources ($csvcontent below), and that data will have 6 or less values per line. I'd like to use PHP to read these values into an array, and insert the array values into into my mysql table.
$csvcontent = file from external source
$fieldseparator = ",";
$lineseparator = "\n";
$linearray = array();
foreach(explode($lineseparator,$csvcontent) as $line) {
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
$query = "insert into MYTABLE values('','$linemysql');";
}
How can I insert the following rows, assuming that I don't know ahead of time how many values are stored inside of $csvcontent? This existing code works well when I always have 6 values, but not when I have fewer.
insert into MYTABLE values('','1','2','3','4','5','6'); //works
insert into MYTABLE values('','1','2','3','4'); //doesn't work
insert into MYTABLE values('','1','2','3','4','5'); //doesn't work
Well, based on the size of $linearray, you can create a column sequence and attach that to your insert query.
<?php
$columns = ['col1','col2','col3','col4','col5','col6'];
$linearray_samples = [
[1,2,3,4,5],
[1,2,3],
[1,2,3,4],
[1],
[1,2],
[1,2,3,4,5,6]
];
foreach($linearray_samples as $each_sample){
echo "(",commaSeparatedColumns($each_sample,$columns),")",PHP_EOL;
}
function commaSeparatedColumns($sample,$columns){
return implode(",",array_slice($columns,0,count($sample)));
}
The code outputs:
(col1,col2,col3,col4,col5)
(col1,col2,col3)
(col1,col2,col3,col4)
(col1)
(col1,col2)
(col1,col2,col3,col4,col5,col6)
Demo: https://3v4l.org/QLnFo

Insert an array to the database like a separate rows

Sorry if this is a duplicate, but I can't reached the result using answers in similar questions.
Here is my situation:
I have a table (users_temp) with 1 column - Users_id;
And I have an array of values, for example - $usersIds = [1,2,3,4,5];
I want to Insert this array to my table and create 5 new rows.
I was trying smth like that, but it doesn't work:
$newdata = "'" . implode("','", $usersIds) . "'";
db_query("INSERT INTO db.users_temp (user_id) VALUES ($newdata)");
Can you help me, please?
Assuming that the $userIds field is safe (all INTs) then just amend your implode a touch.
$newdata = implode("),(", $usersIds);
db_query("INSERT INTO db.users_temp (user_id) VALUES ($newdata)");
You might want to add a check that the array has more than 0 elements.
You can do this
$usersIds = [1,2,3,4,5];
foreach ($usersIds as $user_id) {
db_query("INSERT INTO db.users_temp (user_id) VALUES ($user_id)");
}
To insert multiple rows in a single statement:
sql:
insert into users_temp (user_id)
values (?), (?), (?) [...]
php:
$userIds = array(1, 2, 3, 4, 5);
$placeholders = rtrim(str_repeat('(?),', count($userIds)), ',');
$sql = "insert into users_temp (user_id) values ($placeholders)";
$stmt = $pdo->prepare($sql);
$stmt->execute($userIds);
Your code can build up the placeholders string as above.

PHP Array Explode Twice

I have an array which I need to insert into multiple rows of database. The structure of array is like:
$var = "Name1,Age1,DOB1,Relation1.Name2,Age2,Dob2,Relation2.";//And so on, depending on users input
(Dot indicates new line whereas Comma indicates new column)
I need to insert it into database like this:
I first stored all rows in an array like:
$rowsToInsert = explode (".",$var);
I have now:
$rowsToInsert[0] = Name1,Age1,DOB1,Relation1;
$rowsToInsert[1] = Name2,Age2,DOB2,Relation2;
...And So on...
Problem:
What is the fastest way to store these array elements into database having Name, Age, DOB, Relation columns?
May be this will work
$rows = explode (".",$var);
$addslash = addslashes($rows);
foreach($addslash as $val) {
$val_str = str_replace("," ,"','", $val);
$sql = "INSERT INTO tablename (Name, Age, DOB, Relation) VALUES ('" .$val_str. "')";
}

PHP MYSQL 'INSERT INTO $table VALUES ......' variable number of fields

I am still learning PHP and MYSQL and trying to make a program to list all tables and data in database (that's done), edit selected row (that's done) and now add new record on selected table. Now the problem is with variable number of fields. Table could be with 3 fields, could be 4 and so on. On my code here $getValue is an array. I am printing it out only for testing. It could look like "Array ( [name] => Tomas [lastName] => Timas )" or "Array ( [stufName] => Phone [stufPrice] => 58 [comments] => My new phone )"
$getTable returns name of a table to insert into.
This has to be a new record on the table, so stufID or nameID or what ever ID will be NULL
How do I use "INSERT INTO table VALUES (value1, value2, value3,...)" if I do not know the number of values?
<?php
include "conf.ini"; //connection to the db
$getValue=$_REQUEST['value'];
$getTable=$_REQUEST['table'];
// test********************
print_r($getValue);
print '<br>';
print $getTable;
// test********************
if (!$_POST['submit']) {
print 'Please input data';
} else {
mysql_query ("INSERT INTO $getTable VALUES (?????)");
}
?>
I hope you know this is very dangerous, so do this only if you're sure there are no potentional attackers!
$all_keys = array_keys($getValue);
$getValue = array_map('mysql_real_Escape_string', $getValues);
mysql_query ("INSERT INTO $getTable (`".implode('`,`', $all_keys)."`) VALUES ('".(implode(",", $getValue))."')");
$values = array_map('mysql_real_escape_string', array_values($getValue));
$keys = array_keys($getValue);
mysql_query("INSERT INTO $getTable (".implode(',', $keys).") VALUES ('".implode('\',\'', $values)."')");
Perhaps you should create an include file to execute the values for $gettables and then it include that where you want $gettables values to be picked up.

Categories