Declare php variables for INSERT query in MySQL - php

How to declare php variables that will consist the mysql query columns and values properly? The thing is obviously in quotations, I tried several combination witn no success.
This is the query declared in php:
$query = "INSERT INTO table1(pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8) VALUES ('$q[1]','$q[2]','$q[3]','$q[4]','$q[5]','$q[6]','$q[7]','$q[8]')";
This is my wrong variables in php: (two wrong approaches)
$pt_all = pt1, pt2, pt3, pt4, pt5, pt6, pt7, pt8;
for($i=1;$i<9;$i++) {
$q_all .= '$q[$i]',;
}
This is made in order to place the holder variables into the sql query in php:
$query = "INSERT INTO table1($pt_all) VALUES ($q_all)";
And make it easier and shorter. Is there maybe other better technique?

FIrst of all, do not use mysql_* functions, since those are deprecated. Use mysqli_* or PDO. That said, you probably need something like this:
$fields = "pt".join(", pt",array_keys($q)); //pt1, pt2, pt3, ..
$values = "'".join("','",array_values($q))."'"; //values
echo "INSERT INTO ({$fields}) VALUES ({$values})";
Obviously, you will need to adjust this to fit your requirements, but this should give you good sense on array manipulation.

start with an associative array. As an example, I'll use fruit..
$array = array("banana" => "yellow", "apple" => "red", "kiwi" => "green");
Go through and make the strings "banana, apple, kiwi" and "yellow, red, green"
$fields = array();
$values = array();
foreach($array as $key => $val){
$fields[] = $key;
$values[] = $val;
}
Now concatenate into a string to be used as SQL
$query = 'INSERT INTO table1("'.implode('", "', $fields).'") ';
$query .= 'VALUES ("'.implode('", "', $values).'");';
echo $query; // "INSERT INTO table1("banana", "apple", "kiwi") VALUES ("yellow", "red", "green");
Hope that's what you're looking for.

Related

Creating an INSERT statement for all $_POST variables in an array

We are all familiar with traditional form processing i.e.
$email = $_POST['email']; $name = $_POST['name'];
etc.. and then we go ahead and get all the variables from a post.
and then we would create a compound statement like
$qry = "INSERT INTO $tableName (email,name) values ('$email','$name')";
Now what if you had like 18-20 questions? most people would just write lines and lines of code 99.9% of everyone online does it the same way over and over again.
Let's try something different shall we?
I realized there must be a better way using arrays.
For years I've been looking for a simple routine and looked everywhere for it that will CRAFT an insert statement FROM all the $_POST variables.
It dawned on me that $_POST is actually an array so I wrote this little script:
$vars = $_POST;
print_r($vars);
exit;
After working thru this for a few hours with people on this forum here is the resulting code. I believe that by creating a checksum of the hash of all the array keys will solve the fears of SQL attacks, since the server isn't called unless it gets an exact match. If anyone adds a field it will fail. Does everyone agree?
$predefinedChecksum = "84e602bbec8124f298e353171fb7f5b2"; // this is the hash value of all the array keys
$keys = array_keys($_POST);
$values = array_values($_POST);
$sql = "INSERT INTO $tableName (" . join(',', $keys) . ") VALUES ('" . join("',", $values) . "');";
$checksum = md5(join(',',$keys));
if ($checksum<>$predefinedChecksum) exit;
else $res = mysql_query($qry, $conn);
Thanks to all who contributed... I think we've got the workings of a great script.
Someone mentioned to unset the 'button' - how do you do that?
unset( $_POST['button'] );
This did not work - the output of the script still shows 'button' as one of the variables. So the output of the script still has a field called 'button' in the end.
I'm not sure how you could remove it from the series of $values
Anyone have ideas?
Also the output
INSERT INTO (nameFirst,nameLast,emailPref,emailAlt,phoneDay,phoneMobile,ethnicity,yob,income,marital,kids<18,Education,employment,company,title,industry,department,revAnnual,numemps,street,city,state,zip,Type_Mobile,tablet,computer,laptop) VALUES ('Vik',Grant',viktor#eml.cc',',',',african',',19',single',',Some_HS',student',',',Finance_Accntg',Admin',',',',',',',Android',',',');
is missing the ' quote mark on the beginning of the value - can a join exist as join (a,b,c)?
Just loop it with foreach http://nl1.php.net/manual/en/control-structures.foreach.php be careful as this allows any column to be overwritten.
It is safer to specify which columns are allowed to be inserted.
And plz use something like PDO to use prepared statements
You don't really want to do this since you generate queries which can be altered by the client.
But to answer your question, you can do something like:
$columns = array("email", "name", "etc.."); // Array with the "good" columns.
// Unset the columns you do not want in your query.
foreach($_POST as $key=>$value){
if(!in_array($key, $columns)){
unset($_POST[$key]);
}
}
$qry = "INSERT INTO " . $tableName . " (" . implode(", ", array_keys($_POST)) . ") values (" . implode("', '", array_values($_POST)) . ")";
Although the normal way is to use a loop for producing the string containing your values, i sometimes do the following when i know the exact order of keys in my array:
$arr = array(
"email"=>"foo#bar.gr",
"name"=>"vlzvl"
);
$sql = "INSERT INTO mytable (email,name) VALUES ('".implode("','",$arr)."')";
you shouldn't do this since its huge security issue.
But if you really want to do this: (untested, you can still inject SQL so this ain't secure!)
$keys = array_keys($_POST);
$values = array_values($_POST);
$sql = "INSERT INTO $tableName (" . join(',', $keys) . ") VALUES ('" . join("',", $values) . "');";
Edit:
If you are using PDO, you could do it like this:
$keys = array_keys($_POST);
$values = array_values($_POST);
$valuePlaceholders = "";
for ($i=0; $i < count($_POST); $i++) {
$valuePlaceholders .= $i === 0 ? '?' : ', ?';
}
$sql = "INSERT INTO $tableName (" . join(',', $keys) . ") VALUES ($valuePlaceholders);";
And when executing $pdo->execute($values);

Store Session Array in Database

I have the array-ed session....
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
and I want to store them in my database...
$que = "Insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$_SESSION['Names'][0], $_SESSION['Location'][0])','$_SESSION['Names'][1], $_SESSION['Location'][1])','$_SESSION['Names'][2], $_SESSION['Location'][2])')";
$exec = mysql_query($que);
After Saving, my database (tblpeople) shows the following values:
DateTimePosted: 2014-01-03 16:23:02
first: Array[0],Array[0]
second: Array[1],Array[1]
third: Array[2],Array[2]
Instead, I want my output to be...
DateTimePosted: 2014-01-03 16:23:02
first: 11,35
second: 15,42
third: 26,10
What's wrong?
To expand multidimensional arrays in a string, you need to wrap them in curly braces:
$que = "Insert into tblpeople (DateTimePosted, first, second, third)
VALUES(now(),
'{$_SESSION['Names'][0]}, {$_SESSION['Location'][0]}',
'{$_SESSION['Names'][1]}, {$_SESSION['Location'][1]}',
'{$_SESSION['Names'][2]}, {$_SESSION['Location'][2]}')";
You also had some extra parentheses in the values.
However, this seems like a pretty strange way to store data into a database. Why do you have two values separated by commas in each column, rather than splitting each into separate columns? And why are you storing array elements into different columns, rather than using separate tables with each value in a row?
use this function
$x=serialize($_SESSION['Names']);
it return a string that you can save any where
and this function reverse it
$_SESSION['Names']=unserialize($x);
Try this
<?php
session_start();
$_SESSION['Names'] = array (11,15,26);
$_SESSION['Location'] = array (35,42,10);
$refNumbers = $_SESSION['Names'];
$partIds = $_SESSION['Location'];
$combined = array();
foreach($refNumbers as $index => $refNumber) {
if(!array_key_exists($index, $partIds)) {
throw OutOfBoundsException();
}
$combined[] = array(
'Names' => $refNumber,
'Location' => $partIds[$index]
);
}
print_r($combined);
$combine1 = implode(",",$combined[0]);
$combine2 = implode(",",$combined[1]);
$combine3 = implode(",",$combined[2]);
$que = "insert into tblpeople (DateTimePosted, first, second, third) VALUES(now(),'$combine1','$combine2','$combine3')";
//$exec = mysql_query($que);
?>

Php function to run mysql queries

I am trying to create functions to run mysql queries
How would I do things like insert queries. I was thinking
function insert_query ($table,$cols,$values)
{
$sql="insert into $table ($cols) values ($values) "; ...etc
}
With the rest of the query code in the function. But how would I add multiple columns and values?
Should I make $cols and $values An array inside the function?
This is a function of my Database Class.
public function insert($table,$values){
$fieldNames = "";
$fieldValues = "";
foreach($values as $key => $value){
$fieldNames .= "$key,";
$fieldValues .= "$value,";
}
$fieldNames = substr($fieldNames,0,-1);
$fieldValues = substr($fieldValues,0,-1);
$sql = "INSERT INTO $table($fieldNames) VALUES ($fieldValues)";
$this->newConnection();
$result = $this->mysqli->query($sql);
$this->closeConnection();
return $result;
}
Here is what I'm using. Pass field name and Value as Array key and value. $lsQry is an array of field name & value pair
function insert_record($table,$lsQry)
{
$fields_str = implode(',',array_keys($lsQry));
$data_str = implode("','",$lsQry);
$data_str = "'" . implode("','", $lsQry) . "'";
$lsQry = "INSERT INTO $table($fields_str) VALUES($data_str)";
$rs = mysql_query($lsQry);
if(isset($rs))
return true;
else
return false;
}
Please Note
For this function, do consider that function is getting an array of fields name and value pair. It is assumed that htmlentities() and addslashes() or any escaping functions are already applied while creating array from post/get values.
Easy, just us arrays
function insert_query ($table,$cols,$values){
$sql="insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
insert_query('exampleTable', array('column_1', 'column_2', 'column_3'), array('a', 123, 'c') );
The implode for the values requires a small sidenote:
Strings always required being wrapped in quotes. Therefor I made the implode with single qoutes. The downside to this is that integets (like 123 in the example) also get wrapped.
This is not a big problem, but if you want you could replace the implode with a foreach that uses is_numeric to check wether it should be wrapped in quotes.
IMPORTANT SECURITY NOTE:
In this example I havent used proper seurity, like escape_string(), this has to be added! I've not added thos to keep the examples smaller
Another approach could be key/value-usage of an array:
function insert_query ($table,$data){
$cols = array_keys($data);
$values = array_values($data);
$sql = "insert into $table (".implode(",", $cols).") values (".implode("','", $values)."'') ";
}
$info = array('column_1'=>'a', 'column_2'=>123, 'column_3'=>'c');
$info['example'] = 'Easy method to add more key/values';
insert_query('tableName', $info);
In this case you can use functions similar to codeigniter functions.
Use arrays to store table name and columns or values
For example:
$data = array('hid' => $hcsdate,'start_date' => $sdate, 'end_date' => $edate, 'title' =>$title);
Here $data holds the column name and corresponding values.
And pass this $data to another functions for insert, update etc..

implode() array to insert record into mySql database

I have a single row in a PHP array and I would like to insert that row into mySQL database by imploding the keys and values into a string and using those strings in my Insert statement as follows:
$fields = implode(",", array_keys($_POST));
$newdata = implode(",", $_POST);
$query = (
"INSERT INTO Food_entered ($fields)
VALUES ('$newdata')");
$result = mysqli_query($dbc, $query);
I am able to create the strings, and they appear to be in proper form ,however the row is not being inserted. Seems like a simple approach but not sure what I'm missing.
As #Barmar has pointed out, the problem is your quotes are on the outside of your variable.
I think this may be an easier to follow/cleaner way of fixing this however than the method Barmar posted:
$newdata = "'" . implode("','", $_POST) . "'";
You need to quote each value, not the entire list of values:
$fields = implode(",", array_keys($_POST));
$newdata = implode(",", array_map(function($x) use ($dbc) {
return "'" . $dbc->real_escape_string($x) . "'";
}, $_POST));
$query = (
"INSERT INTO Food_entered ($fields)
VALUES ($newdata)");
$result = mysqli_query($dbc, $query);

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