Find Method Returning False - php

I am trying to execute a find in my script, but I believe my condition is returning false. I am trying to execute a find and pull all records that match the given value in my $data variable. I have tried to compare the BranchLicense.RegionCode to $data but no luck. I have also tried to compare it the _Session['Auth']['User']['region_code']. The $data variable is returning the correct value but the script does not return the proper records. What am I doing wrong here? Here is my code.
//echo '<pre>'; print_r($_SESSION); echo '</pre>';
//$this->loadModel('AuthAcl.Users');
$data = $_SESSION['Auth']['User']['region_code'];
//$data = $this->Users->find('all');
$new = $this->BranchLicense->find('all', array(
'conditions' => array('BranchLicense.RegionCode' == $data)));
die(debug($new));
$this->layout = 'default';
//$this->set('branchLicenses', $this->BranchLicense->find('all', array(
//'conditions' => array('BranchLicense.RegionCode' === '$data'))));

Try as follows-
$new = $this->BranchLicense->find('all', array(
'conditions' => array('BranchLicense.RegionCode' => $data)));
die(debug($new));

Related

Want to get just two object in json

I am trying to make a code verifier with the following code. I've looked at the answers in StackOverflow but couldn't get the right result.
The code is working fine but I want to echo just two value.
validate.php page code is here:
if(isset($apKey) && isset($code)) {
$en = new En();
$Key = $apKey;
$Codes = $code;
if($Key == null || $Codes == null) {
echo json_encode(['data' => 'No Key or code found, Please try again']);
exit;
}
$response = $en->validate($Key,$Codes);
$result = json_decode($response);
$elements = json_encode(['data' => $result]);
echo $elements;
exit;
}
echo json_encode(['data' => 'No Key or code found, Please try again']);
exit;
Now I am trying to check this validate page results using this code:
$siteurl = urlencode($_SERVER['SERVER_NAME']);
$arrContextOptions = array(
"ssl" => array(
"verify_peer" => false,
"verify_peer_name" => false
)
);
$file = file_get_contents('http://www.validates.com/validate.php?code=' . $check , false, stream_context_create($arrContextOptions));
$checks = json_decode($file, true);
$elements = $checks['data'];
echo print_r($elements);
So the results something like this:
Array
(
[buyer] => abcd
)
So what I want to do. I want to echo just buyer and error message after this code: $checks = json_decode($file, true);
The error result is here:
{"data":{"error":404,"description":"No sale belonging to the current user found with that code"}}
Like for example:
if(buyer){echo 'true';}
if(error message){echo 'error';}
I guess you can check with array_key_exists if there is error. You can do something like this:
$checks = json_decode($file, true);
$data = $checks['data'];
if (array_key_exists("error", $data))
echo $data["description"];
else
echo $data["buyer"];

Json response only current data

This is my query and all thing going very well. problem is that only json response. when I print json .its showing only one data .while I want to list all data of current user .so please if any help then let me know Thanks .
$user1 = $wpdb->get_results(
"select product,checked_by,submit_date from diary_user_form_storage where DATE(submit_date) = CURDATE() ;
");
foreach ($user1 as $key => $value) {
$productString = stripslashes($value->product);
$checked = stripslashes($value->checked_by);
$checked_by = json_decode($checked , true);
$product = json_decode($productString, true);
$checked_by = json_decode($checked , true);
$product = json_decode($productString, true);
$date=$value->submit_date;
$date1 = date('Y-m-d',strtotime($date));
$timing= date('H:i:s',strtotime($date));
$jsonString = "";
}
header('Content-type: text/json');
echo json_encode(
array(
"status" => "1",
'user_id' => $user->ID,
'message' => 'fetched',
"token" => $token,
'token' => $token.$device_id.$device_type,
'serverUrl' => $serverUrl,
'option'=>$option,
'product' => $product,
'checked_by' =>$checked_by ,
'submit_date'=>$timing
));
?>
You misunderstand what a foreach loop is, and may be confused about variable scoping. Each time the loop loops over an element of your query, this line is executed:
$productString = stripslashes($value->product);
which overwrites the same variable over and over again. So, in the end, when you echo json_encode(/*stuff*/) only the content of the last iteration of the loop gets outputted.
Luckily for you, you can just put the echo in the loop, and each part will be outputted by your script.
Make sure to put the header before that, or your script will fail. Headers (header('Content-type: text/json');) need to be sent before actual content.

PHP MongoDB find query

I try use this solution for pagination in PHP:
public function getRecords($page, $count, $currentId)
{
$query = ["_id" => ['$gt' => $currentId]]; //what's wrong here?
$cursor = $this->recordsCollection->find($query)->
skip(($page-1) * $count)->
limit($count)->
sort(["_id" => true]);
$result = array();
foreach ($cursor as $doc) {
array_push($result, $doc);
}
return $result;
}
But it returns an empty array result. Also I tried this query without skip and limit, but the result still was an empty array. If $query is empty, everything is ok, it returns all records in colection.
What I'm doing wrong?
SOLUTION$query = ["_id" => ['$gt' => new MongoId($currentId)]];
Maybe $currentId is of wrong type? Looking at what you're trying to do I think it should be instance of MongoId

Return a record from PHP with function and render

I have a function
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
return $results;
}
and this is called via
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
However the results of $returnedUser['(field name']Althought, are always coming up NULL. avatar, userSelectedTheme are some of the fields from the dbase. I have confirmed in the database the infomation is there
I suspect I am missing a key line from my function which involves =array() somewhere and manflu is preventing me seeing it.
Any advice greatly appreicated
First of all stop using mysql_(Why shouldn't I use mysql_* functions in PHP?) is deprecated.
mysql_query from getUser function returns a resource. you must
return an array. so have a look at mysql_fetch_array or mysql_fetch_assoc functions
basically you must return mysql_fetch_array($results) assuming that is only one result comming from db. otherwise you'll have to loop through them.
Thanks to all those who answered, and extra plaudits to those who spotted the use of the depreciated mysql commands.
Had a shot of espresso and got the answer working (albeit unsafe and unsecure and..)
function getUser($linkedInID) {
$sql = "SELECT * FROM ipadapi.users WHERE linkedInID = '".$linkedInID."'";
$results = mysql_query($sql) or die("Error in User SQL query.");
$arr = array();
while($row= mysql_fetch_assoc($results)){
$arr['avatar'] = $row['avatar'];
$arr['userSelectedIndustry'] = $row['userSelectedIndustry'];
}
return $arr;
}
and the call
$returnedUser = array();
$linkedInID = filter_var($_REQUEST['linkedInID'], FILTER_SANITIZE_STRING);
$returnedUser = getUser($linkedInID);
// Generate the array for the JSON String
$returnedMessage = array(
'status' => 'ok',
'error' => false,
'avatar' => $returnedUser['avatar'],
'userLinkedInIndustry' => $userLinkedInIndustry,
'userSelectedTheme' => $returnedUser['userSelectedTheme'],
'userSelectedIndustry' => $returnedUser['userSelectedIndustry'],
'checksum' => $checksum
);
// JSONify the string and return it
$returnedJSON = json_encode($returnedMessage);
echo $returnedJSON;
many thanks for all time spent, and apologies for not just getting my head down and figuring it out
$data=array();
while($row=$result->fetch_array(MYSQLI_ASSOC))
{
data[]=$row;
}
return $row;

Drupal PHP serialize and unserialize

In Drupal, I first serialized emails that appear in the body of private messages and stored them is MySQL like this:
function prvtmsg_list($body) {
$notify = array();
if (isset($body->emails)) {
$notify['mid'] = $body->mid;
$notify['emails'] = serialize($body->emails);
}
if (isset($body->vulgar_words) {
$notify['mid'] = $body->mid;
$notify['vulgar_words'] = serialize($message->vulgar_words);
}
if (isset($notify['mid'])) {
drupal_write_record('prvtmsg_notify', $notify);
}
}
When I later try to retrieve them, email userialization fails, I retrieve them like this:
function prvtmsg_list_notify() {
// Select fields from prvtmsg_notify and Drupal pm_message tables
$query = db_select('prvtmsg_notify', 'n');
$query->leftJoin('pm_message', 'm', 'n.mid = m.mid');
$query->fields('n', array('mid', 'emails', 'vulgar_words'));
$query->fields('m', array('mid', 'author', 'subject', 'body', 'timestamp'));
orderBy('timestamp', 'DESC');
$query = $query->extend('PagerDefault')->limit(20);
$result = $query->execute()->fetchAll();
$rows = array();
foreach ($result as $notify) {
$rows[] = array(
$notify->author,
$notify->subject,
implode(', ', unserialize($notify->emails)),
implode(', ', unserialize($notify->vulgar_words)),
);
}
$build = array();
$build['table'] = array(
'#theme' => 'table',
'#header' => array(
t('Author'),
t('Message subject'),
t('Emails captured'),
t('Vulgar Words Captured'),
),
'#rows' => $rows,
);
$build['pager']['#theme'] = 'pager';
return $build;
}
Maybe the way I serialized the emails is wrong? because:
dpm(unserialize($notify->emails);
gives Array, Array, Array - which means:
Array(
[0] => Array() [1] => Array() [2] => Array() [3] => Array()
)
Surprisingly, the unserialized vulgar words are showing okay! I'm not sure is it possible to serialize the emails like this:
$notify['emails'] = serialize (array($body->emails));
I faced the exact situation in the past where unserialization did not work for me, there is something not clear to me and I need to learn it. Could anyone confirm or tell me what's wrong?
N.B. The above code is from memory and may not be accurate as I currently don't have access to it.
if i am reading this correctly you are writing an array into a db
drupal_write_record('prvtmsg_notify', $notify);
should be:
drupal_write_record('prvtmsg_notify', serialize($notify));
you will most likely no longer need
$notify['emails'] = serialize($body->emails);
and can instead write:
$notify['emails'] = $body->emails;
after retrieving it from the db you can unserialize the array and iterate over it ex:
$array = unserialize(someFunctionToGetPrvtmsg_notifyFromTheDb());
//the array should be the same as the one you serialized

Categories