insertion through variable in mysql table - php

I want to insert data into mysql table through user defined variables. Here is what i am doing. Its gives no error but also don't upload any data into table.
$sql="insert into table(".$columns_name.") values(".$val.")";
Here is how the the values of the variables are:
$columns_name= col1, col2, col3, col4
$val= aa, 11, 22, bb

Possible issues:
1- table is a reserved word. your table name can't be 'table'. (I assume you wrote it as a mock name).
2- the format of column names and values in INSERT query is wrong.
Try this before query:
$columns_name = "`$columns_name`";
$columns_name = str_replace(', ', '`, `',$columns_name);
$val = "'$val'";
$val = str_replace(', ', "', '",$val);

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

MySQL INSERT two fields only

I have a table with quite a few columns. The total number of columns is not yet specified, and will change on a regular basis.
In my insert query, I only need to put two values into the table. All other values will be ' '. is there a way to only specify the first fields, without having to include '','','',''...? Please see below for example:
I would like to have this:
$query = mysql_query("INSERT INTO table VALUES('','$id')");
Rather than this:
$query = mysql_query("INSERT INTO table VALUES('','$id','','','','','',''......and on and on...)");
Is there a way to do this? Thanks!
Yes, specify the column names after the table name:
INSERT INTO table (column1, column2) VALUES ('','$id')
I'd prefer
INSERT INTO table SET columnA = 'valueA', columnB = 'valueB'
INSERT INTO table_name (column1, column2) VALUES (value1, value2)
http://www.w3schools.com/php/php_mysql_insert.asp
Just define the fields you will insert,
eg:
INSERT INTO table (fieldA, fieldB) VALUES('','$id')
the missing fields will have the default value for that field

Make an insert with the values returned by another query directly (PHP)

Im doing a PHP script for insert in the table A values recovered from the table B (A and B are in different databases).
Table A Columns
[index(autoincrement),timestamp(currenttimestamp),col1,col2,.....col15]
and I have the query for retrieve the values from B:
$query= "select count(*) as col1, XXX as col2.....ZZZ as col15 from B";
so having the
$row=$mysql_fetch_array($result)
where
$result=mysql_query($query)
how can I make an
insert into A (col1,col2.....col15) values ($row['col1'],....$row['col15'];
easily without write all the code? Thanks
Insert into db1.A (col1, col2, col3) SELECT col1, col2, col3 FROM db2.B
If you have to transfer the data across databases on different servers, you can use sprintf and implode to generate your query.
$query = sprintf('INSERT INTO table_name (%s) VALUES ("%s")', implode(', ', array_map('mysql_escape_string', array_keys($row))), implode('", "',array_map('mysql_escape_string', $row)));

MYSQL - INSERT INTO from left

First of all thanks for your help, I'm asking how can I insert data into fields starting from the left? Depending on the entity sometimes several fields at the end are left blank but I need to insert the filled fields into the table. If I try to do this, I obviously get a column-values mismatch error.
Thanks!
The column count you use and the number of values you try to insert have to match. You can specify what you want to insert, so you don't have to pass the columns which aren't needed (and so you don't need to pass "blanks").
INSERT INTO Store_Information (store_name, Sales, Date)
VALUES ('Los Angeles', 900, 'Jan-10-1999')
More information:
http://www.1keydata.com/sql/sqlinsert.html
Just specify only fields names you gonna insert at the moment:
INSERT INTO table (field1, field2, field3) VALUES (value1, value2, value3)
or this way
INSERT INTO table SET field1=value1, field2=value2, field3=value3
no matter is it from left, right or checkered
as SQL query is just a string, you could use some PHP code to build this string in the way you want.
hereis an example code in the form of very simple helper function to produce SET statement dynamically:
function dbSet($fields) {
$set='';
foreach ($fields as $field) {
if (isset($_POST[$field])) {
$set.="`$field`='".mysql_real_escape_string($_POST[$field])."', ";
}
}
return substr($set, 0, -2);
}
it can be controlled by $fields array.
used like this
//if we have full set of data
$fields = explode(" ","name surname lastname address zip fax phone");
$query = "INSERT INTO $table SET ".dbSet($fields);
//if we have only three fields ready
$fields = explode(" ","name surname lastname");
$query = "INSERT INTO $table SET ".dbSet($fields);
but you desperately need to learn basic PHP string operations to be able to do such things yourself.
string operations are most important in PHP, as almost every task for PHP is just string manipulation like in your case.
Use querys like
insert into table set col1=val1, col2=val2;
or
insert into table(col1, col2) values(val1, val2);
That is the only way around it. I think method 2 is the most commonly used.
If there is any way you can supply default values for each column use them for the columns you don't have values for.
if all the data can be "NULL", you can setup your query with variables that, if not set, are NULL, example:
$col1 = null;
$col2 = null;
$col3 = null;
$col4 = null;
$col5 = null;
then populate the columns you need
$col1 = 'val1';
$col2 = 'val2';
$query = "INSERT INTO (col1, col2, col3, col4, col5) VALUES ($col1, $col2, $col3, $col4)";
Sincerely I'll never use something like this... but you asked for it...
mysql_query("INSERT INTO People (First_Name, Last_Name, Age)
VALUES ('Marcus', 'Porter', '28')");
mysql_query("INSERT INTO People (First_Name, Last_Name, Email)
VALUES ('Marcin', 'Kruk', 'marcin.kruk#gmail.com')");

Categories