I have the follow problem:
I have differents arrays, each array contain a list of items.
I try to insert in database but each item of list result togheter.
This is my code:
(i use preg_replace for delete between items)
$codice = preg_replace('/(<br>)+$/', '', $_POST['jcitemcodice']);
$prodotto = preg_replace('/(<br>)+$/', '', $_POST['jcitemname']);
$quantita = preg_replace('/(<br>)+$/', '', $_POST['jcitemqty']);
$prezzo = preg_replace('/(<br>)+$/', '', $_POST['jcitemprezzo']);
$a1 = array("$codice","$prodotto","$quantita","$prezzo");
$res = implode("','" ,$a1);
$sql = "INSERT INTO test (codice,prodotto,quantita,prezzo) VALUES ('$res')";
mysql_query($sql);
Making echo of query the result is:
INSERT INTO test (codice,prodotto,quantita,prezzo) VALUES ('SUT03M SUT02M','Arrabbiata Albahaca','12 6','1.25 1.3')
but for to be correct i need the result:
INSERT INTO test (codice,prodotto,quantita,prezzo) VALUES ('SUT03M','Arrabbiata','12','1.25'), VALUES ('SUT02M','Albahaca','6','1.3')
$codice contain: SUT03M SUT02M
$prodotto contain: Arrabbiata Albahaca
$quantita contain: 12 6
$prezzo contain: 1.25 1.3
I have try a lot of codes looking around but always same result.
Thanks you.
Assuming codice, prodotto, quantita, prezzo don't contain value with _ (underscore), you can explode their content separated by it:
//Change existing tag with defined delimiter
$d = "_";//delimiter
$codice = preg_replace('#<[^>]+>#', $d, $_POST['jcitemcodice']);
$prodotto = preg_replace('#<[^>]+>#', $d, $_POST['jcitemname']);
$quantita = preg_replace('#<[^>]+>#', $d, $_POST['jcitemqty']);
$prezzo = preg_replace('#<[^>]+>#', $d, $_POST['jcitemprezzo']);
//replace space in quantita and in prezzo with the delimiter
$quantita = preg_replace(' ', $d, $quantita);
$prezzo = preg_replace(' ', $d, $prezzo);
//Separate data
$tCodice = explode($d, $codice);
$tProdotto = explode($d, $prodotto);
$tQuantita = explode($d, $quantita);
$tPrezzo = explode($d, $prezzo);
//Formulate values string
$values = "";
foreach($tCodice as $key => $_codice){
if($_codice > ""){
$a1 = array(trim($tCodice[$key]), trim($tProdotto[$key]), trim($tQuantita[$key]), trim($tPrezzo[$key]));
$res = implode("','" ,$a1);
if($values != ""){
$values .= ", ";
}
$values .= "('".$res."')";
}
}
$sql = "INSERT INTO test (codice,prodotto,quantita,prezzo) VALUES $values";
echo $sql;
Please improve this for more custom data from you $_POST
This is a generalized code and no matter how many variables u have and it will add null if no match found in the strings u were already split.
$codice = "SUT03M SUT02M";
$prodotto = "Arrabbiata";
$quantita = "12 6";
$prezzo = "1.25 1.3";
$column_keys = array("codice","prodotto","quantita","prezzo");
$res = array();
$c = 0;
$sql = "";
$max = array("k" => 0,"v" => "");
foreach ($column_keys as $key => $value) {
$res[$value] = explode(" ",${$value});
$c = count($res[$value]);
if($c > $max["k"])
$max = array("k" => $c,"v" => $value);
}
if($max["k"] > 0){
$sql = "INSERT INTO test (".implode($column_keys,",").") VALUES ";
for ($i=0; $i < $max["k"] ; $i++) {
$ar = array();
foreach ($column_keys as $key => $value)
$ar[] = isset($res[$value][$i]) ? $res[$value][$i] : "NULL";
$adstrng = $i>0 ? ",":"";
$sql.= $adstrng."(".implode($ar,",").")";
}
}
echo $sql;
As like #tadman commented don't use deprecated codes and try to do in
updated standards like PDO
Related
Php code
<?php
$d1 = "a:1,b:2,c:3,d:4"; //field number variable.. sometimes 4 or 10
$d2 = explode(',', $d1);
foreach ($d2 as $key => $value) {
$arr1 = explode(':',$d2[$key]);
foreach ($arr1 as $key1 => $value1) {
$arr1[] = $key1;
}
echo $arr1[0] . "," . $arr1[1] . ",";
}
?>
Result
a,1,b,2,c,3,d,4,
Fields (a,b,c,d) (field number variable.. sometimes 4 or 10..)
Values (1,2,3,4)
Expected result
Insert into Table1 (a,b,c,d) values (1,2,3,4)
How can i do to make this result ? (it would be good if it is a complete example)
Thanks for all answers
I know preg_split() will do the task fine. But last day when I got the similar problem I did this solution with the help of http://php.net/manual/en/function.explode.php#111307
function multiexplode ($delimiters,$string) {
$ready = str_replace($delimiters, $delimiters[0], $string);
$launch = explode($delimiters[0], $ready);
return $launch;
}
$d1 = "a:1,b:2,c:3,d:4";
$result = implode(',',multiexplode(array(",",".","|",":"),$d1));
echo $result;
See demo : https://eval.in/871705
Edit: As per comment by SO
$d1 = "a:1,b:2,c:3,d:4"; //field number variable.. sometimes 4 or 10
$d2 = explode(',', $d1);
$result = [];
foreach ($d2 as $key => $value) {
list($k,$v) = explode(':',$value);
$result[$k] = $v;
}
print '<pre>';
print_r($result);
print '</pre>';
echo "INSERT INTO table1 (".implode(', ',array_keys($result)). ") VALUES (".implode(', ',array_values($result)). ")";
In recent PHP versions you can destructure the result of explode() on $d2[$key] (you should improve your naming, it helps!) into two separate arrays like so:
$keys = $values = [];
foreach (explode(',', $d1) as $parameter)
[$keys[], $values[]] = explode(':', $parameter);
var_dump($keys, $values);
var_dump(array_combine($keys, $values));
After that you can simply build that into a query. However, it seems like your data might be user-provided so you should be very wary of that data. You seem to be almost introducing a SQL injection vulnerability in your code.
I suggest checking the $keys array against a whitelist and after that properly escaping all $values before using any of this in a query. You may find some info here: PDO with INSERT INTO through prepared statements
You can use preg_split.
$output = preg_split( "/ (,|:) /", $input );
Next, you can do a check in a loop.
foreach ($output as $value)
{
if(is_number($value))
$keys[] = $value;
else
$values[] = $value;
}
Since the string is close to json format i think making it a true json and decode it means no looping or exploding is an efficient solution.
$d1 = "a:1,b:2,c:3,d:4";
$d1 = "{\"".str_replace(array(",",":"),array('","','":"'), $d1)."\"}";
$arr = json_decode($d1, true);
$table = array_keys($arr);
$values = array_values($arr);
Var_dump($table);
Var_dump($values);
https://3v4l.org/Yqrbe
Edit; if you need the string you named as expected result use this:
$str ="Insert into Table1 (". Implode(",", $table) .") values (" . Implode(",", $values).")";
Echo $str;
Used below code.
Just little bit changes in your code this is working fine.
$d1 = "a:1,b:2,c:3,d:4"; //field number variable.. sometimes 4 or 10
$d2 = explode(',', $d1);
$colums = $values = array();
foreach ($d2 as $key => $value) {
$arr1 = explode(':',$value);
$colums[] = "`".$arr1[0]."`";
$values[] = "'".$arr1[1]."'";
}
$sql = 'insert into `Table1` ('.implode(",",$colums).') values ('.implode(",",$values).')';
Try with following logic:
foreach ($d2 as $key => $value) {
$arr1 = explode(':', $value);
if (count($arr1) == 2){
$arr[$arr1[0]] = $arr1[1];
}
}
Get all fields and values as comma separated:
$fields = array_keys($arr);
¢values = array_values($arr);
And use these variables into your query:
$fields = implode(",", array_keys($arr));
$values = implode(",", array_values($arr));
$query = "INSERT INTO Table1 (".$fields.") VALUES (".$values.")";
Running snipet: https://ideone.com/EXAPOt
The errors I am getting are the following: (Also i am echoing the query statement)
Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 75
Notice: Array to string conversion in /home/fanati10/public_html/wp-content/themes/digital-pro/page-nflwranalyzer.php on line 79
*SELECT * FROM WR_TeamAnalyzer WHERE TMID = ? AND WKID = ?*
HERE IS MY php file
if(isset($_POST['submit']))
{
require_once( get_stylesheet_directory() . '/config/config.php' );
if(isset($_POST['check'])) {
$nflposs = "";
foreach($_POST['check'] as $val => $text_field) {
$nflposs.=$text_field.", ";
}
$nflpossint = rtrim($nflposs, ', ');
$nflposs = explode(',', $nflpossint);
$placeholders = rtrim(str_repeat('?, ', count($nflposs)), ', ');
$filter[] = "TMID = $placeholders";
$values[] = $nflpossint;
}
if(isset($_POST['wk'])) {
$wkid = "";
foreach($_POST['wk'] as $val => $text_field) {
$wkid.=$text_field.", ";
}
$wkidint = rtrim($wkid, ', ');
$wkid = explode(',', $wkidint);
$placeholders2 = rtrim(str_repeat('?, ', count($wkid)), ', ');
$filter[] = "WKID = $placeholders2";
$values[] = $wkidint;
}
$sql="SELECT * FROM WR_TeamAnalyzer WHERE " . implode(' AND ', $filter);
echo ($sql);
$selectStmt = $dbcon->prepare($sql);
$selectStmt->execute($values);
$rows = $selectStmt->fetchAll();
$tableContent = '';
foreach ($rows as $row){
$tableContent = $tableContent.'<tr>'.
When you use = in a query it will expect a string. But you are passing an Array (values) in parameters. I'm not sure what you are trying to achieve here but if you want to check in an Array, change these two lines in your code as below:
TMID IN $placeholders
WKID IN $placeholders2
Your final query should look like this:
SELECT * FROM WR_TeamAnalyzer WHERE TMID IN (?) AND WKID IN (?)
This is what I came up with
change:
$filter[] = "TMID IN $placeholders";
$values = $nflpossint;
&
$filter[] = "WKID IN $placeholders2";
$values2 = $wkidint;
&
$sql="SELECT * FROM WR_TeamAnalyzer WHERE TMID IN ($values) AND WKID IN ($values2)";
$selectStmt = $dbcon->prepare($sql);
$selectStmt->execute();
I am having a real issue with variable interpolation - maybe what I'm trying to do shouldn't be done? Sample code (IRL, the array is 70+ elements):
<form submit>
$_POST['A']; //returns 12
$_POST['B']; //returns 8
<query to get orig field values>
$OrigA = $row->appA; //returns 12
$OrigB = $row->appB; //return 14
<array of names>
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$orig = "Orig" . $field;
$new = "\$_POST['app" . $field . "']";
$fieldname = "app" . $field;
if (${$orig} != ${$new}) { $querystr .= "('default', $applID, '$fieldname', '${$orig}', '${$new}', '$DateTimeReq', '$hvid'), "; };
}
print "querystr: " . $querystr . "\n";
The part if (${$orig} != ${$new}) is what's not working as I would expect. When I print it out to screen with print "DEBUG: if (${$orig} != ${$new}) { $querystr .= \"('default', $applID, '$fieldname', '{$orig}', '{$new}', '$DateTimeReq', '$hvid')\"; };<br />\n";, I see my variables aren't interpolating properly, my debug print says: DEBUG: if ( != ) { .... It should interpolate to (for B): DEBUG: if (8 != 14) { ...
I have tried various combinations of dollar signs and braces, but I don't seem to be making headway. Am I barking up the wrong tree here?
Thanks as always!!
Like this : No interpolation POST variable
<?php
$A = $_POST['A'] = 12; //returns 12
$B = $_POST['B'] = 8; //returns 8
$OrigA = 12; //returns 12
$OrigB = 14; //return 14
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$orig = "Orig" . $field;
$fieldname = "app" . $field;
if (${$orig} != ${$field}) { $querystr .= "('default', $applID, '$fieldname', '${$orig}', '${$new}', '$DateTimeReq', '$hvid'), "; };
}
print "querystr: " . $querystr . "\n";
?>
See http://codepad.org/Ecro0PyG
I don't get all your questions but maybe this code could help you a little (you can use your $_POST var instead of mine $post, that is just to show result and debug):
$post = array();
$post['A'] = 12;
$post['B'] = 8;
$OrigA = 12;
$OrigB = 14;
$fields = array ("A", "B");
$querystr = "INSERT INTO tblEditHist VALUES ";
foreach ($fields as $field) {
$origVarName = 'Orig'.$field;
echo '$$origVarName = '.$$origVarName.'<br/>';
echo '$post[$field] = '.$post[$field].'<br/>';
$fieldname = "app" . $field;
if ($$origVarName != $post[$field]) {
echo $field.' NOT EQUAL!';
} else {
echo $field.' EQUAL!';
}
}
I have a .txt file that logs some information. I want to load it to MySQL table, but I have a following problem: the .txt log file isn't uniform, meaning it looks something like this:
04092012 16:07:34.988 stuff1 stuff2 username1 importantStuff
04092012 16:08:12.145 stuff1 stuff2 stuff3 username2 stuff4 importantStuff
Important thing to say is that all usernames begin with the same characters, just like here. I know that I'm supposed to use something like:
$lines=file(log.txt);
foreach($lines as $v) {
$values = explode(' ',$v);
...
But I do not know how to transfer only date, time, username and importantStuff into MySQL table.
I appreciate any help I can get. Thanks in advance.
$file = file_get_contents('log.txt');
$lines = explode("\n", $file);
foreach($lines as $v) {
$values = explode(' ',$v);
$all = count($values);
$user = preg_match_all('/(user\w+\b)/', $v, $matches); // it will match all usernames that start with "user"
$time = $values[1];
$username = $matches[0][0];
$stuff = $values[($all-1)];
$date = $values[0];
$query = "INSERT INTO `MyTable` ('".$date."', '".$time."', '".$username."', '".$stuff."')";
}
If you are sure that the stuff parts do not contain the same pattern as the username part you can use something like:
$lines=file(log.txt);
foreach($lines as $v) {
$values = explode(' ',$v);
$date = "";
$time = "";
$important = "";
$username = "";
foreach($values as $cnt => $val){
if($cnt == 0){
$date = $val;
} else if($cnt == 1){
$time = $val;
} else if(substr($val, 0, 8) == 'username'){
$username = $val;
}
$important = $val;
}
$query = "INSERT INTO logtable VALUES ('$date', $time', '$username', '$important')";
}
How can i explode this? mars#email.com,123,12,1|art#hur.com,321,32,2
the output should be :
$email = mars#email.com
$score = 123
$street = 12
$rank = 1
then remove the |
$email = art#hur.com
$score = 321
$street = 32
$rank = 2
$string = mars#email.com,123,12,1|art#hur.com,321,32,2
explode( ',', $string );
is that correct?
foreach(explode('|', $str) as $v){
$data = explode(',',$v);
echo '$email = '.$data[0].
'$score = '.$data[1].
'$street = '.$data[2].
'$rank = '.$data[3];
}
You might want to use strtok() rather than explode().
http://www.php.net/manual/en/function.strtok.php
$arr = preg_split( '"[,|]"', 'mars#email.com,123,12,1|art#hur.com,321,32,2' );
$len = count($arr);
for( $i = 0; $i < $len; $i+=4 ) {
$email = $arr[$i];
$score = $arr[$i+1];
$street = $arr[$i+2];
$rank = $arr[$i+3];
}
you need to store the new array in variable >
$arr = explode(',',$string);
and I dont get what you want to do with the second part (after the |), but you can get the first par by doing this > $half = explode('|',$string)[0];
You need to unravel it in the right order:
first the blocks separated by |
then individual cells separated by ,
A concise way to do so is:
$array = array_map("str_getcsv", explode("|", $data));
Will give you a 2D array.
Use strtok and explode.
$tok = strtok($string, "|");
while ($tok !== false) {
list($email, $score, $street, $rank) = explode(',', $tok);
$tok = strtok(",");
}
I think what you want is something like this
$output = array();
foreach (explode('|', $string) as $person) {
$output[] = array(
'email' => $person[0],
'score' => $person[1],
'street' => $person[2],
'rank' => $person[3]
)
}
This stores all the results in a multidimensional array. For example, to print person 1's email, you'd use
echo $output[0]['email']; // mars#email.com
and to access person 2's street, you'd use
echo $output[1]['street']; // 32