PHPExcel - read comment from a cell? - comments

Sorry, for my bad english.
I have written the following code.
foreach ($sheetData as $theData)
if ($theData['A'] != "ID")
{
$id = $theData['A'];
$vorname = $theData['B'];
$nachname = $theData['C'];
$bew_foto = $theData['D'];
$emailadr = $theData['E'];
$sql = "INSERT INTO datensatz (
id,
vorname,
nachname,
emailadr)
VALUES (
$id,
'$vorname',
'$nachname',
'$emailadr')";
$ergebnis = $mysqli->query($sql);
echo "Datensatz erfolgreich eingetragen!<br>";{
}
}
How can I make it, that I can read a comment in (to example) column B and write it in a database or give it out with an echo? I will read the comments in all rows 'nachname' (C). How can I make this?

To read a comment in cell A2, it's as easy as
$objPHPExcel->getActiveSheet()
->getComment('A2')
->getText();

Related

Codeigniter update_batch in Core PHP

everyone.
In the codeigniter there is update_batch function by using it we are able to bulk update multiple rows.
$this->db->update_batch('table_name', $update_data_array, 'where_condition_field_name');
I want similar functionality in core PHP in one function or in one file. Is there any workaround?
Is there any way to extract update_batch function from Codeigniter in one file/function?
I tried to extract this function but it is very lengthy process and there will be many files / functions should be extracted.
Please help me in this regard
Thanks in advance
You can also insert multiple rows into a database table with a single insert query in core php.
(1)One Way
<?php
$mysqli = new mysqli("localhost", "root", "", "newdb");
if ($mysqli == = false) {
die("ERROR: Could not connect. ".$mysqli->connect_error);
}
$sql = "INSERT INTO mytable (first_name, last_name, age)
VALUES('raj', 'sharma', '15'),
('kapil', 'verma', '42'),
('monty', 'singh', '29'),
('arjun', 'patel', '32') ";
if ($mysqli->query($sql) == = true)
{
echo "Records inserted successfully.";
}
else
{
echo "ERROR: Could not able to execute $sql. "
.$mysqli->error;
}
$mysqli->close();
? >
(2)Second Way
Let's assume $column1 and $column2 are arrays with same size posted by html form.
You can create your sql query like this:-
<?php
$query = 'INSERT INTO TABLE (`column1`, `column2`) VALUES ';
$query_parts = array();
for($x=0; $x<count($column1); $x++){
$query_parts[] = "('" . $column1[$x] . "', '" . $column2[$x] . "')";
}
echo $query .= implode(',', $query_parts);
?>
You can easily construct similar type of query using PHP.
Lets use array containing key value pair and implode statement to generate query.
Here’s the snippet.
<?php
$coupons = array(
1 => 'val1',
2 => 'va2',
3 => 'val3',
);
$data = array();
foreach ($coupons AS $key => $value) {
$data[] = "($key, '$value')";
}
$query = "INSERT INTO `tbl_update` (id, val) VALUES " . implode(', ', $data) . " ON DUPLICATE KEY UPDATE val = VALUES(val)";
$this->db->query($query);
?>
Alternatively, you can use CASE construct in UPDATE statement. Then the query would be something
like:
UPDATE tbl_coupons
SET code = (CASE id WHEN 1 THEN 'ABCDE'
WHEN 2 THEN 'GHIJK'
WHEN 3 THEN 'EFGHI'
END)
WHERE id IN(1, 2 ,3);

how to use order by random in codeigniter

While Searching I want to show the paid customers firstly, and then rest of customers list
but the problem is I want to show by random
for Example. paid customers should not mix with others.
Can anyone tell what will be query?
please help me!
I am using codeigniter
Example:
function randomval()
{
$this->db->order_by('id', 'RANDOM');
$this->db->limit(1);
$query = $this->db->get('tblname');
return $query->result_array();
}
Mysql query for your need if i understood well
SELECT `featured`,group_concat(`id` order by rand() ) as `id` FROM `dbc_posts` where `status` = 1 GROUP By `featured` ORDER BY `featured` DESC
now with php
$results = $this->db->query("SELECT `featured`,group_concat(`id` order by rand() ) as `id` FROM `dbc_posts` where `status` = 1 GROUP By `featured` ORDER BY `featured` DESC")->result_array();
$paid = $results[0];//featured = 1
// comma seprated ids of the paid people e.g :- 3,7,1,26,92 are available in
$paidusers = $results[0]["id"];
//seprate them by
$paidusers = explode(",",$paidusers);
foreach($paidusers as $paiduser)
{
$row = $this->db->get_where("dbc_posts", array("id"=> $paiduser))->row();
print_r($row );
echo "<br>";
}
// do same for unpaid
$unpaid = $results[1];//featured = 0
$unpaidusers = $results[1]["id"];
//seprate them by
$unpaidusers = explode(",",$unpaidusers);
foreach($unpaidusers as $unpaiduser)
{
$row = $this->db->get_where("dbc_posts", array("id"=> $unpaiduser))->row();
print_r($row );
echo "<br>";
}
Ask me if anything goes wrong
Set featured = 1 for paid and featured = 0 for unpaid customers in database. Then use the query
mysql_query("SELECT * FROM dbc_posts WHERE status = 1 ORDER BY featured DESC, RAND() LIMIT 1");

Multiple array manipulations and merging

I am an amateur programmer that needs the help of a real one to resolve this beautiful problem, because I must admit that I am really stuck on this one!
In my database I have a « tslines » table that contains a value (sum_week) for a given week(startdate) and a given contract(contract_id)
The fields that are important are : sum_week, user_id , startdate and contract_id
I also have a « users » table, the important values are « first_name, last_name »
I have many workers that have worked on a contract, at different times (startdate, represents the first day of the week)
Example (table below): I can have 3 lines for worker A, and 2 lines for worker B
For some week(startdate), it can happend that no one worked on the contract
I want to show a table with those informations, for contract_id=3(ex) (this field is in tslines table) :
sum_week is a field, I don't want to recalculate with a SQL query
I don’t want to run a query for each weeks to check for each user if he worked on a contract because that would become a problem if I have ex : 30 weeks with 30 users that worked on the project..
I started by building an array of all possible « startdate »
//Selects min and max startdate of the tslines, use $dates->maxdate and ->mindate
$dates = $contract->tslines()->whereIsOfficial(true)->select(DB::raw('MAX(startdate) as maxdate, MIN(startdate) as mindate'))->first();
//Define first date declared in tslines
$loopdate = Carbon::parse($dates->mindate);
$maxdt = Carbon::parse($dates->maxdate);
//While loop to create array of date ranges from min to max
$date_count = 0;
$daterange = array();
while($loopdate->gt($maxdt) == false)
{
$daterange[] = $loopdate->format('Y-m-d');
$loopdate->addDays(7);
$date_count++;
}
I know I have to do some array manipulations but I really don’t know from where to start, even witht the queries..
I can get all the related tslines of contract by doing:
$contract->tslines()->get()
But I dont't know how to build an array that contains user information and all the startdate (even if he didn't work that week)
Can anybody give me some hints.. It would be greatly appreciated!!
Thanks in advance!
Raphaël
Let's start from what we know.
We know which users have worked on which contracts and on what date.
With your function above, we have the max date and the min date a user has started working on a contract.
Solution:
$tslines = $contract->tslines()->orderBy('user_id','ASC')->orderBy('startdate','ASC')->get();
//I didn't see any relationship calls to the user's object, so you'll have to add one of your own. I am assuming, your `tslines` has a relationship `user` here.
$userListResult = $contract->tslines()->with('user')->orderBy('user_id','ASC')->select(\Db::raw('distinct("user_id")')->get();
$dates = $contract->tslines()->whereIsOfficial(true)->select(DB::raw('MAX(startdate) as maxdate, MIN(startdate) as mindate'))->first();
$minDate = Carbon::parse($dates->mindate);
$maxDate = Carbon::parse($dates->maxdate);
//we flatten the array for future use.
$userList = array();
foreach($userListResult as $l)
{
$userList[$l->user_id] = $l->user->first_name.' '.$l->user->last_name;
}
//Assuming you are printing a table in blade
<table>
<?php
//Print the table headers
echo"<tr>
<td>User</td>";
$currDate = clone($minDate);
do
{
echo "<td>".$currDate->format('Y-m-d')."</td>";
$currDate->addDay();
}
while($currDate->diffInDays($maxDate) !== 0);
echo "</tr>";
//Print each user's row
foreach($userlist as $userid => $username)
{
echo "<tr>
<td>
$username
</td>";
$currDate = clone($minDate);
//loop through all the dates in range (min to max date)
do
{
$foundDate = false;
//We check if user has worked on that day
foreach($tslines as $row)
{
if($row->user_id === $userid && $row->startdate->format('Y-m-d') === $currDate->format('Y-m-d'))
{
//Print result if startdate & userid matches
echo "<td>{$row->sum_week}</td>";
$foundDate = true;
//Get out of the loops
break;
}
}
if(!$foundDate)
{
echo "<td>X (didn't work)</td>";
}
$currDate->addDay();
}
while($currDate->diffInDays($maxDate) !== 0);
echo "</tr>";
}
?>
</table>

Magmi overwriting position of products in category

I'm using Magmi to import products into my Magento store. Categories are created on the fly and products are imported. All is working well.
Except for one thing: each time I run a Magmi import, the position of the product in the Magento category is set to 0. This way I cannot sort my products on position.
I have searched the Magmi wiki and github for someone who has run into the same problem, but didn't find anything.
Anyone familiar with this issue and is there a way to avoid it?
I wait too long an answer and do it myself, here is a fix:
my fix works other way - category positions clear only if you add $item["category_reset"] == 1; param to product params.
:1280 sting(in current magmi version) or find the public function assignCategories($pid, $item) in magmi_productimportengine.php.
ater
$cce = $this->tablename("catalog_category_entity");
$ccpt = $this->tablename("catalog_category_product");
add next code:
$sql = "SELECT $ccpt.*
FROM $ccpt
JOIN $cce ON $cce.entity_id=$ccpt.category_id
WHERE product_id=?";
$currentPositions = $this->selectAll($sql,$pid);
then change category reset:
if (!isset($item["category_reset"]) || $item["category_reset"] == 1)
{...}
to
if (isset($item["category_reset"]) && $item["category_reset"] == 1)
{
$sql = "DELETE $ccpt.*
FROM $ccpt
JOIN $cce ON $cce.entity_id=$ccpt.category_id
WHERE product_id=?";
$this->delete($sql, $pid);
$currentPositions = array();
}
after this change block with positioning
foreach ($catids as $catdef)
{...}
to:
// find positive category assignments
if (is_array($currentPositions) && count($currentPositions)) {
foreach ($currentPositions as $currentPosition) {
$catPos[$currentPosition['category_id']] = $currentPosition['position'];
}
}
foreach ($catids as $catdef)
{
$a = explode("::", $catdef);
$catid = $a[0];
if (count($a) > 1 && $a[1] != 0) {
$catpos = $a[1];
}
else {
if (isset($catPos[$catid]) && $catPos[$catid] != 0) {
$catpos = $catPos[$catid];
}
else {
$catpos = "0";
}
}
$rel = getRelative($catid);
if ($rel == "-")
{
$ddata[] = $catid;
}
else
{
$cdata[$catid] = $catpos;
}
}
if you dont import position, your current position will save. If it 0, it stay 0.
for clear actual position - add param to product item:
$item["category_reset"] == 1;
or change string back:
if ($item["category_reset"] == 1)
{ ....}
to:
if (!isset($item["category_reset"]) || $item["category_reset"] == 1)
{...}
Only a comment but since I'm a long-time reader but never setup an account and can't leave a comment directly with no rep. I know this is an old post, but I just found it and used AlexVegas's code above (thank you!). Worked almost fine for me, but in my case I still wanted the categories to fully reset to only what was in my Magmi import but I wanted the positions to remain intact. As-is above, the categories only append to the existing unless you use the category_reset column in your import, and if you do that it also resets the position.
If you're like me and want only the position to remain intact, but allow Magmi to overwrite the categories each time, use Alex's code above but tweak it a little
Where he says to change
if (!isset($item["category_reset"]) || $item["category_reset"] == 1)
{...}
to
if (isset($item["category_reset"]) && $item["category_reset"] == 1)
{
$sql = "DELETE $ccpt.*
FROM $ccpt
JOIN $cce ON $cce.entity_id=$ccpt.category_id
WHERE product_id=?";
$this->delete($sql, $pid);
$currentPositions = array();
}
Don't change it. It's that simple. In his code it prevents the category reset unless the column is specified, which is why the if statement gets changed. If the column exists, it also wipes out the currentPositions array that stores the current positions within the categories so those get reset as well.
If you want to append to the categories unless category_reset is in your import, but don't want to overwrite the positioning, use Alex's code as it is above in his answer but leave out
$currentPositions = array();
That way it won't overwrite the array that is storing the positions within the categories
Not an actual solution-
You can try using this plugin
http://www.magentocommerce.com/magento-connect/c3-category-position-import-export-extension.html/
You can ignore UPDATE position if exist
category creator/importer v0.2.5
at line 1248 replace with
if (count($inserts) > 0) {
$sql = "INSERT IGNORE INTO $ccpt (`category_id`,`product_id`,`position`) VALUES ";
$sql .= implode(",", $inserts);
// $sql .= " ON DUPLICATE KEY IGNORE";
$this->insert($sql, $data);
unset($data);
}
The Magmi wiki specifically mentions item positioning functionality here See quoted text below. This seems to describe exactly the functionality you are looking for? I have not tested it myself.
Quote:
Item positioning
From magmi 0.7.18 , category_ids column has been enhanced with item positioning. This feature is also supported in category importer from version 0.2+ (since category importer plugin is roughly a category_ids generator)
Sample
store,sku,....,categories
admin,00001,.....,cat name with \/ in the name and positioning::3
<= here we "escaped" the tree separator with a backslash , the category will be created as "catname with / in the name and positioning"
sku 00001 will be set with position 3 in the category
End quote

PHP - How to accomplish this if?

I am creating an order cart.
On the page that displays the cart, it checks if a value stored in the session $order corresponds with an id of a row in a mysql table. If this match exists, then the corresponding row is returned.
Within this process, I am trying to retrieve the quantity value stored in the session $quantity that corresponds to the id of the row in the table.
Each value in $order and $quantityis assigned a name, which is the id of the item they were added from.
This is the code that adds the order to the cart:
if (isset($_POST['action']) and $_POST['action'] == 'Order')
{
// Add item to the end of the $_SESSION['order'] array
$_SESSION['order'][$_POST['id']] = $_POST['id'];
$_SESSION['quantity'][$_POST['id']] = $_POST['quantity'];
header('Location: .');
exit();
}
This is the code on the cart page:
foreach ($order as $item)
foreach ($quantity as $amount)
{
mysql_data_seek( $productsSql, 0); //<- this line, to reset the pointer for every EACH.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
if ($item == $itId)
{
$pageContent .= '
<tr>
<td>'.$itDesc.'</td>
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
<td>R'.number_format($itPrice1*$amount, 2).'</td>
</tr>
';
}
}
}
This row is producing a syntax error:
<td>'.if ($item[''.$itId.''] == $amount[''.$itId.'']) {echo $amount}.'</td>
What is the problem here for starters?
Secondly, how would I need to do to accomplish the task that I am facing?
Any input on this would be greatly appreciated!
Could you try this?
<td>'.($item[$itId] == $amount[$itId] ? $amount : '').'</td>
This is a ternary operator, look at http://en.wikipedia.org/wiki/Ternary_operation
You can't simply add conditional statements like that while you're building a string.
You can do this, however
<td>' . ($item[$itId] == $amount[$itId]) ? $amount : null . '</td>
but you should use a more legible method.
Another issue you may get is if $amount is an array, you won't be able to print it as a string. If, however, $amount is an object with ArrayAccess interface, you can print it with the __toString() method; but that's another story.
The code for creating the cart page has several issues.
You walk over items and over quantities, which will probably give you duplicate outputs.
$item is a plain string, so I wonder what $item[$itId] is supposed to do?
You walk over your complete result set several times which actually is not necessary. I really hope that "$productSql" isn't a "select * from product", otherwhise this might get REAL slow in production mode.
I suggest creating a good SQL for getting the data and using this as a basis for filling the page:
// note this has SQL-injection issues, so you really need to make sure that $order contains no crap
$productsSql = mysql_query("select * from product where id in (".join($order, ',').")");
// you now have a result set with all products from your order.
while($row = mysql_fetch_assoc($productsSql))
{
$itId = $row['id'];
$itDesc = $row['desc'];
$itPrice1 = $row['price1'];
// session contains the quantity array mapping ID -> Quantity, so grab it from there
$itQuantity = $quantity[$itId];
// finally calculate the price
$itPrice = number_format($itPrice1*$itQuantity, 2);
// now you have all data for your template and can just insert it.
// if you use double quotes you can put the $xyz into the string directly
$pageContent .= "
<tr>
<td>$itDesc</td>
<td>$itQuanty</td>
<td>R $itPrice</td>
</tr>
";
}

Resources