PHP explode and sort - php

I need to sort an exploded string to write into database.
With the code down below it works, but I was not able to detect the summary of arrays outside the foreach loop.
So $terms[0].$terms[1].$terms[2] was not correct.
Cause as example $terms[0].$terms[1].$terms[2].$terms[3] was required for 4 terms in string.
How could that be solved?
$terms = explode(";", "banana;apple;lemon");
sort($terms);
$length = count($terms);
for($x = 0; $x < $length; $x++) {
$terms[$x] = $terms[$x].'; ';
}
$sorted_terms = $terms[0].$terms[1].$terms[2]; // <<< should changed dynamically
$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms) VALUES ('$sorted_terms')");

Use PHP implode which is an exact opposite of explode and intended for just this sort of thing.
$terms = explode(";", "banana;apple;lemon");
sort($terms);
$sorted_terms = implode(";", $terms);
//$sorted_terms = "apple;banana;lemon";
Edit:
As you're using procedural MySQLi for your data entry you should also use mysqli_real_escape_string to limit SQL injection into your database. I know it may not apply to your current work but it's best practise to get into - short of actually using Prepared Statements.
so:
$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms)
VALUES ('".mysqli_real_escape_string($dbcon, $sorted_terms)."')");
Using Prepared Statements instead is very highly recommended.

Simply use string concatenation.
Use $terms1 as string in for loop.
$terms1 = "";
$terms = explode(";", "banana;apple;lemon");
sort($terms);
$length = count($terms);
for($x = 0; $x < $length; $x++) {
$terms1 .= $terms[$x].'; ';
}
//$sorted_terms = $terms[0].$terms[1].$terms[2];
//$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms) VALUES ('$sorted_terms')");
$sql = mysqli_query($dbcon,"INSERT INTO mydatabase (terms) VALUES ('$terms1')");

Try $sorted_terms = implode(';', $terms);
http://php.net/manual/en/function.implode.php

Related

php sum the values seperated by special character

I need to sum the result set values separated by "|" inside the loop eg. set of values 10|2, 6|2, 8|1 should result in 24|5.
here is my code:
<?php
$fromdate="2016-03-31";
$todate="2016-03-31";
$TAG="1";
$con = mysqli_connect("XXXXX","XX","XXX","XXX");
$query = mysqli_query($con, "CALL sp_Android_Online_Dashboard('$fromdate', '$todate','$TAG')") or die("Query fail: " . mysqli_error());
$Totfiles = 0;
$file_minutes = 0;
$Tot_minutes=0;
$Pending=0;
while(($row = mysqli_fetch_array($query)))
{
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
$response["Details"]['Totfiles'] = $Totfiles;
$response["Details"]['file_minutes'] = $file_minutes;
$response["Details"]['Pending'] = $Pending;
$response["Details"]['Tot_minutes'] = $Tot_minutes;
echo json_encode($response);
?>
$row["Pending"] contains the values which are to be summed
result am getting now,
"Pending":"16|9"
"Pending":"11|3"
"Pending":"6|2"
my expected result,
"Pending":"33|14"
This is what you are aiming at i think, you make an array first containing 2 values, on each iteration through the loop you add the new values to them and at the end you can implode it into a string again
// Start with an array containing 0 twice
$Totalpending = [0,0];
while(($row = mysqli_fetch_array($query)))
{
// On each loop we add the left value to the first value in the array and the right value to the second value in the array
$tmp = explode("|", $row['Pending']);
$Totalpending[0] += $tmp[0];
$Totalpending[1] += $tmp[1];
$Totfiles +=$row["Totfiles"];
$file_minutes +=$row["file_minutes"];
$Pending =str_replace(array("/"),"|",$row["Pending"]); //need to sum all the values separated by "|"
$Tot_minutes +=$row["Tot_minutes"];
}
// if you want to format the values in the same way again, although an array is much easier to handle, but it's up to you.
$stringTotalpending = implode('|',$Totalpending);
the string value you want will then be in $stringTotalpending
So Firstly, we need to explode the values from $row["Pending"].
$arr = explode("|", $row["Pending"]);
Now use a loop to add those two numbers:
$temp = 0;
for($i = 0; $i < count($arr); $i++){
$temp += (int) $arr[$i];
}
Now the $temp would contain the result.
As simple as that.
And also as a side note, your code is vulnerable to SQL-Injection attacks.
What about evaling the same string with '|' replaced by '+' ?
eval('$result = ' . str_replace('|', '+', preg_replace('/[^0-9|]/', '', $row["Pending"])) . ';');
echo "$result\n";
Note preg_replace() to sanitize input. Can be avoided if input is already sanitized

Explode and then merge arrays

I have two strings, one containing names separated by commas and the other containing email addresses separated by commas.
I now want my end result to replicate the behaviour as if I had gotten those values from the database with a:
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
echo $row['name'].'<br />'.$row['email'];
}
So I have for example these strings:
email1#domain.com,email2#domain.com,email3#domain.com
and
name1,name2,name3
And can then explode these into value arrays. Now, after exploding them,
I want to be able to make a loop where in each loop I can get $name[0] and $email[0] together, and $name[1] and $email[1] together, etc.
How can I merge the two arrays (after exploding them) and get the data for each datapair (name and email) in a loop?
So if I understood you right, you are converting your strings (lets call them email, and name) too two arrays (lets call them arrEmail, and arrName) and now you want to get a array with the merged datasets.(creating the arrays should be easy if not check this out: manual for php explode function)
If so I would create a for loop based on the length of your two arrays. In the loop I would extract value i of arrEmail and arrName, and put the information into an two-dimensional array. Maybe something like this:
It should work but I didn't test it for ages so if not leave me a comment.
<?php
$arrEmail = array();
$arrName = array();
$arrGoal;
$arrLength = count($arrName);
//creating two-dimensional Array
for($i = 0; $i < $arrLength; $i++){
$arrGoal[$i] = array($arrName[$i], $arrEmail[$i]);
//should look something like this ((name, email),(name, email)…)
}
$arrGoalLength = count($arrGoal);
//accessing Array
//1. dimension
for($i = 0; $i < $arrGoalLength; $i++){
//2. dimension
//Variables should be global (but aren't)
$newName = $arrGoal[$i][0];
$newEmail = $arrGoal[$i][1];
}
?>
I think you want something like this:
$output = array();
for ($i = 0; $i < count($names); $i++) {
$output[] = $names[$i] . ' ' . $emails[$i];
}
print_R($output);
$emails = 'email1#domain.com,email2#domain.com,email3#domain.com';
$emails = explode(',', $emails);
$names = 'name1,name2,name3';
$names = explode(',', $names);
and you can use array_combine() as follow :
$combined = array_combine($names, $emails);
foreach($combined as $name => $email){
echo $name, ' : ', $email, '<br/>';
}
I think you should use the built in explode function wich will allow you to turn a string to an array by spliting it using a delimiter (comma) :
$names = explode(",",$row['name']);
$email = explode(",",$row['email']);
for merging them you should use something like this
$Array = array();
for ($j = 0; $j < count($names); $j++) {
$Array[] = [$names[$j],$email[$j]];
}
This is kind a related with your question, but only if you like to access the value by a key(e.g. access the name by email provided):
<?php
$emails = 'email1#gmail.com,email2#gmail.com,email3#gmail.com';
$names = 'name1,name2,name3';
$arrayEmails = explode(',',$emails);
$arrayNames = explode(',',$names);
$result = array_combine( $arrayEmails, $arrayNames);
print_r($result);
?>

Variable string concatenation and interpolation, string is stored in array

I wish to create a piece of dynamic SQL where the values from string variables are used as variables in the SQL string:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,'1234');"
This works.
What I need to do however, is to have "variable variables"?
So earlier on in the code:
foreach($array as $val)
{
$s .= ',"$val"[$i]';
}
This creates the string:
s = ,'$val[0]','$val[1]'
When inserted as the SQL string:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,$s);"
It returns:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,'$val[0]','$val[1]');"
Whereas it should return:
"INSERT INTO `product` (`id`,`number`) VALUES (NULL,'12','34');"
This is being very literal as the MySQL insertion is on a loop where by $val is the array value and [0] is the key.
I'm not sure if this makes sense to anybody as I'm struggling to wrap my head around it, please let me know if my question is to vague or just doesn't make any sense at all.
Thanks
Nick
You are using single quotes, so no string interpolation is done, if you want strings interpolated you have to use double quotes"$var":
$arr = array( 1,2,3);
$i = 0;
echo '$arr[0]'; // prints: $arr[0] <== Your error is here
echo "$arr[0]"; // prints: 1
A better approach
Anyways, you may like to do it this way:
$array = array(12, 34);
$s = implode("', '", $array); // $s is: 12', '34
$s = ", '$s'"; // $s is: '12', '34'
echo $s; // prints: , '12', '34'
From what I could understand from your question, this might help you to achieve what you are looking for.
On your foreach loop you are using
$s .= ',"$val"[$i]';
$val is not concatenated in correct way
try this one
$s .= ','.$val[$i];
You can split values in array by , with implode function
For example:
$array[] = 12;
$array[] = 31;
implode(','$array) returns 12,31
so you could use $s = ','.implode(','$array); to achieve same result
Using your code I think this is what you are trying to do but as I said you are missing attributes.
$s="";
$array = array("12","34");
for($i =0; $i < count($array); $i++)
{
$s .= ",'" . $array[$i] . "'";
}
$sql = "INSERT INTO `product` (`id`,`number`) VALUES (NULL$s);";

To prevent sql-injection, is it sufficient for mysqli_real_escape_string() to be applied only once to a comma separated string?

I apologize if someone posted this and I missed it...I googled and scanned SO for a similar question and if it exists, I missed it.
Scenario: user enters comma separated input. The string needs to be exploded and each piece used to update different table row. Is it sufficient to apply mysqli_real_escape_string() once:
<?php include 'connect.php';
$ExplodedCommaString = explode(",", mysqli_real_escape_string($cxn, $_GET['userinput']));
$Count = count($ExplodedCommaString);
for ($i = 0; $i < $Count; $i++) {
$myID = $ExplodedCommaString[$i];
$sql = mysqli_query($cxn, "UPDATE myTable SET myValue = 'y' WHERE id = '$myID'");
}
?>
or must each pass through the for loop apply mysqli_real_escape_string?
<?php include 'connect.php';
$ExplodedCommaString = explode(",", $_GET['userinput']);
$Count = count($ExplodedCommaString);
for ($i = 0; $i < $Count; $i++) {
$myID = $ExplodedCommaString[$i];
$sql = mysqli_query($cxn, "UPDATE myTable SET myValue = 'y' WHERE id = '".mysqli_real_escape_string($cxn, $myID)."'");
}
?>
So, apply it once on the comma-separated string and explode the string, or explode the string and then apply it for each iteration of the for loop?
By using prepared statements you don't have to worry about escaping the content yourself, or how to properly do it.
Example:
<?php include 'connect.php';
$ExplodedCommaString = explode(",", $_GET['userinput']);
$Count = count($ExplodedCommaString);
for ($i = 0; $i < $Count; $i++) {
$myID = $ExplodedCommaString[$i];
// replace your raw var with ? in the sql statement
$sql = "UPDATE myTable SET myValue = 'y' WHERE id = ?";
// run the prepare method
$stmt = $conn->prepare($sql);
// bind the '?' in the sql statement to $myID of type int
// I'm assuming it's an int here, if it's a string change the 'i' to an 's'
$stmt->bind_param('i', $myID);
// and run it
$stmt->execute();
}
?>
Some further reading, examples, and discussion.

Comparing an array against itself

I am currently a bit stuck in finding out how to compare these variables against eachother, I have 24 dropdown selections with 24 options to choose from within each one, I then post them to the PHP page. What is the easiest, most efficient way of comparing each of these values against each other to check that each option that is chose is different from each other as none of the 24 options can be the same. I know that an array is the way forward with this, just not sure on how to compare them.
Any help is much appreciated.
$id = $_POST[trackid];
$pos1 = $_POST[pos1];
$pos2 = $_POST[pos2];
$pos3 = $_POST[pos3];
$pos4 = $_POST[pos4];
$pos5 = $_POST[pos5];
$pos6 = $_POST[pos6];
$pos7 = $_POST[pos7];
$pos8 = $_POST[pos8];
$pos9 = $_POST[pos9];
$pos10 = $_POST[pos10];
$pos11 = $_POST[pos11];
$pos12 = $_POST[pos12];
$pos13 = $_POST[pos13];
$pos14 = $_POST[pos14];
$pos15 = $_POST[pos15];
$pos16 = $_POST[pos16];
$pos17 = $_POST[pos17];
$pos18 = $_POST[pos18];
$pos19 = $_POST[pos19];
$pos20 = $_POST[pos20];
$pos21 = $_POST[pos21];
$pos22 = $_POST[pos22];
$pos23 = $_POST[pos23];
$pos24 = $_POST[pos24];
Given an array you could try array_unique function
count($original_array) != count(array_unique($original_array))
Alternative solution with array_count_values
count(array_count_values($original_array)) = count($original_array)
There are lot of way to do that (e.g. a for loop), it just depends from your exact needs.
Firstly, you should be adding quotes around your array indices rather than using barewords which should be raising warnings:
$pos1 = $_POST['pos1'];
To copy the pos* values out of $_POST, you should use a loop:
$pos = array();
for ($i = 1; $i <= 24; ++$i) {
$pos["pos$i"] = $_POST["pos$i"];
}
To make sure there are no duplicates, use array_unique and see if the two arrays have the same length:
if (count(array_unique($pos)) == count($pos)) {
# pos contains no duplicates
}
Just do an array_unique on it. First you'll need to put those POST vars into an array instead of splitting them up.
$pos = array();
for ($i = 1; $i <= 24; $i++)
{
$pos["pos$i"] = $_POST["pos$i"];
}
$unique = array_unique($pos);
if (count($unique) == 24)
{
// all good!
}
else
{
// bad!
}
can you more explicit? if none of them can be the same, than what is the problem?
considering that you actually can select the same option more than once or you just want to protect from attacks, than you can put them into an array, and then use the array_unique function.

Categories