MongoDB showing error when it finds a blank entry - php

I have a project where it searches for a specific entry in a specific column and then returns all documents that have that entry in that column. It works almost perfectly except when that entry field is empty it gives an error. Let me try to illustrate below.
My DB:
A|B|C|D
1|1|5|5
2|1| |6
3|2|7|7
4|2|8|8
My PHP:
$query = array( "B" => 1);
$cursor = $collection->find( $query );
foreach ($cursor as $obj) {
echo $obj["A"] . $obj["B"] . $obj["C"] .$obj["D"] . "<br />";
}
My output is:
1155
21Notice: Undefined index: C6
How do I go about not giving any errors. Just treat it as an empty field. I'm not sure if this is a common problem but, I'm still new to PHP and very new to MongoDB.

Use isset() to find out if the key exists in the array before trying to index using it
foreach ($cursor as $obj) {
echo $obj["A"] . $obj["B"]. (isset($obj["C"]) ? $obj["C"] : '' ) .$obj["D"]."<br />";
//It will replace each blank with an ''
}

I believe thats nothing to do with mongodb. Its how the flexible document schema works. It wont return the field because the key C doesnt exist in the particular document.
I dont have any experience with PHP. But am sure php throws the error because you are trying to access the key 'C' that doesnt exist in the particular document.
But i believe these problems can easily be solved if you use some ODM (Object document mappers). It solves the problem by assigning default value based on the data type of the field.
Hope it helps

Related

conditional check inside a foreach is causing errors

I am using Simple_html_dom trying to grab Reputation points and make a check on those values and then extract only those user profiles whose Repu is greater that 200. Below is the code, It works fine when doing this
`
$html2=str_get_html($html1);
foreach ($html2->find('.user-details') as $value) {
foreach($html2->find('.reputation-score') as $repu){
echo (int)$repu->plaintext.$value.'<br>';
}
}
When doing the above i am getting all thereputation and the user detailswell each line, looks fine till now. But now i wanna perform aconditional checkand then echo only those profiles whose repo is higher than100`. So when i am trying the below code
`
$html2=str_get_html($html1);
foreach ($html2->find('.user-details') as $value) {
foreach($html2->find('.reputation-score') as $repu){
if($repu>100)
{
echo ($repu->plaintext.$value.'<br>';
}
}
}
I am getting an error saying Object of class simple_html_dom_node could not be converted to int seeing that i've tried doing (int) to convert and then echo still couldnt solve
Any help here ?

Using Include Files with PHP Associative Array

I have an event listing page in a wordpress plugin I mage that is showing a date with times for that date.It shows 14 days worth.
I’ve used an associated array to grab the server date and strip it down to a number. Each day has an include file associated with it.
I’m trying to get it to sort those dates and then include that file so it will show.
When use the following code, it works fine. Shows the key, date, value and name of the include for all the 14 days.
$compare = array($getshow1=>("day1.php"),$getshow2=>("day2.php"),$getshow3=> ("day3.php"),$getshow4=>("day4.php"),$getshow5=>("day5.php"),$getshow6=>("day6.php"),$getshow7=>("day7.php"),$getshow8=>("day8.php"),$getshow9=>("day9.php"),$getshow10=>("day10.php"),$getshow11=>("day11.php"),$getshow12=>("day12.php"),$getshow13=>("day13.php"),$getshow14=>("day14.php"));
ksort($compare);
foreach($compare as $x => $x_value) {
echo "Key=" . $x . ", Value=" . $x_value;
echo "<br>";
}
However when change it to the following sorth to try and use the includes, it works but for some reason only shows on about half of the 14.
ksort($compare);
foreach($compare as $x => $x_value) {
include $x_value;
}
I’m thinking there is some function I need to use but I’ve working on this a while now and think I have code block.
Any help would be appreciated.
use associative array key as string it will work fine :)
Make sure that your php file should be in same directory if it is in different directory than define its proper path in array value.
your array should look like this
$compare = array(
'getshow1'=> "day1.php",
'getshow2'=> "day2.php",
'getshow3'=> "day3.php",
'getshow4'=> "day4.php",
'getshow5'=> "day5.php",
'getshow6'=> "day6.php",
'getshow7'=> "day7.php"
);
and try again
ksort($compare);
foreach($compare as $x => $x_value){
include $x_value;
}
For some reason, the sorting would not work if any of the fields were empty. So, I created a null value for each field and had it auto add that value if the user didn't enter a value when filling out the data.
Using the getshow or $getshow in between '' did not work as it just sorted on that an not the actual variable that needs to be pulled in to each one of the 14. I dropped the '' and now with the no blanks everything is working as I needed it to.

Why is my first value in reset() null?

I have a server with a directory full of books. I wrote a script which loops through this directory and lists out all the PDF's that are located inside. I then took it a step further and started searching Google books and bringing back the picture and description of these books. For some of the books this works perfectly, but for a good number of them I get this error...
Warning: reset() expects parameter 1 to be array, null given in bookDescriber.php on line 49
This the code that is giving this error (this is all inside a big foreach, which lists all the PDFs in the directory). the last line of this code is line 49.
//search GoogleBooks for a description
$item = file_get_contents("https://www.googleapis.com/books/v1/volumes?q=$v&maxResults=1");
$item = json_decode($item);
$item = reset($item->items);
the $v in the above url is simply the filename of the book, so this is one of the links it would generate and as you can see this does return information... (if you copy the entire link all the way to maxResults=1 then the data is returned, could it be that sometimes the spaces in the URL don't matter and sometimes they do?? I'm lost)
https://www.googleapis.com/books/v1/volumes?q=Ajax the definitive guide.pdf&maxResults=1
so why is the first parameter in my reset() set to null??? Help please!!
I've tested around with that snippet and it can be recreate if:
$v is blank
The book doesn't exist
If the book doesn't exist, the null error is thrown and Google returns:
{
"kind": "books#volumes",
"totalItems": 0
}
This isn't enough information to create an array. You are better off having a check like so:
<?php
$item = file_get_contents("https://www.googleapis.com/books/v1/volumes?q=$v&maxResults=1");
if(is_array($item))
{
$item = json_decode($item);
$item = reset($item->items);
}
else
{
return false; // echo 'no book';
}
?>

I need help sorting out an if statement in a simplexml statement

Some basic background ...
I have a form that enters data to an xml file and another page that displays the data from teh xml depending that it meets the requirements . All of this I have managed to get done and thanks to a member on here I got it to show only the data as long as it has todays date and status is out . But I am left with the problem of trying to sort an if statement which needs to show data if it has it or show another div if not .
My Code ...
$lib = simplexml_load_file("sample.xml");
$today = date("m/d/y");
$query = $lib->xpath("//entry[.//date[contains(., '$today')]] | //entry[.//status[contains(., 'out')]]");
foreach($query as $node){
echo "<div id='one'>$node->name</div>
<div id='two'>$node->notes</div>
<div id='three'><div class='front'>$node->comments</div></div>";
}
So to reiterate if query returns matched data do the foreach else show another div
I only wish to know the right code for the if else statement if soneone could help with this I would be very grateful and will up vote any answer as soon as I have the reputation in place . I also apologise in advance if the question has been asked before or if it is too vague thanks again .
If xpath fails to resolve the path, it will return false (see here). Wrap the foreach loop in a simple check:
if( $query ) {
foreach($query as $node){
...
}
}
else {
// Echo the special div.
}
Since PHP is loose typed, if xpath happens to return an empty array, this check will also handle that case. Be aware that if the xpath call does return false, there may be a separate error at play that may require additional or alternative handling.

How To Stop Duplicates Being Listed On PHP Results?

I've made up a PHP script which assigns a score to listings on a website and assigns it to the results page. I have got it to work in that it shows the score and the details but it keeps listing the same results over and over.
I can't work out what it is doing but there is a small section of code I was hoping would prevent duplicate listings. Could anyone give it a tweak and see if I am going wring somewhere?
The Code is:
$dupCatch .= $adId.",";
$dupResults = explode(',', $dupCatch);
foreach($dupResults as $dupResult){
if($dupResult == $adId){
print "";
} else {
print $showResults;
$scoreBox = 'THIS IS THE SCORE: ' . $finalScore . '';
print $scoreBox;
}
}
Thanks in advance!
Jack
The problem is that you add your current $adId to the duplicate list before you check if it is there - which it will always be, of course.
Storing a bunch of numbers in a string, explodeing it every time, is a little weird, use an array instead. You also don't need to manually loop through all the items, just use in_array()
if( !in_array($adId, $dupCatch) ){
print $showResults;
$scoreBox = 'THIS IS THE SCORE: ' . $finalScore . '';
print $scoreBox;
}
$dupCatch[] = $adId;
Needless to say: it would be a better idea to fix the part that gives you the duplicate results in the first place.
You can either try to use array_unique from php side or use unique attribute at field in mysql this way duplicates can be prevent before even inserting them.

Categories