I Have some request like below :
$input = "$POS,1234,5223,A,2719";
If get a request like above , process an save to database with below code :
$input_ex = explode(",", $input);
$input_ex[0];
$input_ex[1];
$input_ex[2];
$input_ex[3];
$input_ex[4];
mysql_query("INSERT INTO table_name (cl_1,cl_2,cl_3,cl_4,cl_5)
values ('$input_ex[0]','$input_ex[1]','$input_ex[2]','$input_ex[3]','$input_ex[4]')
Problem:
my inputs may be sometimes more than one and split with ' # ' character
last row of inputs is maybe have ' # ' character too
$input = "$POS,1234,5223,A,2719#
$POX,752,4342,N,SXD#
$POZ,122,6242,B,XFB#";
How can i separate each row and insert it on database as a new row ?
thanks ;)
edit :
inputs is 3 different mode , 1st is a one row without any # sign , 2nd is have more row with end # on last row , 3th more row without # sign on end of last row
foreach (explode('#', $input) as $record) {
$record = trim($record);
if ($record == '')
continue;
$input_ex = explode(',', $record);
$input_ex[0];
$input_ex[1];
$input_ex[2];
$input_ex[3];
$input_ex[4];
// Same MySQL query as you already have
mysql_query("...");
}
first explode by '#', and for each result explode by ',' and add new row
Just explode on the '#" first, then loop through the array of results exploding on "," as you are doing and making an insert for each row.
You will need to use explode() twice. First to check for multiple records and then once more to split on the delimiter ,:
<?php
$input = "POS,1234,5223,A,2719# POX,752,4342,N,SXD# POZ,122,6242,B,XFB#";
foreach(explode('#', $input) as $records){
$record = explode(',', $records);
print_r($record);
}
?>
Related
My main motive is to remove the comma ',' from the last value of the array.
$Followingcount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
if (mysqli_num_rows($Followingcount) > 0) {
while ($ids = mysqli_fetch_assoc($Followingcount)) {
$followedids = $ids['acc_id'].',';
$array = array($followedids);
$arraystr = implode("','",$array);
}}
If I echo $followerdids the result comes like this with commas like:
5, 7, 8,
To remove the comma at the last value I tried to place the values inside an array and then I imploded it.
When I echo $arraystr it still contains the comma at the last value.
All you need is:
$followedIds = [];
$followingCount = mysqli_query($con,"SELECT * from followers where follower_id = '$idnow'");
while ($ids = mysqli_fetch_assoc($followingCount )) {
$followedIds[] = $ids['acc_id'];
}
echo implode(',', $followedIds);
...and take care of SQL Injection
The solution to your problem is quite simple. There is a function called rtrim(), which removes all characters on the right side.
$followedids = rtrim($followedids, ',');
There is also a trim() function, which does the same on both sides, and ltrim() which does it for the left side.
You can use rtrim to remove the last comma after the while loop.
$followedids = rtrim($followedids, ',');
You could use the substr-function (more information here)
The last parameter is the length of the substring you want, but you can also use negative values, which means "remove this many characters", in your case: 1.
In your case:
$followedids = substr($followedids, 0,-1);
hii i have 2 level foreach loop like this and i want to remove last comma from each loop ,
/* Here is the mysql query */
foreach($loop1 as $val1){
$showvalone = $val1['data1'];
echo "[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2){
$showvaltwo[] = $val2['data2'];
}
echo implode(",",$showvaltwo);
echo "] , ";
}
output of this program :
[ 1
one ,
two ,
three
],
[ 2
one ,
two ,
three
],
And i want like this
[ 1
one ,
two ,
three
],
[ 2
one ,
two ,
three
]
i am already use implode , trim but is remove only one loop not remove second .
sol me my problem , thanks .
You can turn the problem around and add the ',' to the start of the next output. There is no need to remove it afterwards.
However you don't want the comma for the first output.
$addComma = ''; // should be empty for the first lines.
foreach($loop1 as $val1){
$showvalone = $val1['data1'];
echo $addComma."[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2){
$showvaltwo[] = $val2['data2'];
}
echo implode(",",$showvaltwo);
echo "]";
$addComma = " , "; // any lines following will finish off this output
}
Rather than output the information directly you could put it in to a variable as a string. This will allow you to rtrim the last comma after the loop, then echo the information.
// Declare variable to hold the string of information.
$values = "";
/* Here is the mysql query */
foreach($loop1 as $val1)
{
$showvalone = $val1['data1'];
$values .= "[".$showvalone;
/* Here is the second MySQL query connected with 1st query */
foreach($loop2 as $val2)
{
$showvaltwo[] = $val2['data2'];
}
$values .= implode(",",$showvaltwo);
$values .= "] , ";
}
// Remove the last comma and spaces from the string.
$values = rtrim($values, ' , ');
// Output the information.
echo $values;
I have my own version in removing "," at the end and instead of adding a "."
$numbers = array(4,8,15,16,23,42);
/* defining first the "." in the last sentence instead of ",". In preparation for the foreach loop */
$last_key = end($ages);
// calling the arrays with "," for each array.
foreach ($ages as $key) :
if ($key === $last_key) {
continue; // here's the "," ends and last number deleted.
}
echo $key . ", ";
endforeach;
echo end($ages) . '.' ; // adding the "." on the last array
I am a newbie in this and I have read lots of stuff about this matter (including some topics here), before starting this topic, but I do not quite get it yet, so I will ask for some help (if it is possible) :)
So, in the column that I want to print I have values like this on every row:
value1|value2|value5|value12|value25
value3|value5|value12|value14|value26|value32|value55
value1|value2|value14|value26|value31
The number of rows can be 3 or 1500+... So I want to merge the arrays and print those values sorted and without duplicates: value1, value2, value3, value5, value12, etc...
I have tried to explode the arrays, but I could not find out how to assign a variable to every array and merge them and all I have done is to print all values:
foreach ($rows as $areas) {
foreach (explode('|', $areas->value) as $area) {
var_dump($area);
}
}
Afterwards I have read somewhere this will be very slow if I have many rows (and I am going to have thousands), so I am stuck here and I do not know what else I could do...
I will appreciate any help and direction that you can give me, because it is too hard for me and I can not do it without help
Thank you in advance
You can store each value of your exploded string as key (if it's not an object nor array), it store only unique values. Then you have to just use array_keys() to get keys and sort returned array:
$rows = array(
'value1|value2|value5|value12|value25',
'value3|value5|value12|value14|value26|value32|value55',
'value1|value2|value14|value26|value31'
);
$results = array();
foreach ($rows as $row) {
$items = explode('|', $row);
foreach ($items as $item) {
$results[$item] = 0;
}
}
$results = array_keys($results);
sort($results, SORT_NATURAL);
Live demo on eval.in
There are two ways of doing this:
<?php
$str = 'value1|value2|value5|value12|value25';
$str1 = 'value3|value5|value12|value14|value26|value32|value55';
$str2 = 'value1|value2|value14|value26|value31';
//-- Method 1: Concat and make a single string and then explode and make a single array
$finalString = $str . '|' . $str1 . '|' . $str2;
print_r(array_unique(explode('|', $finalString)));
//-- Method 2: explode first and then merge into a single array
$strArr = explode('|', $str);
$strArr1 = explode('|', $str1);
$strArr2 = explode('|', $str2);
print_r(array_unique(array_merge($strArr, $strArr1, $strArr2)));
I have a column in a table of a MySQL database that stores numbers separated by commas. Here's an example:
,,322,,,,455,,,,698,,,,722,
There is a specific pattern:
The first number always has two commas before it
The numbers in between the first and last are separated by 4 commas
The last number is followed by a single comma
The numbers are ALWAYS separated by commas
I'm having some difficulty maintaining this pattern.. sometimes this field updates incorrectly resulting in too many or too few commas in certain places like so:
,,166,,,,845,,,,,,,,846,
I use this PHP to add/remove commas:
public function serializeArray($array) {
$string = ',';
foreach ($array as $obj) {
$string .= ',' . $obj . ',';
}
return $string;
}
public function unserializeArray($string) {
$array = explode(",,",$string);
unset($array[0]);
$array = array_values($array);
return $array;
echo "Array: " . print_r($array);
}
SQL to update column:
$query = $this->pdo->prepare(
'UPDATE `' . $this->table . '` SET
`team_ids` = :team_ids
WHERE `id` = :customer_id LIMIT 1;');
$query->bindParam(':customer_id', $customer_id, PDO::PARAM_INT);
$query->bindParam(':team_ids', $team_ids);
$query->execute();
What SQL can I use to UPDATE all of the values in the column to follow the specific pattern requirements mentioned above?
The issue here looks like you're missing a number, not that it is not following your pattern.
,,166,,,,845,,,,Missing No,,,,846,
Are you sure you want to delete this? I would instead focus on catching the null or blank number.
If so, it looks like you should be able to do a replace
Update TableName
Set NumberPattern = Replace(NumberPattern, ',,,,,,,,', ',,,,') --Repalce 8 ',' with 4 ','
I'm exploding a comma separated list into a variable named $tagArray and trying to write those values into incrementing rows of a table.
The code below works in so much as it creates the appropriate number of rows in my table but it only writes the first letter of the comma separating string (ie. if the string reads as "one, two, three", "o" is written in the first row and the remaining two rows have a blank value for column "blog_tag":
$tagInput = $_POST["blog_tags"];
$tagArray = explode(",",$tagInput);
$sql_2 = "INSERT INTO blog_tags (blog_tag, blog_id)
VALUES ";
$valuesArray = array();
foreach($tagArray as $row){
$tag = mysqli_real_escape_string($conxn, $row['blog_tag']);
$valuesArray[] = "('$tag','$lastID')";
}
$sql_2 .= implode(',', $valuesArray);
if (!mysqli_query($conxn,$sql_2)) {
die('Error: ' . mysqli_error($conxn));
}
This is spaghetti pieced together from various searches here and it's getting close but I can't figure out where it's grabbing just that first letter of the string.
Explode doesn't create associative arrays
$tag = mysqli_real_escape_string($conxn, $row); //instead of $row['blog_tag']
just replace your foreach with this for inserting values of array
foreach($tagArray as $row){
$a=mysqli_real_escape_string($row)
$sql_2 = "INSERT INTO blog_tags (blog_tag, blog_id) VALUES
('$a','$lastID') ";
}