Reading all the values except 0 - php

I have this module where the user first generates the blank CSV, which only contains the headers, that is six fields. Out of those 6 fields, 3 fields are filled while the other 3 are empty.
for example:
A, B, C, D, E, F. So the values that A, B, C contain are coming from database using the query.
Now, when user fills in D, E, F and uploads the the sheet, a problem arises. I had set this condition that whenever D & E & F are 0, it will delete that particular ID, that is A. So the particular entry with 0,0,0 will be deleted. It worked fine for a while, but now the deletion has stopped working, I don't know why. I figured out a lot, but couldn't get the solution.
Here are my code snippets.
$sql = "SELECT query......";
$outlet_locality_array = $DB->query($sql);
if(isset($outlet_locality_array[0]->minimum_order)
&& isset($outlet_locality_array[0]->delivery_time)
&& isset($outlet_locality_array[0]->delivery_charge))
{
if(($outlet_locality_array[0]->minimum_order == 0)
&& ($outlet_locality_array[0]->delivery_time == 0)
&& ($outlet_locality_array[0]->delivery_charge == 0))
{
$condition_check = array();
$condition_check['outlet_locality_id'] = $outlet_locality_array[0]->outlet_locality_id;
$DB->delete(PLATFORM_OUTLET_LOCALITIES,$condition_check);
}
}
Now when I tried debugging, the first IF statement executed, but the second IF statement did not execute. When I debug the variable $outlet_locality_array, I get all the values except the 0. And when I see the response that ajax sends, the data there shows me that the csv file that was uploaded has a 0.
So where am I missing out???
the response that i get is this:
csv_data:Location Id,City Name,Location Name,Minimum Order Amount,Delivery Time,Delivery Charge
5,East,Park,213,69,12123
6,East,Garden,2782,123,234
12,East,Phase 2,12345,345,2345
837,West,College,0,0,0
This is when I debug the array $outlet_locality_array
Array( [0] => stdClass Object ( [outlet_locality_id] => 44104 [minimum_order] => 213 [delivery_time] => 69 [delivery_charge] => 12123 ))
Array( [0] => stdClass Object ( [outlet_locality_id] => 44105 [minimum_order] => 2782 [delivery_time] => 123 [delivery_charge] => 234 ))
Array( [0] => stdClass Object ( [outlet_locality_id] => 44106 [minimum_order] => 12345 [delivery_time] => 345 [delivery_charge] => 2345 ))

Related

PHP reading CSV files in an odd order

I'm using the the League CSV library, but the same exact thing happens when I use built in PHP functions. Here is my spreadsheet:
ID column A column B column C
123 apple orange pear
And here is my code:
$stmt = (new Statement())
->offset(0)
->limit(2)
;
$records = $stmt->process($csv);
foreach ($records as $record) {
print_r($record);
}
Finally, here is the output. Notice, the ID value (123) is hanging off to the left. I'm not even sure what that is supposed to mean.
Array
(
[0] => ID
[1] => column A
[2] => column B
123 [3] => column C
[4] => apple
[5] => orange
[6] => pear
)
Edit: Here is the raw CSV file. Newline character is possibly a carriage return?
ID,column A,column B,column C
123,apple,orange,pear
This was really lame. Since I'm on a Mac, I needed to add this line to the top of the script:
ini_set('auto_detect_line_endings',TRUE);

usort of session array not outputting as expected

I have a grid of img squares that can be dragged into any order using the sortable library. Each img is a visual representation of a result from a mySQL db query that selects any image that shares an 'imageparent' identifier. The order they're presented in the grid is taken from the 'imageorder' column in the database and starts at 0 and works in sequence up to the nth number of images returned.
The purpose of dragging the img grid is to be able to change the 'imageorder' index. On completion of the drag, the sortable library POSTS an 'imageorder' var by ajax to service.php and is received correctly. So rather than the original 0,1,2,3,4,5,6,7 order of the original, it sends a string like 2,1,0,3,4,5,7,6. Not too hard to grasp. After I switch the order the orderList var sent to service.php is always correct, but the array I end up sending to the db and setting as my session var becomes a little garbled in order after the second or third drag and I'm not quite sure why.
Code Examples and Comments
$_SESSION['selectedCsImages'] Array structure:
[0] => Array
(
[imagename] => "Title"
[imageorder] => 0
[imageid] => 43
)
[1] => Array
(
[imagename] => "Title"
[imageorder] => 1
[imageid] => 21
)
[2] => Array
(
[imagename] => "Title"
[imageorder] => 2
[imageid] => 3
)
etc...
Services.php extract:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}
// Turn the orderList posted into an array
$removeChars = array('"','[',']');
$orderList = str_replace($removeChars, "", $_POST['order']); // POST received fine.
$listArray = explode(",",$orderList);
// Retrieve the session array
$sorting = $_SESSION['selectedCsImages'];
/* My logic is that I compare the $sorting array to $listArray and reorder $sorting by 'imageorder' to match $listarray */
usort($sorting, function($a, $b) use ($listArray) {
return array_search($a['imageorder'], $listArray) - array_search($b['imageorder'], $listArray);
});
/* I now have a $sorting array that (sometimes, hence the problem) matches the order that the images had just been dragged into by the user. Typically, as I mentioned above, it's correct after the first drag, but not always after the second or third where it creates a new order that I can't see a pattern or logic in. */
/* Had there not been errors with the usort function, I (would) have a $sorting array in the order I want but with imageorder values referring to pre-sorting. I iterate through the array and set each key to 0, 1, 2, etc. so that I have an array in the correct order and with each imageorder correctly stating its place.*/
$i = 0;
foreach ($sorting as $key => $value) {
$sorting[$key]['imageorder'] = $i;
$i++;
}
/* The information is attempted to be sent to the db and, on success I update the session var */
// Database code (runs succesfully and updates the db as per the image orders found in the $sorting array)
$_SESSION['selectedCsImages'] = $sorting;
Debugging:
From debugging, it appears that something happens with the usort function when I call this page from ajax for the second or third time. Everything after this follows through fine and processes the correct or incorrect order as per expectations. The orderList var posted by sortable is correct each time. I'd provide a sample of the $sorted var after usort each time but it's as simple to describe it as the above array example in an order I didn't specify after dragging and I can't see a pattern in the seemingly random order it outputs.
From researching, I had thought that it was an issue with session vars being retained until the page is refreshed but it appears that the ajax call to services.php should refresh the $_SESSION['selectedCsImages'] var. I had also read that, perhaps, I was unknowingly using referenced array values and - as I source from a session var to a new array and, ultimately, save back to this session var from this array - I may have created some messy referencing feedback. However, I tried using $sorted = (array)clone(object)$_SESSION['selectedCsImages']; before attempting usort and the results didn't change.
PHP error logs are showing nothing.
Updates:
Per the suggestion of #Ayaou, I've checked the output of $listArray and am getting some unexpected results. I'd wrongly assumed that as the posted $orderList was correct, that the exploded array would not be a culprit.
Here's the output of print_r($listArray) after completing the following order swaps of 16 img elements: 1st with 2nd, 2nd last with last,6th with 7th:
1st and 2nd:
(
[0] => 1
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 14
[15] => 15
)
last and 2nd last:
(
[0] => 1
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 5
[6] => 6
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 15
[15] => 14
)
6th with 7th:
(
[0] => 1
[1] => 0
[2] => 2
[3] => 3
[4] => 4
[5] => 6
[6] => 5
[7] => 7
[8] => 8
[9] => 9
[10] => 10
[11] => 11
[12] => 12
[13] => 13
[14] => 15
[15] => 14
)
I was progressing with the idea that $listArray would show a sequential 0,1,2,3,etc. each time with only the two swapped items showing order changes. As it's not, I'll look back again at $orderList and check if my sortable library is updating the orders it's obtaining correctly from the updated session var. Older order swaps are being retained somewhere along the chain where they shouldn't.
The solution is on your sortable form (on the front end), so instead of sending the imageorder on your 'order' post data, send the imageid index.
Then change your sort callback like this
//Use imageid index instead of imageorder
usort($sorting, function($a, $b) use ($listArray) {
return array_search($a['imageid'], $listArray) - array_search($b['imageid'], $listArray);
});

How to append a serialized string that already exists in the database

I have just started to learn about serialization and I have a question that I cannot seem to find a simple explanation to.
Say I had a table called week and inside week I had 3 columns with the third column containing a bunch of serialized meal IDs like so stored in my database:
INSERT INTO `week` (`week_id`, `meal_code`, `meal_id`) VALUES
(1, 'week12016', 'a:6:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;}');
But later I want to append another meal_id to the existing string but not update any other column so it reads
(1, 'week12016','a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;}')
I have tried in a php file to store the following
$food=array("7");
$sfood=serialize($food);
Then trying to add the 7 to the existing meal_ids in the week table
mysqli_query($conn,"UPDATE week
SET meal_id ('$sfood')");
//if entry into the database is successful, confirm with a alert popup and refresh the home page
if(mysqli_affected_rows($conn) > 0){
//header("location: admin.php");
header("refresh:0; url=admin.php");
echo "<script type='text/javascript'>alert('Upload Successful!')</script>";
exit;
But when I check my database, nothing has changed.
What am I doing wrong, is it even possible to do what I am trying to achieve?
You have to read the column from your table row. Unserialize it into a PHP variable and then add a new occurance to it.
Then serialize the new array and store it back to your database
// SELECT from table
$s = 'a:7:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;}';
$d = unserialize($s);
print_r($d);
$d[] = 99;
print_r($d);
$s2 = serialize($d);
echo $s2;
// UPDATE table row
RESULTS
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
)
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
[6] => 7
[7] => 99
)
a:8:{i:0;i:1;i:1;i:2;i:2;i:3;i:3;i:4;i:4;i:5;i:5;i:6;i:6;i:7;i:7;i:99;}
Storing data like this is not recommended, as it makes this data impossible to process using queries

check if a value exist in array from database query

I am trying to build a website that will display the text in multiple languages.
I have a table 'text' with all the languages. If the text does not exist in the chosen language it has to display the default language.
query SELECT * FROM text WHERE TextId = 10
results in
Id TextId LanguageId Text
10 10 1 first name
13 10 2 名前
If I r_print this result I get something like this
Array ( [0] => Array ( [0] => 10 [Id] => 10 [1] => 10 [TextId] => 10 [2] => 1 [LanguageId] => 1 [3] => first name [Text] => first name )
[1] => Array ( [0] => 13 [Id] => 13 [1] => 10 [TextId] => 10 [2] => 2 [LanguageId] => 2 [3] => 名前 [Text] => 名前 ) )
How can I check that LanguageId 2 exist in this array ?
the problem is that it is possible that TextId 2 and Id 2 can also exist in this array.
Is this possible to do with in_array()?
Here is a function that can check if LanguageId equals a special value .
function isLanguageIdExists($yourArray , $LanguageId){
$exists=false;
foreach($yourArray as $array){
if(isset($array['LanguageId'])&& $array['LanguageId'] == $LanguageId){
$exists=true;break;
}
}
return $exists;
}
$exist = isLanguageIdExists($yourArray , 2);//return true or false
You can check by isset the key and match the value in php.
$dataArray = array(
0 => array(0 => 10 ,'Id' => 10, 1 => 10, 'TextId' => 10, 2 => 1, 'LanguageId' => 1),1 => array(0 => 10 ,'Id' => 10, 1 => 10, 'TextId' => 10, 2 => 1, 'LanguageId' => 1)
);
foreach($dataArray as $value) {
if(isset($value['LanguageId']) && $value['LanguageId'] == 2) {
echo 'language ID 2 is available';
}
}
Working Demo
After giving this some more thought I came up with a maybe not so elegant solution.
Instead of getting an array back I modified the SQL Query to give one row back with the default language (English) and a user selected language (Japanese).
It uses two left joins. This shows that I received (some) training in SQL but am really not at ease with multidimensional arrays.
Query
def_text = text in default language
usr_text = text in user chosen language
$table01 = "text";
$query="SELECT $table01.TextId,
text_def.Text as def_text,
text_usr.Text as usr_text
FROM $table01
LEFT JOIN $table01 as text_def ON $table01.TextId = text_def.TextId AND text_def.LanguageId = $_SESSION[default_language]
LEFT JOIN $table01 as text_usr ON $table01.TextId = text_usr.TextId AND text_usr.LanguageId = $_SESSION[language]
WHERE $table01.TextId=$mess;";
after getting back the results it is easy to check with isset() or empty() to see if the text is available in the user selected language

SQL to insert data read from excel using PHPExcel

I am currently working on reading a excel using php and storing those records in mysql.I came across PHPExcel,a bunch of very nice plugin classes which can very easily help to achive it.I tried to search through but did not something similar to my use case.Also,not very good at object oriented PHP and I am short of time in doing this.
First Name Last Name Nationality Gender Date of Birth Time of Birth Date/Time PHP Coder Sanity %Age
Above are my sample database columns and First row of my excel sheet.I want to match the column names of my rows before inserting them to database.
My code till now gives me a 2 dimensional array in which I get the column names and values.The reason I want to check the column name before inserting is that,my excels can be in any order of the column names.
I used exampleReader01 in the package and some SO reference to achieve this.
$headingsArray = $objWorksheet->rangeToArray('A1:'.$highestColumn.'1',null, true, true, true);
$headingsArray = $headingsArray[1];
$r = -1;
$namedDataArray = array();
for ($row = 2; $row <= $highestRow; ++$row) {
$dataRow = $objWorksheet->rangeToArray('A'.$row.':'.$highestColumn.$row,null, true, true, true);
if ((isset($dataRow[$row]['A'])) && ($dataRow[$row]['A'] > '')) {
++$r;
foreach($headingsArray as $columnKey => $columnHeading){
$namedDataArray[$r][$columnHeading] = $dataRow[$row][$columnKey];
}
}
}
Now I want some help how can I insert this in the right column.
My array is like this
Array
(
[0] => Array
(
[First Name] => Mark
[Last Name] => Baker
[Nationality] => British
[Gender] => M
[Date of Birth] => 19-Dec-60
[Time of Birth] => 1:30
[Date/Time] => 22269.0625
[PHP Coder] => 1
[Sanity %Age] => 32%
)
[1] => Array
(
[First Name] => Toni
[Last Name] => Baker
[Nationality] => British
[Gender] => F
[Date of Birth] => 24-Nov-50
[Time of Birth] => 20:00
[Date/Time] => 18591.83333
[PHP Coder] =>
[Sanity %Age] => 95%
)
[2] => Array
(
[First Name] => Rachel
[Last Name] => Baker
[Nationality] => British
[Gender] => F
[Date of Birth] => 7-Dec-82
[Time of Birth] => 0:15
[Date/Time] => 30292.01042
[PHP Coder] =>
[Sanity %Age] => 100%
)
)
Hope I am clear.
Thanks for your time.
If I can assume that your Excel column header names never change, why not simply use a mapping array?
$dbMapping = array(
'col1' => header1,
'col2' => header2,
..
'colN' => headerN
);
So when you're ready to insert to the database, you iterate through each row with the column header names you already have in your 2D array and pass it into your mapping array i.e. $dbMapping['col1'] and that will get you your header name and you can grab the correct row value.
psuedo
foreach ($rows as $row) {
insert into col1, col2, ... colN
values ($rows[$dbMapping['col1']], $rows[$dbMapping['col2']], ...
}
Of course it would be in your best interest to use parameterized values.

Categories