Replacing content of block after generating clones using cloneBlock - PHPWord - php

Please can somebody be so kind to show me the syntax for using cloneblock in phpword.
So Ive got data in a MySQL DB, and for the single rows that I need to import into my word doc via phpword it works fine....to run my query and search and replace with template processor. BUT, now I want to insert multiple rows into my word document. I've researched and found that the cloneblock method is the answer. However I cannot get it working....currently my code runs but it doesn't seem to get to the second row.
I actually dnt get any error messages. My code executes fine...but the end display word file doesn't display fine....and if you see my code I got an echo statement...which echo's out in my browser exactly what I want "damaged" &"good", (as an example given of one of the row data) but that data doesn't get pulled into my word doc like that...it duplicates "damaged" , "damaged". .
$group_key=1;
do {   
//loop to increase my uuid  - ($repeatgroup')
$repeatgroup = $id."/"."trailer_repeat_group"."[".$group_key."]";
// query string
$trailer_repeat_grouping = mysqli_query($connect, "SELECT * FROM trailer_repeat_group LEFT JOIN main on trailer_repeat_group.PARENT_KEY = main.metainstanceID WHERE trailer_repeat_group.KEY_id = '$repeatgroup'");
$templateProcessor->cloneBlock('CLONEME', $trailer_count);
while ($row1 = mysqli_fetch_array($trailer_repeat_grouping)) {   
//this echo below I am using to test exactly what happends – independent of
//PHPword/templateprocessor
echo $rttc =  $row1['right_trailer_tyre_condition'];
//inserting  / searching / inserting values
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc);
}
// ending of loop / checking loop
$group_key++;
} while ($group_key <= $trailer_count);

I've done investigation and found the solution.
You're cloning same blocks N times:
$templateProcessor->cloneBlock('CLONEME', $trailer_count);
and then by doing fetch You're trying to replace right_trailer_tyre_condition with some value:
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc);
Issue is that You're replacing all placeholders.
But in fact You need to replace them one by one with different values.
Solution is to define 3rd argument that means count of items to replace.
Simply change it to be:
$templateProcessor->setValue("right_trailer_tyre_condition", $rttc, 1);

Related

PHP While loop Update stopping at first row

I made a while loop that will tell if there are items in the transaction history and will put it back in the inventory as the transaction ends but the problem is. It fetches an error called
Uncaught Error: Call to a member function fetch_assoc() on bool in
So I tried the query's one by one and it works.
I tried to experiment and comment the other query and adding a counter++; to tell if the loop works. The problem I found is that after the first if else the counter only add's 1 Where as if I only try this it loops 4 which is right
Query I tried to check the number of loops
$counter=0;
$sql="SELECT * FROM brb_backtransaction WHERE trans_uk='$curr_trans' ";
if($rs=$con->query($sql)){
while ($row=$rs->fetch_assoc()){
$counter++
}
}
It echoes 1234 so it's correct but when the first if else happen it only echo'es 1
$counter =0;
$sql="SELECT * FROM brb_backtransaction WHERE trans_uk='$curr_trans' ";
if($rs=$con->query($sql)){
while ($row=$rs->fetch_assoc()){
$item = $row['trans_item'];
$quan = $row['trans_quantity'];
$sqlsitem="SELECT itmQuantity FROM brb_inventory WHERE itmName='$item'";
if($rs=$con->query($sqlsitem)){
$quanrow = $rs->fetch_assoc();
$currquan = $quanrow['itmQuantity'];
$counter++;
}
I remove other query's as I think this is the problem I ran a total of 3 queries in the while loop.
For your while loop to work it needs access to your original data stream as stored in the $rs variable.
However, further down in your code you are replacing the contents of the $rs variable with a totally new data stream. Therefore, the while loop no longer has access to the original data stream as it is basically throw away.
To solve this, change the second instance to another variable name such as $rs2. That way you have two completely different variables for two different data streams.
With that said, your code is also open to injection attacks. I would recommend looking into PDO and prepared statements.
Also, Tangentially Perpendicular is correct in using SQL JOINS

Is there any solution to run the same query inside foreach with different variable, using PHP?

I'm running the following PHP code bellow. I have a string with seperated data (separated by ";"). I want to split this data into an array and with foreach I want to run the same INSERT sql query, changing with the array actual item only.
After I runned the code the succesfully message appearing. But as I described only one record get into the database (and only one time so if I do the same thing at the second time no more record added, also not the record before what is there in the database already too. (This is why I got so confused.)
String example: "email#email.com;email2#email2.com;"
The PHP code:
$connection = dbconnect();
$mail_addresses = explode(";",$_POST["mailaddresslist"]);
for($i = 0; $i < count($mail_addresses); $i++){
$query = "INSERT INTO `tablename` (`emsd_email`, `emsd_theme`, `emsd_timerdate`) VALUES ('".$mail_addresses[$i]."','". $_POST["themes"]."','".$_POST["emailsenddate"] ."');";
$connection->query($query);
}
print_note("E-mail successfully added!");
There is no any error message the code is running down. In the first time it create one record (just with the first item in the array), but after that the code doesn't make any effect at all. It no matters that how many times I run it does nothing. There's no more record appearing in the database.
I solved it. The problem was the record must have a unique id, and it must be Auto Increment. Now it works fine. :)*

Display MySQL Results in Different Sections of Page

I have a MySQLi query that returns all of the "assets" assigned to an employee based on their EmployeeID. This works great. The problem I'm facing is in the presentation.
I have an HTML table that has two sections: 1 for Hardware and 1 for software. What I am hoping to avoid is having to perform separate lookups that generate separate result sets for each type of asset. The end result needs to display as follows:
I can build the table just fine. The result sets contains a field of asset_type but I've not had any luck figuring out the code to use to iterate through my single result set. Is this even possible? Can I pull just the hardware assets from the result set with a while? Perhaps a
while($result['asset_type'] == "hardware"){
echo ""; // table row code
}
And then repeat the same thing later in my table code for asset_type software?
UPDATE 1
The code I've thought might work so far, but isn't doing anything, is
// SQL query
$q = "SELECT * FROM `assets_table` WHERE `emp_id` = '".$emp_id."'";
$r = mysqli_query($connect, $q);
$total_assets = mysqli_num_rows($r);
while($r){
if($r['category'] = "hardware"){
echo $r['asset_name']." - ".$r['hw_make']." ".$r['hw_model'];
}
}
I ended up going ahead and breaking out the query into multiple result sets and dealing with them that way. It'd be awesome if you could have a while() with a WHERE statement when iterating through result sets / arrays.

PHP/mySQL get_file_contents and update the column

I have a mySQL db table. One of the table columns contains URLs which point to different xml files on a remote server.
My goal is to read each URLs info and write the xml content into another column on the same record (line) respectively.
In my PHP code, I am able to get the URL correctly from mySQL database and I am able to get the XML content on remote server into a variable correctly.
But the issue is while I write the content to my table line by line. Some XML columns got update correctly and some XML columns are empty.
I am pretty sure each time the variable got content correctly because I am able to print out each individual content on screen.
Why are some content updating the column and some don't. All the XML strings have the same format. If I copied that content and updated the mysql table manually, it successfully wrote into the table.
At beginning I thought it was time issue so I add enough sleep time for my PHP code. it does't help. then I suspected my db datatype, so I changed the XML
column data type from VCHAR to TEXT and even LONGTEXT. it does't help either. Does any one have a clue?
part of my php code below...
$result = mysqli_query($con,"SELECT url_txt FROM mytable ");
//work with result line by line:
while($row = mysqli_fetch_array($result)) {
echo $url_content = file_get_contents($row['url_txt']);
//debug line below *******************************/
echo $URL=$row[url_txt];
//debug line above********************************/
mysqli_query($con,"UPDATE mytable SET xml_info='$url_content' where url_txt = '$URL' ");
}
Maybe try converting your XML to a native array and working with it that way:
$array = json_decode(json_encode(simplexml_load_string($url_content)),TRUE);

Why is my MySQL INSERT query inserting 3 identical rows?

I am trying to track what users are searching for on my site (from a simple search form on the front page) with PHP and MySQL.
At the end of all my queries I am using this query:
INSERT INTO `DiggerActivity_Searches` (
`SearchTerms`,
`SearchType`,
`NumResults`,
`Location`,
`Date`,
`Time`
) VALUES (
'SearchKeywords',
'SearchTypes',
'NumberOfResults',
'User'sLocation',
'CurDate',
'CurTime'
)
Now, whenever there is a new search keyword, it inserts 3 identical rows. However, if I refresh the page it only inserts 1 row, as it should.
The values are passed as a GET like this (I have mod rewritten the URL stuff):
http://www.mysite.com/Search-Category-Search_these_words
You might want to check first whether your script executes the query three times or the script is invoked three times (e.g. by some browser addons).
If you do not have a debugger installed you can use something like
function trace_log() {
static $magic = null;
if (is_null($magic)) {
$magic = uniqid();
}
$s = $magic . ' '. microtime(true) . ":\r\n";
foreach( debug_backtrace() as $d) {
$s .= ' '. $d['file'].'#'.$d['line']."\r\n";
}
file_put_contents('trace_log.txt', $s, FILE_APPEND);
}
...
trace_log();
mysql_query(....) // or stmt->execute() or whatever you use to execute the query.
If the first value of each log entry (the "magic" id) in trace_log.txt changes, your script is invoked multiple times. If it's the same for all three calls to trace_log(), your script executes the query three times.
Your table is missing a primary key. Id suggest a PK like search ID or something similar
Read more about this at Unique key - Wikipedia
Just know you are not alone in dealing with this strange bug.
This same problem showed up on my website in the past few days as well. The only thing I recently added was a third party banner ad.
SOLUTION: I commented out the banner ad script (Hint: from search engine that starts with a G) and everything was good again.
I was just going to make a comment put need more reputation to so...
Anyway, similar happened to me. Turns out I was echoing out debug information above the header causing the browser to reload automatically. Easiest way to check is just use
<script type="text/javascript">alert("loading");</alert>
in the header and see how many times you see it.

Categories