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);
Related
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.
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..
I have an array which contains $player_ids. The array was obtained in a form which the user used to select his team. I then query the database with the $player_ids array.
As such:
if ( isset($_POST['submit']) ) {
$player_ids = array_map('intval', $_REQUEST['players']);
var_dump($player_ids);
$query = 'SELECT `name`
FROM `player_info`
WHERE `player_id` IN (' . implode(',', $player_ids) . ')';
$return_names = mysql_query($query) or die(mysql_error());
while ( $row = mysql_fetch_assoc($return_names) ) {
$selected[] = $row['name'];
}
var_dump($selected);
The above code is working and when I open it in my browser I get this output
Now I want to extract the values from array $selected (which contains the names of players selected) and upload it to a database. I try to do this as follows:
foreach ($selected as $player){
$sql = mysql_query('INSERT INTO `team`(`player_name`) VALUES ("$player")')
or die(mysql_error());
print ($player);
echo'<br>';
` }
Im suspecting the above code is where the problem comes in. when the above code is executed the database contains only the array name itself and not the actual values of the array. As the following picture shows:
If anyone could point me in the right direction, as to why the array name and not its values gets saved in the database it would be greatly appreciated.
Thanks in advance.
You must put double quotes around your string instead of single quotes. In single quoted strings variables like $player are not replaced by their value interpreted there as text.
use this:
'INSERT INTO `team`(`player_name`) VALUES ("' . $player . '")'
instead of this:
'INSERT INTO `team`(`player_name`) VALUES ("$player")'
Just replace following code with your ones code and it will work efficiently.
foreach ($selected as $player){
$sql = mysql_query("INSERT INTO `team`(`player_name`) VALUES ('$player')")
or die(mysql_error());
echo "$player<br />";
}
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);
The following is the query that I'm trying to get to work.
$array = array();
SELECT * FROM ENTRIES
WHERE
entry_id = '12'
OR
entry_id_extra IN ('$array')
This is of course simplified. The problem is that it works great if the array has items and it returns everything fine. But if the array has no item it fails to work.
What is the correct way to construct this statement that doesn't break if there are no items in the array? I tried IN ('NULL','$array') but that didnt work.
Any help is appreciated.
You can make the OR portion of the where clause go through a conditional check:
$sql = "SELECT * FROM entries WHERE entry_id = 12"
if (count($array) > 0) {
$sql .= ' OR entry_id_extra IN ($array)';
}
$array = array(...);
$array = array_map('mysql_escape_string', $array); // make sure it's safe
$query = "SELECT *
FROM entries
WHERE entry_id = '12'"
. (count($array) > 0
? " OR entry_id_extra IN ('" . implode("','", $array) . "')"
: "");
// echo the query to see what it looks like (optional)
echo "<pre>{$query}</pre>";
You can use implode, but also make sure you escape the values so quotes don't set the query off.