How to access result set in phpDataMapper? - php

I started learning this very nice PHP ORM api last week: http://phpdatamapper.com/
and have been trying to get up to speed with it
What I'm not seeing in the site documentation, is how to iterate with "$postMapper->all()"?
http://phpdatamapper.com/documentation/usage/finders/
When I try to iterate through the value returned from ->all(), it seems only to have gotten the last element in the table.
Here's the code I have:
// $postMapper uses phpDataMapper framework. It works to create the schema & insert values
$postEntities = $postMapper->all();
$postEntities->execute(); // tried adding this to help things
foreach ( $postEntities as $postEntity);
{
echo $postEntity->title;
echo "<br/>";
}
I see other folks are forking it from GitHub and using it in their projects, so I believe I'm making some mistake in my call logic.
It would be great if someone could share a small example of how to access the query data correctly when using mapper->all()? This is an important part of a PHP stack and I would very much like to be able to use this particular solution in my projects going forward. Thanks

Ok, this turned out to be a "not so smart" mistake on my part. The font in my IDE was too small I guess, and I didn't see the ';' at the end of the line that declares the for loop.
So the ORM is all good, just my code wasn't. I'm updating this in case someone else can learn from my mistake - other option is to just delete the post all together (... not sure which is better)

Related

PHP Stops execution randomly for no reason - random changes in code fixes it

On our platform, users may have different combinations of products in their inventory. Every now and then, a user will report to us that the page that lists these products is crashing. What this "crashing" actually is is PHP just stoping the rendering of a product for no reason at all, and then not rendering the rest of the page (for example, PHP won't include the footer file, so the page just ends at the half-rendered product).
Sometimes it stops at a random product after rendering it fully, sometimes it only renders a product's image and stops the whole page rendering there.
Seemingly random changes to the code seem to make the crashing stop. What do I mean?
If I add this anywhere inside the product loop:
<?php echo "<script>console.log('test');</script>"; ?>
It will stop the error. Just today I decided turning php.ini's display errors on and that fixed the error for some dude. Turning it off brought it back. Some other user was fixed when I changed the loop's syntax from
<?php foreach ($inventory as $code) : ?>
to
<?php
foreach ($inventory as $code)
{
This is the current code for the loop:
<div class="myProductsList">
<?php
$inventory = GetUserInventory($user, $plan);
if ($inventory)
{
$evenOdd = false;
foreach ($inventory as $code)
{
$product = GetProductObject($code, $plan);
$product = $product[0]->ID;
if ($product)
{
$prdTitle = get_the_title($product);
$prdDate = get_the_date('F, Y', $product);
$prdImg = get_the_post_thumbnail_url($product);
$prdLink = str_replace('/offer/', '/product/', get_the_permalink($product));
$evenOdd = !$evenOdd;
$tagCloud = get_field("prd_tagcloud", $product);
$owner = false;
include 'parts/product-card.php';
}
}
}
?>
</div>
And this is the current code for the product-card
<div class="productCard altCard_<?=$evenOdd;?> <?=$owner;?>" stamp="<?=get_the_date('U', $product);?>">
<div class="productCardCont fullw fullh cont col">
<a href="<?=$prdLink;?>">
<img class="fullw" src="<?=$prdImg;?>">
</a>
<div class="productCardAbout fullw hcent cont col npad">
<h3 class="fullw fcent"><?=$prdTitle;?></h3>
<span class="fullw fcent"><?=$prdDate;?></span>
<div class="productCardWarp"></div>
<div class="ctaMain cont col hcent" id="#ctaMain">
<?=ctaMain($prdLink, "Select");?>
</div>
</div>
<span style="display:none!important;"><?=$tagCloud;?></span>
</div>
</div>
I have absoulutely no idea what causes this, especially since no errors appear when I turn them on, no product has any invalid or corrupted data (as you can see I only pull their images, names and date), no inventory code is ever wrong, we have very few users compared to our VM's specs capabilities, the page always loads blazing fast, and as I said:
Random users, with seemingly nothing in common experience these issues, and the 'fixes' often make no sense at all.
One last thing. Sometimes in order to investigate these error reports, I will copy the user's inventory and set it to my own test account (so we both have a identical inventory). Sometimes my account experiences the error, sometimes it doesn't.
The "inventory" I talk about is a table in our database, where each user has a row, and the inventory is just a comma separeated sequence of our internal codes for each products. The codes are a simple number-letter combination.
Example of a inventory that has caused my account to crash:
F2112S04E6B,F2105S03E05,FL21M03V2,F2106S03E06,F2107S04E01,FL20M03V1,F2109S04E03,F2110S04E04,F2111S04E05,F2202S05E02,F2006S1E00,F2208S06E02,F2209S06E03,
Sometimes, if I remove a random product from it, it stops crashing.
PHP version: PHP 8.0.18
Database: 10.6.7-MariaDB
I'm running on a Bitnami Wordpress stack
The question: What is causing this error?
I know it's a complex environment and many things could be at fault, but looking at the code I provided, is anything there that looks potentially guilty?
If the error that I have described is not clear enough, please bare with me as this is a very unique situation which I have never encountered, and I will do my best to make it clearer for you.
EDIT
Tim Morton raised some relevant topics in the comments, so I'll reply to them here to improve context for this question.
'Your first "fix" was to print a javascript command?'
I printed multiple JS commands (console.log) just to see at what point in the PHP script it crashed. When I ran it I noticed that the simple presence of these console.log commands, for some bizarre reason, fixed the crash itself.
'Then changed the syntax of your loop? This seems aimless.'
Yes, and yes it does seem aimless, but believe me it worked. That's why I'm dumbfounded, since it shouldn't.
'Is it printing all of the php-generated content and then failing some javascript?'
No, there is no Javascript here. The only JS was added later (console.log), as I explained, in order to see at what point the PHP crashed. It usually prints the PHP generated product-card.php (included by the loop) and at a random product, stops printing anything, even outside the loop.
'or is it failing in one particular part of the php loop?'
I'm pretty sure its in the PHP loop, but I have not been able to narrow it down.
'To diagnose, you could use try/catch and error_log() to help narrow it down to what is actually failing.'
Will do! The issue is, simply adding a try/catch will probably 'fix it' since as I stated earlier, random changes to the code seem to 'fix' the issue temporarily.
'Does the same record fail every time (hint, it could be the next record that's actually failing)'
So far it seems random. I've tried modifying the inventory record to place different products at different orders. This sometimes works, sometimes it doesn't. So far no pattern emerged.
UPDATE
So far, I've noticed two types of crashes. One of them it prints out halfway thru on a product-card.php iteration, then crashes (so it doesn't even get to the other iterations). On one of these cases, it crashed at only the second iteration.
On this specific case I've been able to see the front end code thru Chrome dev tools, and I noticed that it crashed right here, at the product-card.php
<a href="https://some-link.com/something/
As you can see, it crashed right after the echo, as it didn't even put the finishing quote and '>'.
On the other type of crash, it'd crash at a random iteration too, only the last iteration it'd finish rendering whatever card it was on and then crash, instead of crashing halfway thru.
I saw people commenting that I should just update or modify my PHP installation and be done with it, and to be honest I may do that since this is happening in prod, but this question is aimed at why this is happening.
What does contains $prdLink ?
What does contains $prdImg ?
What does contains $prdTitle ?
Are those variables correct sanitized ?
Does contains chars like ", ', > or anything that could ruins your dom ?
PS. If does, I'm afraid you have bigger problem, a security problem (XSS, etc).
After a very exhaustive wild-goose chase, I've come to the conclusion to the (likely) root cause of the issue:
Too many errors and warnings being logged onto the apache2/error.log file.
Seriously, it was like hundreds of warning logs per second, the file was several GBs large. I don't know exactly why it caused this behaviour, but turning off the logging for everything but critical errors seemed to solve the issue AFAIK (we didn't do anything else, it's AFAIK because we can't be 100% sure that this completely stopped for all our users).
Maybe it was a problem with the exception handler itself, as previously suggested. Maybe it were just too many exceptions to handle, maybe PHP or Apache were overwhelmed with so many logs. We'll never know.
Thank you for everyone who helped, commented and answered, definetely pointed me into the right direction. I were so desperate that I even bountied this, I think. Hopefully this will help another clueless developer out there.
I don't know if that's a typo made on this post or you copy pasted it but
<a href="https://some-link.com/something/ notice you are missing a " (sorry to not comment but not enough karma)

How to print query result in python/django

I came from CakePHP and just started playing with Django framework. In CakePHP, I have the habit of printing out all the returned array using pr() straight out to the webpage. For example:
A controller spits out a $result to a View, I use pr($result) and it will print out everything right on the webpage so I know how to travel through $result from my View.
A form POST a $request to a Controller, I use pr($request) to see what is sending in before processing it in the Controller. The content of $request will be displayed immediately on the webpage right after I hit Submit the form.
I'm wondering if I could do the same thing in django instead of going to the shell and try pprint (or could I just use pprint to print out to the web???)
This is a really simple example about what I'm talking about:
app_name/views.py:
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
return render(request, 'socs/detail.html', {'soc': soc})
How can I just view clearly what is in "soc". In cakephp, I could just pr($soc) right there and it will be displayed right on the detail.html page.
I have tried this and it didn't work (I'm sure it's basic but i'm just new to this)
import pprint
def detail(request, soc_id):
soc = get_object_or_404(Soc, pk=soc_id)
pprint.pprint(soc)
return render(request, 'socs/detail.html', {'soc': soc})
I have spent two days doing research but I couldn't find the answer. I'm hoping one of you can help this newbie out.
The way you're trying to print will show the print in the terminal that is running your Django server. If you just need to see it quick, check there.
If you want to output the value on to the rendered page, you'll have to include it in the template using template tages. It looks like you send {'soc': soc} to your template as context. Because of this, you should be able to use it in your template. So, in your template (socs/detail.html), just add {{ soc }} somewhere and it should print out the value. The template has full access to the object, so if you wanted something specific, you can also print that instead (like {{ soc.id }}).
If you want to see everything that's in the object without specifying all of the different fields yourself, send OBJECT.__dir__. For example, for this you'd send {'soc': soc.__dir__} as your context. Keep in mind that this likely should not be used for anything but inspection on your part.
If you'd like to learn more about Django's templating, check out the syntax and more.

PHP eval code and store the result into a variable

I have continued my voyage into creating a extremely simple template engine.
Because I wanted to add logic to my template I eventually got back to the point that I allowed PHP tags into my code which I enabled by evalling the code.
Maybe not the best solution but when looking at the WordPress templates I noticed that the idea itself may not be that bad.
But now there still is one small problem left.
And that is that I want to translate the generated code.
But it has been evalled already. Hence parsed.
I thought of solving this problem by using ob_get_contents().
But this brought one more question and in case of errors it shows a white screen. (memory usage etc.)
Plus it still did not take away the problem of eval that it parsed the contents when evalled.
In short the class logic is:
Loading template files
Adding the contents
Compiling the template
Eval the code (but unfortunately also displaying the code)
Translate the code so I can translate the code parsed by a PHP script
I would love something like:
$code = eval('?>'.$tpl.'<?php');
$code = translate($code);
WriteCache($code);
SetDocumentHeader();
echo $code;
Would anyone know how to achieve this?
Thanks in advance!
$code = eval($tpl);
Check this out.

mysql fetch array returns false in function but not in the document

i am creating a CMS and have php creating a page. i have a while loop like this
while($row = mysql_fetch_array($results)) {
echo "some html code" . $row['name'];
its shortend but hopefully you get the point. i have the full thing in my page working just as it should and i wanted to move it to a function include as i want to reuse it. the problem is i do that and it stops working.
i did some testing and found that the function is getting the query result and after doing a var dump both were identical the problem comes when i try to assign it to an array. it comes back as false so in the above code, for example,
$row = false;
im toatly lost in this and if my explanation is confusing i appologise but i am a bit of a newbie i have tried searching but....i dont really know where to begin
any thoughts.
the query you are doing is basically wrong, try posting exactly the code which you have in $query and then let us see the problem.
also, it is better to use mysqli functions.
but for this, edit the question and type the query, or simply put a die(mysql_error()) at the end of your query which is in $query. It will show your exact error.
i fugured it out
when i was testing the function i commented out the original code on the main page but for some reason i had not comented out enough (it was a mix of php and html clearly the php had not been commented out properly) this must have been causing a clash of some kind as when i put the function above the code on my page the function worked and the long code below it did not
sorry for wasting your time guys

NetBeans-Xdebug works, but won't expose some PHP variables

UPDATE -- working on getting WAMP with phpDeveloper/Xdebug going. I still want NetBeans -- I just want to compare, see if I get some insights.
I am using NetBeans 6.9 with LAMP and Xdebug to work on PHP code. The Variables display works well, but lately it works less well. For example below, $authorized should be visible in the variables pane below the code and should expose its value. But it doesn't show, nor its value, and mousing over the code doesn't help. (The $this object is showing and it does go on and on, but $authorized isn't in there, and it wouldn't make sense if it were.)
This behavior is consistent. Maybe it's a function of the complexity of the code? Or rampant object usage? it seems to have started when I took up CodeIgniter.
Of course the variables are hidden when I need them most ... or so it seems to the poor human. What am I missing?
NetBeans debugger http://themanthursday.com/wiki/Debugger_Display.png
There's a better example below. When I'm stepping through this code, Variables displays only Superglobals and $this, just as in the picture. I can't see any values, even mere strings.
(Nagging thought: I bet the $CI SuperObject has something to do with all this ...)
class Product_documents {
function getProductImage_all($id)
//Return an array of all documents for this product
{
$imgPath = $this->_getProductImage_folder($id);
$arrayPossibleFilenames = $this->_getProductImage_possible_files($id);
foreach ($arrayPossibleFilenames as $imgFile) {
$imgPathFull = $imgPath.$imgFile;
$file_exists = get_file_info($imgPathFull);
if ($file_exists)
{
$arrayFilesPresent[] = $imgPathFull;
}
}
return $arrayFilesPresent;
}
}
Right click on the variable pane. Select "Filters". You will find the secret.
Came across this site that has a very nice link to an Xdebug page that walks one through the process of upgrading Xdebug by compiling a 'more latest' version:
http://icephoenix.us/php/xdebug-doesnt-show-local-variables-in-komodo-netbeans-or-eclipse-pdt/
Variables inside by objects/classes are showing up again! Yeah!
No watches, no 'this may make Xdebug freak out' messages - just good ol' variables that now fully expose the failure of my solution... (haha).
David
I've seen stuff like this before in Netbeans. I expect it's just a bug involving Netbean's interaction with XDebug. One possible workaround that I've seen before is adding a "Watch" for the variable that you can't see. For your example, you could go to the "Watches" tab and type in $authorized. It should show up once it has been set.
I think it comes down to the singleton pattern that is implemented in CodeIgniter as "Super Object". I never have restarted this project to test Kamal's idea. Shortly after he posted, I concluded the singleton was the reason (I did not try to guess whether Kamal has the solution or not). Thus my response to this post.
(2015) In php.ini under [xdebug], set xdebug.show_local_vars=1 if you want all the local variables in debug mode.
Try initializing $authorized to bool false.
I've seen Netbeans not show me variables initialized with a return value from a function without a doctype, but it's hit or miss enough to not be make a pattern out of.

Categories