I am imploding data inside of an array, called the following:
["Levels_SanctionLevel_array"]=>
string(14) "IR01,IR02,IR03"
I need to explode this data and input each value as a row inside of mysql. Such as
pri_id value
---------------
01 IR01
02 IR02
03 IR04
Now where I am getting stuck is this:
The array listed above could have 1 value, 3 values (right now I am showing three values) or 5 values, and I dont want to input NULL values inside of my database.
Appreciate any guidance anyone can share...
$data = explode(',',$your_string);
foreach ($data AS $value) {
// INSERT INTO DB
}
A simple loop works correctly, but has the drawback of making multiple queries to the database:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
foreach ($vals AS $value) {
// insert into database
}
As DB operations are a more significant bottleneck than building a query in PHP, I would opt to generate the SQL code for a single query as follows:
$str = "IR01,IR02,IR03";
$vals = explode(',', $str);
$query = 'INSERT INTO my_data VALUES ';
foreach ($vals as $value) {
$query .= "('', '".$value."'),";
}
$query = rtrim($query, ',');
// insert into database
Why don't you use an iterator over the array to construct the sql query? That way you will only insert as many elements as you have in the array.
Like the answer above. I think we were answering at the same time.
Supposing your major array is $data:
foreach ($data as $values)
{
$value = explode(",", $values);
foreach ($value as $v)
{
$sql = "INSERT INTO table(value) VALUES('$v')";
}
}
Related
I'm gonna try to be as clear as possible.
I'm currently working on a project for my work, with dynamic forms where the form inputs are in a database, and created dynamically. Every input row looks something like:
Question? Radiogroup Textinput
And when the user press submit in a section of maybe 3-5 of these rows the form is serialised and managed with AJAX. So here comes the part I'm having trouble with, as of now, in my AJAX file, there is a foreach loop which loops through all $_POST values, adds them to an array and then after the array is complete all data is inserted to a SQL database. And I don't know if it's a problem since I'm not a professional DBA, but there's a lot of rows being inserted to the database, since EVERY radio group, and EVERY text input, gets their own row. And I was thinking if I at least could cut it down to every question getting their own row, but how do I then merge the radio group value with the text input value so they are on the same row but different columns.
I hope I'm being clear enough here.
Database layout today
|ID|RowID|Type|User|Value
Where Type is either Radio or Text. What I want to achieve to get half of the rows I'm gonna get this way is:
|ID|RowID|Type|User|Radio|Text
And the problem is howto achieve this when my foreach loop fills an array with a lot of rows, for each form, which as I say, is containing maybe 3-5 rows with both a radio group and a text input. This is how I do it today:
foreach($_POST as $key => $value) {
$values[] = "'{$id}', '{$user}', '{$type}', '{$value}'";
}
$mysqli->query('INSERT INTO data (rowid, user, type, value) VALUES ('.implode('),(', $values).')');
Hope someone can help me out.
Best Regards
Cisco
Solved it by doing the following:
//Only define for testing.
$_POST['rad_1'] = "yes";
$_POST['rad_2'] = "no";
$_POST['rad_3'] = "yes";
$_POST['txt_1'] = "Test";
$_POST['txt_2'] = "Test2";
$_POST['txt_3'] = "Test3";
$array = array();
foreach($_POST as $key => $value) {
$keyarr = explode('_', $key);
$type = $keyarr[0];
$id = $keyarr[1];
$value = $value;
$array[$id][$type] = $value;
}
$values = array();
foreach($array as $key => $value)
{
$values[] = implode(', ', $value);
}
$query = "INSERT INTO table_name test VALUES (" . implode ("),(", $values) . ")";
I want to do something like this
----sql output----
name TEXT
b
c
$arr = ["a","b","c","d"];
foreach($arr as $key=>$val){
$query = "select count(*) from mydata where name = $val";
$count = xxxx($query);
if($count)unset($arr[$key]);
}
And $arr will be
a,d
Any simple way to do it but not checking every single element?
---edited---
I think I solve my problem myself...getting some inspired from mrlore that using having.
$arr = ["a","b","c","d"]; /* make the string inside arr safe for query */
$val = array_map(function($val){return "'$val'";},$arr);
$q = "select name from mydata where name in (" . implode(',',$val) .")";
$all = xxxxx($q);
$arr = array_diff($arr,$all);
This took me 0.8 second. Using my old way take 46 second and RST way takes 2 seconds.
---edited----
I have over 200k rows of data in my database, so I want a better way to optimize it.
--re MrLore--
ps : I don't know how to use stackoverflow to posting comments..so I just edit my post.
I have tried it on my mysql workbench but it does not seem to work for me.
select name from mydata
where name in("a","b","c","d")
having count(name) = 0
-- returns nothing
select name from mydata
where name in("a","b","c","d")
having count(name) > 0
$arr = ["a","b","c","d"];
$query = "select DISTINCT name from mydata";
$results = <result of query>;
foreach ($results as $result){
if(($key = array_search($result, $arr)) !== false) {
unset($arr[$key]);
}
}
Or the other way around
foreach ($arr as $key=>$value){
if( in_array( $value, $results) ) {
unset($arr[$key]);
}
}
By querying DISTINCT the database only returns unique values. You can then compare them with the array you have and remove them.
I have an odd issue. I have one PHP script that is used for multiple forms. It takes in all the requests and then puts the data in the appropriate table in a database. As it stands, it looks like this:
$fields = "";
$values = "";
foreach ($_REQUEST as $key=>$value)
{
$key = str_replace(":","",$key);
$fields .= "$key,";
$values .= "'$value ',";
}
//remove the ending comma from $fields and $values
$fields = substr($fields, 0, -1);
$values = substr($values, 0, -1);
$sql = "INSERT INTO " . $survey . " ($fields) VALUES ($values)";
mysql_query($sql)
or die(mysql_error());
And this works well. The problem is, there are some forms with checkboxes (i.e. a person can select more than one option). If I were to use a get method, the query string would look like:
www.somesite.php?V9=1&V9=2&V9=4
With the current script, only 4 is taken, since it was the last value.
Now, I know a reason this is happening is because of the way the name of the checkbox is defined in the form. It says name="V9" instead of name="V9[]" However, I cannot change the forms. They are generated by software, and the idea is that any user can create an HTML form, point it to the script and their information will be recorded in a table. So, changing the HTML is not an option for me.
So, I need a way to detect whether a key has been submitted, and if so, append the value. I tried this:
$fields = "";
$values = "";
foreach ($_REQUEST as $key=>$value)
{
//check to see if the key has already been used for multi-choice questions
$key_check = strpos($fields, "$key,");
if($key_check !== false){
$values = substr($values, 0, -2);
$values .= "\;$value ',";
}else{
$key = str_replace(":","",$key);
$fields .= "$key,";
$values .= "'$value ',";
}
}
//remove the ending comma from $fields and $values
$fields = substr($fields, 0, -1);
$values = substr($values, 0, -1);
$sql = "INSERT INTO " . $survey . " ($fields) VALUES ($values)";
mysql_query($sql)
or die(mysql_error());
But I get the same results. $key_check never seems to be valid. Any help would be appreciated. Someone here has a working ASP version that does a similar thing, but it emails the data, rather than saving it in a DB.
You could try this if you are using $_GET:
function convertInput($qs=""){
$rtn = "";
$holdingArray = array();
if(trim($qs)!=""){
$vars = explode("&", $qs);
foreach($vars as $val){
$kv = explode("=", $val);
if(count($kv)==2){
if(isset($holdingArray[$kv[0]])){
$holdingArray[$kv[0]] .= "," . $kv[1];
}else{
$holdingArray[$kv[0]] = $kv[1];
}
}
}
$rtn = $holdingArray;
}
return $rtn;
}
print_r(convertInput($_SERVER["QUERY_STRING"]));
Try this:
$keys = array();
$values = array();
foreach ($_POST as $key=>$value){ //So, it will loop through the form data
if (!array_search($key, $keys)){ //Checking to see if the key has been used yet
$keys[] = $key;
} else {
$values[$key][] = array($key=>$value);
}
}
This should build an array of your FORM SELECT choices built from the same form, provided that the data is preserved from the browser and is logically eliminated (when accessed as an array, only the last element of the same associated key is preserved, but otherwise the data is there to be had) instead of procedurally eliminated.
I have no idea if this works, because this is building from a theory, not from any kind of documentation or code expertise.
PHP parses the request string (query string or x-www-form-urlencoded) into $_GET, $_POST, and $_REQUEST arrays using the rule that when the same key is present multiple times, later key values overwrite previous ones. So if you cannot change the key names on the forms to append [] like PHP expects, you have to access the raw query string and parse it by hand.
Note that repeating the key name without [] creates ambiguity as to whether a query string key is meant to be a scalar or an array. You will have to decide how to resolve that. E.g., you can use a server-defined hardcoded list of names with array values.
This is how you could process a query string into a list of values:
function paramlist($querystring, $raw=false) {
$plist = array();
$decoder = ($raw) ? 'rawurldecode' : 'urldecode';
$pairs = explode('&', $querystring);
foreach ($pairs as $pair) {
$plist[] = array_map($decoder, explode('=', $pair, 2));
}
return $plist;
}
If you have a query string like a=1&b=2&a=3, this function will return array(array('a','1'),array('b','2'),array('a','3')). You can then turn that to an associative array using any logic you want.
However, you need to get the query or form string in the first place:
if ($_SERVER['REQUEST_METHOD']==='POST'
and $_SERVER['CONTENT_TYPE']==='application/x-www-form-urlencoded') {
// form body
$qs = trim(file_get_contents('php://input'));
} else {
// url query string
$qs = $_SERVER['QUERY_STRING'];
}
Note that if you send a form encoded with multipart/form-data, PHP will not let you access the raw request (even php://input will not work), so in this case there is no way to reprocess the form variables. Sorry!
what is the optimal way for me to insert and array of 1000 lines and 10 columns each into a mysql table below is how i display it so it would be a similar construct but i need some directions
foreach ($stack as $val) {
print "<tr>\n";
foreach ($val as $no) {
print " <td>$no</td>\n";}
print "</tr>\n";
}
You can insert multiple rows with a single insert as follows :
INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);
look at implode() to create the values string from your array
Better way to insert thousands of data into DB is to use implode function implode
i'm guessing u got something like this
$stack = array("man1" => array("name"=>"ik", "class"=>"highskl", "age"=> "12"),"man1" => array("name"=>"ijk", "class"=>"higkl", "age"=> "13"));
and you want to insert them into a table, try and use the table fields as index for the inner arrays then adjust the code to look like this
foreach ($stack as $entry => $value) {
$query = "INSERT INTO table set ";
foreach ($value as $key => $val) {
$query .= $key ."= ".$val.",";}
//use a string function to remove the last comma
$result = mysql_query($query) or die("Error in Query ".$entry." ",mysql_error());
//this helps to track error..
}
I am looking to store the database values which are already stored as id's and retrieve via a for each loop within an array.
I have tried something like this, but it is not working:
foreach ($list as $item)
{
$commaSeparated = implode(',' , $item['id');
}
echo $commaSeparated;
Where item['id'] is the specific column pulled out of the query. If I use the $list variable, then I am getting the full result of the query which I do not want.
But, my error results in this:
Warning: implode(): Invalid arguments passed
This is what has correctly returned what I need:
foreach ($list as &$id)
{
$listArr[] = $id['toolbar_id'];
$commaSeparated = implode(',' , $listArr)
echo $commaSeparated;
That happens because you need to perform
$commaSeparated = implode(',' , $list);
It is not a good practice though. You should never store the lists as comma-separated items in database. Instead - create additional table for it and store 1 item per row.
The second argument to implode needs to be an array. Try this:
$commaSeparated = implode(',', $list);
Implode function accepts a separator and an array for parameters. Then you should do this:
$commaSeparated = implode(',' , $list);
echo $commaSeparated;
(Source: http://php.net/manual/pt_BR/function.implode.php)
You need to do more checks to avoid the error if your data is not in correct format.
if(is_array($list)){
foreach ($list as $item)
{
if(is_array($item))
$commaSeparated = implode(',' , $item);
}
echo $commaSeparated;
}
I suggest you trying a var_dump($variable) where $variable is the ...variable, in which the data is stored, knowing its structure will tell you what data to expect and how to iterate over it.