Iterating through FileMaker record set - php

I'm new at FileMaker and trying to get data out via the API.
The issue I'm having is when I create a newFindCommand and execute it the resulting record set contains as many rows as there are in the layout but each row is the same. More specifically, each row is a copy of the FIRST row in the database.
E.g. I'm looking for products with a product code like 'XXX', of which there should be 7. I get 7 rows back but each one is the same product.
I've looked a couple of tutorials online and they do exactly the same operations I do so I'm lost as to why my results come out this way.
This is my code for this problem. I haven't been able to track the cause myself yet.
$findCommand = $productsFM->newFindCommand($productsLayout);
$findCommand->addFindCriterion('Product Code', 'XX123');
$findCommand->addSortRule('Product Code', 1);
$result = $findCommand->execute();
if (FileMaker::isError($result)) {
echo "<p>Error: " . $result->getMessage() . "</p>";
exit;
}
$records = $result->getRecords();
foreach($records as $record) {
echo $record->getField('Product ID'); // get the same code for each iteration here
}
Any advice?
Edit:
The layout $productLayout mentioned above refers to the Items layout.
Here is a brief breakdown of the ER diagram for the Items table.
Table: Items
Family ID Item ID GUID
Table: Item Options
Item ID Description GUID
Table: Pricing ~ Item
Family ID Item ID Item Option Qty
Table: Quantity
Qty Item ID GUID

I fixed this be trying to add the api PHP files again, operating on the assumption I had something wrong. When I added the files and ran the code I got several errors about using deprecated operators at various lines in the FileMaker API.
It turns out several lines use the old =& when creating objects and this was the cause of the errors.
For all but one of those errors you can just remove the '&' and everything is OK.
But for one of the lines (I think it was around line 72), if you correct it by removing the '&' the API will start returning incorrect results. This is where I went wrong the first time around.
The only two options I could see were to drop down to an older version of PHP where the =& operator is not deprecated or suppress the warnings in the php.ini.
I opted for the latter:
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

Related

Replacing content of block after generating clones using cloneBlock - PHPWord

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);

foreach loop returns nothing

I am trying to pull user data from a Cart66 table I have and put it into a shortcode in wordpress. $account is an integer pulled from session data. The code below returns nothing.
$account =Cart66Session::get(Cart66AccountId);
global $wpdb;
$fname=$wpdb->get_results("SELECT * FROM 'vfp_cart66_accounts' WHERE id = '$account', ARRAY_N");
foreach ($fname AS $row)
{
echo $row;
}
This returns "Array"
return $fname;
Ok firstly, maybe I am the only one who saw this, and it could be the source of your entire problem, but you have a misplaced double quote, at the end of your SQL line, which should live at the end of the actual SQL string, not after the requested return type:
// at the end of this line you have: '$account', ARRAY_N");
// this should be changed to: '$account'", ARRAY_N);
$fname=$wpdb->get_results("SELECT * FROM 'vfp_cart66_accounts' WHERE id = '$account', ARRAY_N");
Even the first person who answered the question did not correct you, so I am assuming he didn't see it either. Secondly, using single quotes (') to escape a table name is invalid. If it is quoted at all, use backticks (`). Single quotes indicate a string, not an database, table, or field, all three of which should only be quoted with backticks (except on utility queries like SHOW). Use this instead:
select * from `vfp_cart66_accounts` where id = '$account'
Thirdly, as your commenters point out, you could be vulnerable to SQL Injection. Make sure to use the tools that WP gives you, and do this, or similar, instead:
$fname = $wpdb->get_results(
$wpdb->prepare(
'select * from `vfp_cart66_accounts` where id = %d',
$account
),
ARRAY_N
);
Lastly, you are requesting an array from the DB, but you are trying to echo it as if it were a scalar value. This explains why printing the value of $row yields "Array". When you convert an array() to a string, by default, you get "Array", since arrays can be complex data that may not be beautifully converted to a string. As a correction of this, you can do one of two things.
First, if you need the entire resulting array that represents the entire row of the table, then you can simply change your echo code to this:
foreach ($fname as $row) {
// print the fname of the row
echo $row['fname'];
// do the other stuff you need to do with $row
...
}
OR, if you simply need the fname field out of that table, for the given id, you could use a different $wpdb function, called $wpdb->get_var(), which gets one specific field from the first entry of the resulting data from the database, coupled with some minor SQL changes:
// use the get_var() function instead
$fname = $wpdb->get_var(
$wpdb->prepare(
// 1) change the 'fields' of your sql to only get the `fname` field
// 2) also add limit 1, to reduce load by only asking for one row
// NOTE: #2 is optional really, because WP does this for you when using get_var,
// but is good practice to only ask for what you need. so do it
'select fname from `vfp_cart66_accounts` where id = %d limit 1',
$account
),
ARRAY_N
);
echo $fname; // print the value of field fname from vfp_cart66_accounts for id $account
Now. I don't have specific knowledge of Cart66. That being said, if the above changes to PHP, WordPress, and SQL syntax do not yield results, then you are probably having one of the following other problems instead:
there is a different PHP error somewhere in the code, causing this to never run
this code is never called, and thus it is never executed
you misspelled the table name, which is causing an SQL error
the table exists, but does not have a field named id
both table and field exist, but there are no entries in the table
some other random thing that is not coming to mind
DEBUG #1
For #1, you could try turning on error_reporting() and display_errors early in the code execution. In a normal, run of the mill PHP script you could add the following two lines somewhere early in the code:
error_reporting(E_ALL);
ini_set('display_errors', 1);
However, you are using WordPress, so you will need to do something like this in your wp-config.php file:
// find the line that looks like this and comment it out
// define('WP_DEBUG', false);
// add these two lines directly below it
define('WP_DEBUG', true);
ini_set('display_errors', 1);
DEBUG #2
Make sure your code is running. Don't be afraid to throw a die() statement directly above it, to make sure it is running. Something like this:
// add a die() before everything
die('I am running. Awesome!');
// revised code
$account = Cart66Session::get(Cart66AccountId);
global $wpdb;
$fname = $wpdb->get_var(
$wpdb->prepare(
'select fname from `vfp_cart66_accounts` where id = %d limit 1',
$account
),
ARRAY_N
);
echo $fname;
DEBUG #3
To debug #3, you need either access to a commandline tool for MySQL or some type of GUI interface like phpMyAdmin, so that you can run a query directly from the database. Here is the query you should run:
show tables like 'vfp_cart66_%';
This is an example of one of the only places in SQL that you should ever quote a table name in single quotes. Running this will yield a list of all the tables that start with vfp_cart66_. If you get no results, then your table name is wrong. If your results do not include vfp_cart66_accounts, then your table name is wrong. If you see vfp_cart66_accounts, you are good to go.
DEBUG #4
This one will need to be run directly from the DB or through something like phpMyAdmin also. You are trying to make sure you have the correct field name. The way you do that is:
show create table `vfp_cart66_accounts`;
Assumedly, the field you are calling id would be the auto_incremented field in the table. Thus you are looking for a line, similar to this one:
`id` bigint(20) NOT NULL AUTO_INCREMENT,
Make sure that the line that has AUTO_INCREMENT on it, begins with:
`id`
If it does not, and the name is something else other than id, then you probably have the wrong field name.
DEBUG #5
Make sure you actually have data to display. From your mysql console or phpMyAdmin, run:
select * from `vfp_cart66_accounts` limit 1;
If you bet any results, then you have data, and you are good.
DEBUG #3 - #5 (alternate methods)
Another option you have is to dump the $wpdb object, directly after you run the query, because it contains the last error you received from MySQL. You can do this like so:
$fname = $wpdb->get_var(
$wpdb->prepare(
'select fname from `vfp_cart66_accounts` where id = %d limit 1',
$account
),
ARRAY_N
);
// dump a readable version of the $wpdb object
echo '<pre>';
print_r($wpdb);
die('</pre>');
Often times, reading the MySQL error message helps narrow down the problem in your SQL syntax.
DEBUG #6
If none of this has helped at all, then you will need to use your experience to trackdown a random bug in either your plugins or theme, what could literally be anything. You may as well not even dig in core WP code because, while it does have a couple minor bugs unrelated to your problem, which are getting repaired as we speak, it is one of the most stable CMS platforms out there. It is used by more of the top 10 million sites on the internet than any other CMS, for a good reason. It works, it is up-to-date, and most of all, it is stable.
I really hope you found this helpful or at least learned something from it. Hopefully others find it useful as well.
$fname=$wpdb->get_results(
"SELECT * FROM `vfp_cart66_accounts` WHERE id = '$account'",
ARRAY_N"
);

PHP mySQL variable access

Say I do something like this:
//get unit id
$query = "SELECT id FROM units WHERE unit_name = '".$unit."'";
$id = mysqli_query($con, $query);
$unit_id = 0;
while ($row = mysqli_fetch_array($id))
{
$unit_id = $row['id'];
}
why is $unit_id not changed outside of the while loop?
What happens is this: I have a selection dropdown with a list of units and when on is clicked that php code is fired (along with other code in the file) and it makes a hidden input field with the id in it. I unhide the id and find that the id is not correct. What is displays, rather, is, say I click the first option, 1001, second option, 1002, third, 1003, etc. These ids do not correspond to my database at all, though the units begin at 1001 in the database. Because of all of that I assumed that my $unit_id just wasn't getting read properly and that somehow PHP didn't let one access the variable outside of a while loop in that way. I see now that assumption was premature. Thanks.
Two possible explanations:
Your query is failing but you have error reporting disabled (nor are you outputting/logging MySQL errors).
There is no unit_name with that name.
If you don't have error reporting enabled by default, try putting:
ini_set('display_errors',1);
error_reporting(E_ALL);
at the top of your script (in a dev enviornment, error reporting should be enabled by default, by the way). Also, you can try using:
$id = mysqli_query($con, $query) or trigger_error(mysqli_error($con));
to view any MySQL errors that may have occurred.
Actually it changes.
Two cases for this..
Maybe your $row['id'] value is also 0.
[or]
Your query returning (0 results) and it is not entering the loop.
What happens is this: I have a selection dropdown with a list of units and when on is clicked that php code is fired (along with other code in the file) and it makes a hidden input field with the id in it. I unhide the id and find that the id is not correct. What is displays, rather, is, say I click the first option, 1001, second option, 1002, third, 1003, etc. These ids do not correspond to my database at all, though the units begin at 1001 in the database. Because of all of that I assumed that my $unit_id just wasn't getting read properly and that somehow PHP didn't let one access the variable outside of a while loop in that way. I see now that assumption was premature. Thanks.

PHP & SQL: update record issue

Having some difficulty pinpointing exactly what is wrong with this block of code. I am expecting it to run through a loop a set number of times and update some rows in the table tbl_games with some values received from the form.
I have tried running the code in phpMyAdmin without variables, which works fine (updates specified row). I assume the problem is something to do with the string in $insert_q.
gamecount will always be an int<30, game_ID will be a unique primary key integer value in tbl_games.
A little background: this code is part of a bigger project - which is centered around football games. An admin adds games to tbl_games (coded and finished), this current file now displays games to the admin which are unplayed (scores for team1 and team2 are NULL) and gives them a space to input scores for each team. This code takes those 2 scores, and the game_ID and updates each row.
It's having no effect on the DB rows though. Please point me in the right direction.
<?php
$lim=$_SESSION['gamecount'];
for ($i=1; $i<$lim; $i++) {
$game_ID = ${"_SESSION['game".$i."_ID']"};
$score_team_1 = ${"_REQUEST['".$i."_team1-score']"};
$score_team_2 = ${"_REQUEST['game".$i."_team2-score']"};
$insert_q = "UPDATE tbl_games SET team1_score = '$score_team_1', team2_score = '$score_team_2' WHERE game_ID = '$game_ID';";
mysql_query($insert_q);
}
session_destroy();
?>
I think the problem is with this line.
$game_ID = ${"POST['game".$i."_ID']"};
It should be something like this.
$game_ID = ${"_POST['game".$i."_ID']"}; or
$game_ID = $_POST['game'.$i.'_ID']; //much cleaner
You need to make use of the mysql reporting. Get it to output any errors, and affected rows. While you may think affected rows will be none, it might not be (always good to check when debugging just so you check everything).
Does your PHP error log have any warnings or other notices that might point to your query being an issue etc?
What is the value you're updating (echo out the var/session) and what is the DB value (look at it in phpmyadmin or mysql command line).
Could be there's nothing to update.

unable to adjust array input in php?

I have a back propagation code implemented in PHP for simple multiplication table. Its training set input is like:
$data=array(0=>array(1,1,1),
2=>array(1,3,3),
3=>array(1,4,4));
basically it trains neural network for 1*1=1,1*3=3 etc
and then the testing dataset is like:
$testData=array(0=>array(1,1));
1=>array(1,3),
2=>array(1,4));
and thus the results are predicted...
NOW my problem is I want to change my training data in a way that:
$churn=1;
foreach($id as id1){
$data=array($row['count_call']<3,$row['total_cost']>60,$churn)}
and similarly wants to change my testing data but this won't work at all...
please help me how to change training data as i want against each customer id, its count of calls and total cost are checked for some values range and then the output will be decided as: customer will churn or not?
my table will be like:
id count_call Total_cost
03214567890 2 60
03212999438 4 80
I'm going out on whim here guessing that your question is related to the loop:
foreach($id as id1){
$data=array($row['count_call']<3,$row['total_cost']>60,$churn)}
Which will not work and should give you a rather comprehensible error message.
I'm guessing that you want to do something like:
foreach($id as $id1){
$data=array($row['count_call']<3,$row['total_cost']>60,$churn)
}
Why you'd do it like that is strange however since you're not using the value $id1.
Also note that the foreach - as statement is used like this:
foreach($array as $item) {
echo $item;
}
Read more about it here.

Categories