I have this code:
function saveField($field, $id, $module, $value)
{
$bean = BeanFactory::getBean($module, $id);
if (is_object($bean) && $bean->id != "") {
if ($bean->field_defs[$field]['type'] == "multienum") {
$bean->$field = encodeMultienumValue($value);
}else if ($bean->field_defs[$field]['type'] == "relate" || $bean->field_defs[$field]['type'] == 'parent'){
$save_field = $bean->field_defs[$field]['id_name'];
$bean->$save_field = $value;
if ($bean->field_defs[$field]['type'] == 'parent') {
$bean->parent_type = $_REQUEST['parent_type'];
$bean->fill_in_additional_parent_fields(); // get up to date parent info as need it to display name
}
}else{
$bean->$field = $value;
}
//return here will work
$bean->save(); //this works
//nothing works here
return getDisplayValue($bean, $field);
} else {
return false;
}
}
The problem here is that anything under
$bean->save()
will not work. But I know that save is working as the values are being updated. So how can I debug this problem?
I already tried:
return var_dump($bean->save());
return print_r($bean->save());
if($bean->save()){
return "1";
}else{
return "2";
}
And none of those in the above worked I still get nothing in my return.
There is likely something such as an after_save logic hook that is executing and either causing a fatal error or doing an exit.
Try using xdebug, it should allow you to investigate further into the save method that fails.
Related
I am trying to insert more than 100 records at a time. if more records them form will not perform any action unless it will submit and redirect to another page.
How to sove this error.
I tried using insert_batch also. But no use.
I changed php.ini post_max_size also,
Somebody please help me.
Below is my code for controller and model
controller code
foreach($chkproduct as $key=>$chkvalue1){
foreach($chkvalue1 as $key1=>$chkvalue2 ) {
$chkvalue=explode("/",$chkvalue2);
$datachk['product_id'] =$chkvalue[0];
$datachk['client_id']=$chkvalue[1];
$ins1=$this->Sub_model->record_count_Product($chkvalue[0]);
$num1=$ins1->num_rows();
$qry1=$ins1->row();
$prodId=$qry1->prod_rand_id;
$datachk['payment_id']=$paymentid;
$datachk['prod_rand_id']=$prodId;
$datachk['sub_type'] =$st1[$chkvalue[0]][$key1];
$datachk['prod_type'] =$pt1[$chkvalue[0]][$key1];
$datachk['quantity'] =$qty1[$chkvalue[0]][$key1];
$datachk['reductionamount'] =$redamount[$chkvalue[0]][$key1];
$datachk['amountafterreduction'] =$ramount[$chkvalue[0]][$key1];
$datachk['individual_amt'] =$ramount[$chkvalue[0]][$key1]+$redamount[$chkvalue[0]][$key1];
$cliname=$clientname[$chkvalue[0]][$key1];
//$date1=$sd1[$chkvalue];
//$datachk['start_date'] = date('Y-m-d', strtotime($date1));
$cliname=$clientname[$chkvalue[0]][$key1];
$expper=explode("-",$per1[$chkvalue[0]][$key1]);
//echo $expper[0];
$smonth=$this->check($expper[0]);
if($smonth>=10){
$startyear=$year1[$chkvalue[0]][$key1]-1;
}else{
$startyear=$year1[$chkvalue[0]][$key1];
}
//echo $st1[$chkvalue];
if($st1[$chkvalue[0]][$key1]==1){
$endyear=$year1[$chkvalue[0]][$key1];
}elseif($st1[$chkvalue[0]][$key1]==2){
if($smonth>=02 && $smonth<=10){$endyear=$year1[$chkvalue[0]][$key1]+1;}else{$endyear=$year1[$chkvalue[0]][$key1];}
}elseif($st1[$chkvalue[0]][$key1]==3){
if($smonth>=02 && $smonth<=10){$endyear=$year1[$chkvalue[0]][$key1]+3;}else{$endyear=$year1[$chkvalue[0]][$key1]+2;}
}
//echo $endyear;
if($smonth==01){$endmonth=12;}else{$endmonth=$smonth-01;}
$ts = strtotime($expper[0]."".$startyear);
$lastdate=date('t', $endmonth);
if($endmonth=='02'){
if($endyear%4==0){
$lastdate1=29;
}else{
$lastdate1=28;
}
}
elseif($endmonth=='04' || $endmonth=='06' || $endmonth=='09' || $endmonth=='11'){
$lastdate1=30;
}else{
$lastdate1=31;
}
//if($endmonth=='02'){$lastdate1=$lastdate-2;}elseif($endmonth%2==1){$lastdate1=30;}else{$lastdate1=31;}
$datachk['start_date'] =$startyear."-".$smonth."-01";
$datachk['end_date'] =$endyear."-".$endmonth."-".$lastdate1;
$datachk['periodicityno'] = $per1[$chkvalue[0]][$key1];
$datachk['year'] = $year1[$chkvalue[0]][$key1];
$datachk['product_status'] =$ps1[$chkvalue[0]][$key1];
if($comboval == 1 && $datachk['reductionamount']!=0){
$datachk['combostatus']=1;
}else{
$datachk['combostatus']=0;
}
$pbyp1=$this->Sub_model->getProductByperiodicity($chkvalue[0]);
$datapdf['products'][]=array("pname"=>$pbyp1->productname,"cliname"=>$cliname,"abbr"=>$pbyp1->productshortname,"pername"=>$datachk['periodicityno'],
"year"=>$datachk['year'],"subtype"=>$st1[$chkvalue[0]][$key1],"perno"=>$pbyp1->periodicity,"dur"=>$pbyp1->duration,"randid"=>$prodId,"prodid"=>$chkvalue[0]);
$this->Sub_model->addSubscribedProduct($datachk);
}
}
Model
function addSubscribedProduct($data) {
foreach ($data as $key => $value) {
if ($value=="") {
$array[$key] =0;
}else{
$array[$key] =$value;
}
}
$res = $this->db->insert('iman_subscribed_products', $array);
//$res = $this->db->insert_batch('iman_subscribed_products', $array);
//echo $sql = $this->db->last_query();
if($res) {
return 1;
} else {
return 0;
}
}
Screen shot of my form
i think you stumpled into php's max_input_vars option
the standard value for this is 1000
just change your value to something higher than that
Be aware you can't change it with ini_set.
For more information click here.
User insert_batch() instead of insert() as follows:
$this->db->insert_batch(array)); // Here the array is multidimensional which can contain number of rows as you need 100s.
I'm working on implementing some geoIP functionality to redirect a user away from my .com site to the relevant country domain (.fr, .es, .co.uk ...etc).
I've the following in my index.php to check the users IP:
ini_set('display_errors', 1);
require_once("geoip.inc");
$gi = geoip_open("GeoIP.dat",GEOIP_STANDARD);
$country_code = geoip_country_code_by_addr($gi, $_SERVER['REMOTE_ADDR']);
geoip_close($gi);
if($country_code == 'ES')
{
header('Location: https://www.testsite.es');
}
elseif($country_code == 'GB')
{
header('Location: https://www.testsite.co.uk');
}
elseif($country_code == 'FR')
{
header('Location: https://www.testsite.fr');
}
else {
header('Location: https://www.testsite.com/home');
}
When I check the $country_code variable it is an empty String and as a result the above fails and I always hit https://www.testsite.com/home...
I started delving into the code and noticed that first I call this method:
function geoip_country_code_by_addr($gi, $addr) {
if ($gi->databaseType == GEOIP_CITY_EDITION_REV1) {
$record = geoip_record_by_addr($gi, $addr);
if ($record !== false) {
return $record->country_code;
}
} else {
$country_id = geoip_country_id_by_addr($gi, $addr);
if ($country_id !== false) {
return $gi->GEOIP_COUNTRY_CODES[$country_id];
}
}
return false;
}
which calls:
function geoip_country_id_by_addr($gi, $addr) {
$ipnum = ip2long($addr);
return _geoip_seek_country($gi, $ipnum) - GEOIP_COUNTRY_BEGIN;
}
I can't figure out why it keeps failing and returning a '0'? I am using Maxminds geoip.inc php to check the country code.
I've checked that mbstring is enabled within my php.ini file and it is. For some reason it just doesn't find the Country code based on the IP I pass to it. Does anyone have any help in terms of what might be causing this?
just wanted to say that I've resolved the issue. A mistake on my part and probably a sign that I need a break!
Within geoip.inc.php supplied by Maxmind I was initially getting these errors:
Cannot redeclare geoip_country_code_by_name() in geoip.inc on line 438
In order to fix this I simply check if the method is defined and if not I use it as follows:
if (!function_exists('geoip_country_code_by_name')) {
function geoip_country_code_by_name($gi, $name) {
$country_id = geoip_country_id_by_name($gi, $name);
if ($country_id !== false) {
return $gi->GEOIP_COUNTRY_CODES[$country_id];
}
return false;
}
}
I unfortunately had a minor typo in the above code which prevented the code from executing properly hence returing 0 each and every time.
so I have this code for my db transactions:
$to_return = true;
$this->db->trans_begin();
$this->insert_arrest_details($data);
$this->update_barangay($data['barangay_id']);
$this->insert_arresting_officers($data);
$folders = $this->insert_violators($data);
$this->insert_arrest_booking_form($data);
$this->insert_case_report($data);
$this->insert_seizing_officers($data['case_id'],json_decode($data['seizing_officers']));
$this->insert_items(json_decode($data['items']));
$this->insert_nitems(json_decode($data['nitems']));
$this->insert_violator_items(json_decode($data['items']));
$this->insert_violator_nitems(json_decode($data['nitems']));
if($this->db->trans_status() === FALSE){
$array['error_message'] = $this->db->_error_message();
$array['error_number'] = $this->db->_error_number();
$this->db->trans_rollback();
$to_return = $array;
}else{
$img_success = $this->move_violators_images($folders);
$img_success = $this->move_items_images($data['case_id']);
$img_success = 1;
if($img_success == 1){
$this->db->trans_commit();
}else{
$this->db->trans_rollback();
$to_return = false;
}
}
return $to_return;
My problem is, if the error (for example) occurs in $this->insert_arrest_details(); My code doesn't get the error. It returns something like this:
"error_message":"","error_number":0
But when I tried to run 1 method only and that method failed, my code was able to get the error. why is that so?
Your responses will be greatly appreciated.
I am trying to GET different rows from different columns in php/mysql, and pack them into an array. I am able to successfully GET a jason encoded array back IF all values in the GET string match. However, if there is no match, the code echos 'no match', and without the array. I know this is because of the way my code is formatted. What I would like help figuring out, is how to format my code so that it just displays "null" in the array for the match it couldn't find.
Here is my code:
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode($fbaddra);
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['addr'];
} else {
$fbaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['addr'];
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
UPDATE: The GET Request
I would like the GET request below to return the full array, with whatever value that didn't match as 'null' inside the array.
domain.com/api/core/engine.php?a=fbaddra&facebook=username&facebookp=pagename
The GET above currently returns null.
Requests that work:
domain.com/api/core/engine.php?a=fbaddra&facebook=username or domain.com/api/core/engine.php?a=fbaddra&facebookp=pagename
These requests return the full array with the values that match, or null for the values that don't.
TL;DR
I need assistance figuring out how to format code to give back the full array with a value of 'null' for no match found in a row.
rather than assigning as 'null' assign null. Your full code as follows :
include '../db/dbcon.php';
$res = $mysqli->query($q1) or trigger_error($mysqli->error."[$q1]");
if ($res) {
if($res->num_rows === 0)
{
echo json_encode('no match');
}
else
{
while($row = $res->fetch_array(MYSQLI_BOTH)) {
if($_GET['a'] == "fbaddra") {
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = null;
}
if ($row['facebookp'] === $_GET['facebookp']) {
$fbpaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fbpaddr = null;
}
$fbaddra = (array('facebook' => $fbaddr, 'facebookp' => $fbpaddr));
echo json_encode($fbaddra);
}
}
}
$mysqli->close();
You can even leave else part altogether.
Check your code in this fragment you not use same names for variables:
if ($row['facebook'] === $_GET['facebook']) {
$fbaddr = $row['dogeaddr'];
//echo json_encode($row['dogeaddr']);
} else {
$fpaddr = 'null';
}
$fbaddr not is same as $fpaddr, this assign wrong result to if statement.
It was the mysql query that was the problem.
For those who come across this, and need something similar, you'll need to format your query like this:
** MYSQL QUERY **
if ($_GET['PUTVALUEHERE']) {
$g = $_GET['PUTVALUEHERE'];
$gq = $mysqli->real_escape_string($g);
$q1 = "SELECT * FROM `addrbook` WHERE `facebookp` = '".$gq."' OR `facebook` = '".$gq."'";
}
** PHP CODE **
if($_GET['PUTVALUEHERE']{
echo json_encode($row['addr']);
}
I am working with SilverStripe, and I am working on making a newspage.
I use the DataObjectAsPage Module( http://www.ssbits.com/tutorials/2012/dataobject-as-pages-the-module/ ), I got it working when I use the admin to publish newsitems.
Now I want to use the DataObjectManager Module instead of the admin module to manage my news items. But this is where the problem exists. Everything works fine in draft mode, I can make a new newsitem and it shows up in draft. But when I want to publish a newsitem, it won't show up in the live or published mode.
I'm using the following tables:
-Dataobjectaspage table,
-Dataobjectaspage_live table,
-NewsArticle table,
-NewsArticle_Live table
The Articles have been inserted while publishing in the Dataobjectaspage table and in the NewsArticle table... But not in the _Live tables...
Seems the doPublish() function hasn't been used while 'Publishing'.
So I'm trying the use the following:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
But when I use this, it gets an error:
here is this picture
It seems to be in a loop....
I've got the NewsArticle.php file where I use this function:
function onAfterWrite() {
parent::onAfterWrite();
DataObjectAsPage::doPublish();
}
This function calls the DataObjectAsPage.php file and uses this code:
function doPublish() {
if (!$this->canPublish()) return false;
$original = Versioned::get_one_by_stage("DataObjectAsPage", "Live", "\"DataObjectAsPage\".\"ID\" = $this->ID");
if(!$original) $original = new DataObjectAsPage();
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onBeforePublish', $original);
$this->Status = "Published";
//$this->PublishedByID = Member::currentUser()->ID;
$this->write();
$this->publish("Stage", "Live");
// Handle activities undertaken by decorators
$this->invokeWithExtensions('onAfterPublish', $original);
return true;
}
And then it goes to DataObject.php file and uses the write function ():
public function write($showDebug = false, $forceInsert = false, $forceWrite = false, $writeComponents = false) {
$firstWrite = false;
$this->brokenOnWrite = true;
$isNewRecord = false;
if(self::get_validation_enabled()) {
$valid = $this->validate();
if(!$valid->valid()) {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
throw new ValidationException($valid, "Validation error writing a $this->class object: " . $valid->message() . ". Object not written.", E_USER_WARNING);
return false;
}
}
$this->onBeforeWrite();
if($this->brokenOnWrite) {
user_error("$this->class has a broken onBeforeWrite() function. Make sure that you call parent::onBeforeWrite().", E_USER_ERROR);
}
// New record = everything has changed
if(($this->ID && is_numeric($this->ID)) && !$forceInsert) {
$dbCommand = 'update';
// Update the changed array with references to changed obj-fields
foreach($this->record as $k => $v) {
if(is_object($v) && method_exists($v, 'isChanged') && $v->isChanged()) {
$this->changed[$k] = true;
}
}
} else{
$dbCommand = 'insert';
$this->changed = array();
foreach($this->record as $k => $v) {
$this->changed[$k] = 2;
}
$firstWrite = true;
}
// No changes made
if($this->changed) {
foreach($this->getClassAncestry() as $ancestor) {
if(self::has_own_table($ancestor))
$ancestry[] = $ancestor;
}
// Look for some changes to make
if(!$forceInsert) unset($this->changed['ID']);
$hasChanges = false;
foreach($this->changed as $fieldName => $changed) {
if($changed) {
$hasChanges = true;
break;
}
}
if($hasChanges || $forceWrite || !$this->record['ID']) {
// New records have their insert into the base data table done first, so that they can pass the
// generated primary key on to the rest of the manipulation
$baseTable = $ancestry[0];
if((!isset($this->record['ID']) || !$this->record['ID']) && isset($ancestry[0])) {
DB::query("INSERT INTO \"{$baseTable}\" (\"Created\") VALUES (" . DB::getConn()->now() . ")");
$this->record['ID'] = DB::getGeneratedID($baseTable);
$this->changed['ID'] = 2;
$isNewRecord = true;
}
// Divvy up field saving into a number of database manipulations
$manipulation = array();
if(isset($ancestry) && is_array($ancestry)) {
foreach($ancestry as $idx => $class) {
$classSingleton = singleton($class);
foreach($this->record as $fieldName => $fieldValue) {
if(isset($this->changed[$fieldName]) && $this->changed[$fieldName] && $fieldType = $classSingleton->hasOwnTableDatabaseField($fieldName)) {
$fieldObj = $this->dbObject($fieldName);
if(!isset($manipulation[$class])) $manipulation[$class] = array();
// if database column doesn't correlate to a DBField instance...
if(!$fieldObj) {
$fieldObj = DBField::create('Varchar', $this->record[$fieldName], $fieldName);
}
// Both CompositeDBFields and regular fields need to be repopulated
$fieldObj->setValue($this->record[$fieldName], $this->record);
if($class != $baseTable || $fieldName!='ID')
$fieldObj->writeToManipulation($manipulation[$class]);
}
}
// Add the class name to the base object
if($idx == 0) {
$manipulation[$class]['fields']["LastEdited"] = "'".SS_Datetime::now()->Rfc2822()."'";
if($dbCommand == 'insert') {
$manipulation[$class]['fields']["Created"] = "'".SS_Datetime::now()->Rfc2822()."'";
//echo "<li>$this->class - " .get_class($this);
$manipulation[$class]['fields']["ClassName"] = "'$this->class'";
}
}
// In cases where there are no fields, this 'stub' will get picked up on
if(self::has_own_table($class)) {
$manipulation[$class]['command'] = $dbCommand;
$manipulation[$class]['id'] = $this->record['ID'];
} else {
unset($manipulation[$class]);
}
}
}
$this->extend('augmentWrite', $manipulation);
// New records have their insert into the base data table done first, so that they can pass the
// generated ID on to the rest of the manipulation
if(isset($isNewRecord) && $isNewRecord && isset($manipulation[$baseTable])) {
$manipulation[$baseTable]['command'] = 'update';
}
DB::manipulate($manipulation);
if(isset($isNewRecord) && $isNewRecord) {
DataObjectLog::addedObject($this);
} else {
DataObjectLog::changedObject($this);
}
$this->onAfterWrite();
$this->changed = null;
} elseif ( $showDebug ) {
echo "<b>Debug:</b> no changes for DataObject<br />";
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Clears the cache for this object so get_one returns the correct object.
$this->flushCache();
if(!isset($this->record['Created'])) {
$this->record['Created'] = SS_Datetime::now()->Rfc2822();
}
$this->record['LastEdited'] = SS_Datetime::now()->Rfc2822();
} else {
// Used by DODs to clean up after themselves, eg, Versioned
$this->extend('onAfterSkippedWrite');
}
// Write ComponentSets as necessary
if($writeComponents) {
$this->writeComponents(true);
}
return $this->record['ID'];
}
Look at the $this->onAfterWrite();
It probably goes to my own function on NewsArticle.php and there starts the loop! I'm not sure though, so i could need some help!!
Does anyone knows how to use the doPublish() function?
The reason that is happening is that in the DataObjectAsPage::publish() method, it is calling ->write() - line 11 of your 3rd code sample.
So what happens is it calls ->write(), at the end of ->write() your onAfterWrite() method is called, which calls publish(), which calls write() again.
If you remove the onAfterWrite() function that you've added, it should work as expected.
The doPublish() method on DataObjectAsPage will take care of publishing from Stage to Live for you.