codeigniter - compare values - codeigniter

I need to compare two values in a table: cliente and nro_cuota, if both exist I don't want to add it.
Here is my code
$crud = new grocery_CRUD();
$crud->set_theme('datatables');
$crud->set_table('cobranzas');
$crud->set_subject('Cobranzas');
$crud->set_language('spanish');
$crud->required_fields(
'id',
'cobrador',
'cliente',
'nro_cuota'
);
$crud->columns(
'cobrador',
'cliente',
'nro_cuota'
);
$crud->set_relation('cobrador', 'cobradores', 'apellido_nombre');
$crud->set_relation('cliente', 'clientes', 'apellido_nombre');
$output = $crud->render();
$this->load->view('cobranzas/cobranzas_v', $output);
}catch(Exception $e){
show_error($e->getMessage().' --- '.$e->getTraceAsString());
}
}
and I wrote a model, I`m not sure if this is the right way, but I don't know how I must call it
class Compare_values_model extends CI_Model
{
public function compare($id)
{
$this->db->select('"SELECT * FROM `cobranzas` WHERE `cliente` = '$cliente' AND `nro_cuota` = '$nro_cuota'"');
if ($query->num_rows() > 0) {
return true;
} else {
return false;
}
}
}
Hope can help me I couldn't find some examples on internet to learn more, thanks in advance.

You said I need to compare two values in a table: cliente and nro_cuota, if both exist I don't want to add it. But you are matching the variables with fields. So just check not equal as below:
$query = $this->db->query("SELECT * FROM `cobranzas` WHERE `cliente` <> '$cliente' AND `nro_cuota` <> '$nro_cuota'");
Note: Remove extra single quote in your query

Related

How to check name already exist from first result array

i want to check cpt code is already exist in db or not in update form..
so,First i'm checking all cpt codes present in database except post one now i'm getting result without post cpt code....now I want check cpt code from first query result.
my function in controller
public function updatedDxCodeExist()
{
$this->load->model('MedicineModel');
$Id = $this->input->post("Id");
$dxCode = $this->input->post("dxCode");
if(empty($Id))
{
$result = $this->MedicineModel->updatedDxCodeExist($dxCode);
} else {
$result = $this->MedicineModel->updatedDxCodeExist($dxCode, $Id);
}
if(empty($result))
{
echo("true");
}
else
{
echo("false");
}
}
my function in model
public function updatedDxCodeExist($dxCode, $Id =0)
{
$this->db->select("dx_code");
$this->db->from("dx_codes");
$this->db->where('dx_code !=',$dxCode);
$query = $this->db->get();
return $query->result();
}
Actually you can use like this:
if($result->num_row() <= 0 )
{
echo("true");
}
else
{
echo("false");
}
You can use array_search function in codeigniter

codeigniter : Commands out of sync; you can't run this command now

I applied all the possible answers but still same problem.
also tried
$this->db->reconnect();
there is no problem in my query
MyCode:
public function GetdistributorsDetails($username){
$sql = "SELECT u.FirstName, u.Email, u.Telephone, u.MobileNumber, u.AlternateMobileNumber, ud.Address1, ud.Pincode,ud.City,s.Statename FROM users u JOIN userdetails ud ON ud.UserId = u.UserId JOIN states s ON s.StateId = ud.StateId WHERE u.Username = ? ";
$result = $this->db->query($sql,array($username));
return $result->result_array();
}
add following code into /system/database/drivers/mysqli/mysqli_result.php
function next_result()
{
if (is_object($this->conn_id))
{
return mysqli_next_result($this->conn_id);
}
}
then in model when you call Stored Procedure
$query = $this->db->query("CALL test()");
$res = $query->result();
//add this two line
$query->next_result();
$query->free_result();
//end of new code
return $res;
you can use this after call
mysqli_next_result( $this->db->conn_id );
Here is example if you don't want change any thing in mysqli drivers files
$sql = "CALL procedureName(IntParam,'VarcharParm1','VaracharParm2','VarcharParm3');";
$query = $this->db->query($sql);
mysqli_next_result( $this->db->conn_id );
$query->free_result();
these are important line place after to remove the error
mysqli_next_result( $this->db->conn_id );
$query->free_result();
Just use this one if you use multiple query make in same function:
$this->db->close();
If your stored procedure returns more than one result, try to add this code between the queries:
$storedProcedure = 'CALL test(inputParam, #outputParam)';
$this->db->query($storedProcedure);
$conn = $this->db->conn_id;
do {
if ($result = mysqli_store_result($conn)) {
mysqli_free_result($result);
}
} while (mysqli_more_results($conn) && mysqli_next_result($conn));
$sql = 'SELECT #outputParam;';
$this->db->query($sql);
Just add next_result function in
system\database\drivers\mysqli\mysqli_result.php file
public function next_result(){
if(is_object($this->conn_id) && mysqli_more_results($this->conn_id)){
return mysqli_next_result($this->conn_id);
}
}
To call query function
$result = $this->db->query("CALL {$Name}({$Q})",$Param);
$result->next_result();
return $result;

Joomla 2.5 method save()

Is there a way to show the changed values after saving within the Joomla save method?
For example, when I edit a "maxuser" field and save it, I´d like to show the old and the new value.
I tried this by comparing "getVar" and "$post", but both values are the same.
function save()
{
...
$maxuser1 = JRequest::getVar('maxuser');
$maxuser2 = $post['maxuser'];
...
if($maxuser1 != $maxuser2) {
$msg = "Not the same ...";
}
...
}
It's better to override JTable, not the Model. Heres sample code:
public function store($updateNulls = false) {
$oldTable = JTable::getInstance(TABLE_NAME, INSTANCE_NAME);
$messages = array();
if ($oldTable->load($this->id)) {
// Now you can compare any values where $oldTable->param is old, and $this->param is new
// For example
if ($oldTable->title != $this->title) {
$messages[] = "Title has changed";
}
}
$result = parent::store($updateNulls);
if ((count($messages) > 0) && ($result === true)){
$message = implode("\n", $messages);
return $message;
} else {
return $result;
}
}
This will return message string if there are any, true if there are no messages and save succeeded and false if saving failed. So all you have to do is check returned value in model and set right redirect message.
In the controller you can use the postSaveHook which gives you access to the validated values.

Magento Order History Comments: Modify Date

I am creating a script to add orders programmatically in Magento. I need help to change the date of the entries in the Comments History (quote, invoice, shipping, etc.). I can manipulate the date of the order itself (setCreatedAt) and some of the comments related to the creation of the order are correct (e.g. "Sep 29, 2008 8:59:25 AM|Pending Customer Notification Not Applicable"), but I cannot change the date of the comment when I use addStatusHistoryComment...
Here's a snippet of my code:
try {
if(!$order->canInvoice()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice.'));
}
$invoice = Mage::getModel('sales/service_order', $order)->prepareInvoice();
if (!$invoice->getTotalQty()) {
Mage::throwException(Mage::helper('core')->__('Cannot create an invoice without products.'));
}
$invoice->setRequestedCaptureCase(Mage_Sales_Model_Order_Invoice::CAPTURE_OFFLINE);
$invoice->setCreatedAt('2008-09-23 13:05:20');
$invoice->register();
$invoice->getOrder()->setCustomerNoteNotify(true);
$invoice->getOrder()->setIsInProcess(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($invoice)
- >addObject($invoice->getOrder());
$transactionSave->save();
//END Handle Invoice
//START Handle Shipment
$shipment = $order->prepareShipment();
$shipment->setCreatedAt('2008-09-23 14:20:10');
$shipment->register();
$order->setIsInProcess(true);
$order->addStatusHistoryComment('Shipping message goes here...', true);
$shipment->setEmailSent(true);
$transactionSave = Mage::getModel('core/resource_transaction')
->addObject($shipment)
->addObject($shipment->getOrder())
->save();
$track = Mage::getModel('sales/order_shipment_track')
->setShipment($shipment)
->setData('title', 'Some tracking no.')
->setData('number', '111222333444')
->setData('carrier_code', 'fedex') //custom, fedex, ups, usps, dhl
->setData('order_id', $shipment->getData('order_id'))
->save();
//END Handle Shipment
}
catch (Mage_Core_Exception $ex) {
echo "Problem creating order invoice and/or shipment: ".$ex."\n";
}
Thanks in advance.
If I understand your question correctly, you just need to do this:
$comments = $order->getStatusHistoryCollection(true);
$comments now contains a collection of all the status history comments, and you can loop over them with whatever sort of criteria you like.
foreach ($comments as $c) {
if ( /* some stuff */ ) {
$c->setData('created_at',$new_date)->save();
}
}
So this is untested, but should work:
You need to create a new method based off addStatusHistoryComment:
/app/code/core/Mage/Sales/Model/Order.php
/*
* Add a comment to order
* Different or default status may be specified
*
* #param string $comment
* #param string $status
* #return Mage_Sales_Model_Order_Status_History
*/
public function addStatusHistoryComment($comment, $status = false)
{
if (false === $status) {
$status = $this->getStatus();
} elseif (true === $status) {
$status = $this->getConfig()->getStateDefaultStatus($this->getState());
} else {
$this->setStatus($status);
}
$history = Mage::getModel('sales/order_status_history')
->setStatus($status)
->setComment($comment)
->setEntityName($this->_historyEntityName);
->setCreatedAt('2008-09-23 14:20:10'); //I added this line
$this->addStatusHistory($history);
return $history;
}
Obviously you either need to rewrite this method, or refactor the code to do the same.

Joomla 1.5 - JTable queries always doing UPDATE instead of INSERT

The following code is straight from the docs and should insert a row into the "test" table.
$row = &JTable::getInstance('test', 'Table');
if (!$row->bind( array('user_id'=>123, 'customer_id'=>1234) )) {
return JError::raiseWarning( 500, $row->getError() );
}
if (!$row->store()) {
JError::raiseError(500, $row->getError() );
}
My table class looks like this:
class TableTest extends JTable
{
var $user_id = null;
var $customer_id = null;
function __construct(&$db)
{
parent::__construct( '#__ipwatch', 'user_id', $db );
}
}
SELECT queries work fine, but not INSERT ones. Through debugging I find that the query being executed is UPDATE jos_test SET customer_id='1234' WHERE user_id='123', which fails because the row doesn't exist yet in the database (should INSERT instead of UPDATE).
While digging through the Joomla code I find this:
function __construct( $table, $key, &$db )
{
$this->_tbl = $table;
$this->_tbl_key = $key;
$this->_db =& $db;
}
.....
.....
function store( $updateNulls=false )
{
$k = $this->_tbl_key;
if( $this->$k)
{
$ret = $this->_db->updateObject( $this->_tbl, $this, $this->_tbl_key, $updateNulls );
}
else
{
$ret = $this->_db->insertObject( $this->_tbl, $this, $this->_tbl_key );
}
if( !$ret )
{
$this->setError(get_class( $this ).'::store failed - '.$this->_db->getErrorMsg());
return false;
}
else
{
return true;
}
}
_tbl_key here is "user_id" that I passed in my TableTest class, so it would appear that it will always call updateObject() when this key is set. Which is baffling.
Anyone have any insight?
function store( $updateNulls=false )
{
// You set user_id so this branch is executed
if( $this->$k)
{
$ret = $this->_db->updateObject( $this->_tbl, $this, $this->_tbl_key, $updateNulls );
}
// ...
Looking at the code it seems to me that store() check if the primary key field is present and if it use updateObject(). This means if you want to store a new user you can't specify the user_id.

Resources