i have a trouble when retrieve last insert id in codeigniter.
when i try to debug like var_dump();
the output just send int(0)
i use uuid as id with primary key. this is the code:
$this->db->set('id_customer','uuid_short()',FALSE);
$query = $this->db->insert('customer',$data);
$id = $this->db->insert_id();
echo var_dump($id);
if($query)
{
$array = array(
'kode_trans' => 'uuid()',
'trans_date' => 'NOW()'
);
$this->db->set('id_customer','$id');
$this->db->set($array,'',FALSE);
$this->db->insert('transaction_header');
return $id;
}else{
return FALSE;
}
im newbie in ci.
there is something wrong with my code?
The "insert_id" function uses PHP's mysql_insert_id function, which returns "The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value"
You could try it this way;
$id = uuid_short();
$data['id_customer'] = $id;
$query = $this->db->insert('customer', $data);
if ( $query )
{
$array = array(
'kode_trans' => 'uuid()',
'trans_date' => 'NOW()'
);
$query = $this->db->insert('transaction_header', $array);
return $id;
}
else
{
return false;
}
Related
I am doing update in zend which in some cases doesn't update all the fields, the fields that are not updated become null as if we are doing an add.
This is the code from the Controller
$result = $theuserModel->updateUserTest(
$id,
$this->getRequest()->getPost('user_name'),
/*some code*/
$this->getRequest()->getPost('user_postee')
);
if ($result) {
$this->view->notif = "Successfull Update";
return $this->_forward('index');
}
The corresponding model
public function updateUserRest($id, $nom,$poste)
{
$data = array(
'user_name' => $nom,
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
I do an update for user_name only I found that the old value of user_postee got deleted and replaced by the default value (initial value which we get at the time of creation) for example null.
Thanks in advance!
I have done this changes (bad solution) If anyone has another one optimised
->Controller
if($this->getRequest()->getPost('user_name')){
$resultname=$userModel->updateUserName($id,$this-
>getRequest()->getPost('user_name'));
}
if($this->getRequest()->getPost('user_postee')){
$resultpostee=$userModel->updateUserPoste($id,$this-
>getRequest()->getPost('user_postee'));
}
if ($resultname|| $resultpostee){
$this->view->notif = "Mise à jour effectuée";
return $this->_forward('index');
}
-> Model
public function updateUserName($id, $name)
{
$data = array(
'user_name' => $name
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
public function updateUserPostee($id, $postee)
{
$data = array(
'user_postee' => $poste
);
$result=$this->update($data, 'user_id = '. (int)$id);
return $result;
}
that is complete correct response of update in Zend Db Table.
I believe your assumption is if the value of 'user_postee' is null then it should not be updated into the database, am I correct.
The answer is they will update the new value of "NULL" into the database.
To avoid it , what you should do is
using fetchrow() to get the value of the line by id
foreach user_name and user_postee check if the value of them matching the array value your fetched , if nothing changed or Null, then use the old value from array , if new value exist use new value insert into the array , finally use update to update the new array into database
Assume your Table Column is also "user_name" and "user_postee"
public function updateUserRest($id, $nom,$poste)
{
$row = $this->fetchRow('user_id = '. (int)$id);
if(!empty($nom) && $row['user_name'] != trim($nom)){
$row['user_name'] = $nom;
}
if(!empty($poste) && $row['user_poste'] != trim($poste)){
$row['user_poste'] = $poste;
}
$result=$this->update($row, 'user_id = '. (int)$id);
return $result;
}
This is different from Insert based on Keys
I would like to know how to use the array_keys of an array as column names for an update query. The object is that I have a form with all the data a user can update like Gender, Country, Nationality, etc. But say the user only wants to update their Country, therefor array_filter filters the array of all NULL/Empty values. Then I want the keys as names of Columns to update; however, I'd like to know how to bind them together.
Perhaps so they go together like so:
"UPDATE Users SET" . $Columns . "WHERE ID = 5";
I want Columns to be in the format. "Nation = US, Gender = Male" etc.
My current code:
<?php
class Update {
private $UpdateColumn;
private $UpdatedData;
private $ID;
protected $Connect;
protected $Data;
public function __construct($UpdateColumn, $ID) {
try {
$this->Connect = new pdo(****); //Hidden for privacy test server
$this->Connect->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
} catch(PDOException $ex) {
die(json_encode([
'outcome' => false,
'message' => 'Unable to connect'
]));
}
$this->UpdateColumn = $UpdateColumn;
$this->ID = $ID;
}
public function bindData() {
$this->Data = [
$this->UpdateColumn,
$this->ID
];
return $this->Data;
}
public function checkForErrors(){
foreach($this->Data as $Data){
$Error = false;
if(empty($Data)){
$Error = true;
}
if(isNum($Data[1])){
$Error = true;
}
}
return $Error;
}
public function Update() {
$Query = $this->Connect->prepare(
"UPDATE Users SET". $this->Data[0] . "WHERE ID = :ID"
);
$Query->bindValue(":ID", $this->Data[1]);
$Query->execute();
}
public function Redirect(){
return header("Location: /Profile?ID=$this->Data[1]");
}
}
Place to use the code.
<?php
session_start();
require_once("Scripts/PHP/Class/Update.class.php");
$DataUpdate = array_filter($_POST);
$Columns = array_keys($DataUpdate);
$ColumnsToUpdate = implode($Columns, ", ");
//I want to have ColumnsToUpdate look like: Gender = Male, Age = 67, format
//$Update = new Update($ColumnsToUpdate, $DataUpdate, $_SESSION['ID']);
?>
In my case then, I will need an array delimiter which I could use to go through each array_key with it's counterpart data
$Array = array(
"Age" => 9,
"Gender" => "Boy",
"Country" => "",
);
$Array = array_filter($Array);
$Columns = array_keys($Array);
$ColumnToSend = "";
foreach($Array as $Arr => $Key){
$ColumnToSend .= $Arr ."=". $Key . ",";
}
echo($ColumnToSend);
That produces the desired format, but would it work if it was put into a query?
I update a field with saveField method in cakephp.
Example:
$this->Attachment->id = $id;
$updateResult = $this->Attachment->saveField('dispatched', '1');
Now if the value of $id not exist in db then saveField insert a new record in database. But I want to update record instead of new insert. if the value of $id is not exist in db then I want return false from saveField
How I do it?
you have to check if the record exists
if ($this->Attachment->findById($id)) {
$this->Attachment->id = $id;
return $this->Attachment->saveField('dispatched', '1');
} else {
return false;
}
Just wrap your save in a conditional:
$this->Attachment->id = $id;
if(isset($id) {
//your save here
$updateResult = $this->Attachment->saveField('dispatched', '1');
}else{
return false;
}
Update after comment:
So do a count and use this as the test instead:
$settings = array(
'conditions'=>array(
'Atachment.id'=>$id;
)
);
$test = 0;
$test = $this->Attachment->find('count', $settings);
if($test >0 {
//your save here
} else {
//return false here
}
Should do it.
I'm trying to get the data from array in my controller php on Cakephp.
I have this function:
public function updateUserStatus() {
if(isset($this->params['url']["pcs"])) {
$uus = array( "pcs" =>$this->params['url']["pcs"] );
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
And I want to get the data from status_id who have this response:
Array (
[0] => Array
(
[status_id] => 2
)
[1] => Array
(
[rem_time] => 66
)
)
How can I do it?
My question is how can i get the data for status_id ?
public function updateUserStatus() {
if (isset($this->params['url']["pcs"])) {
$uus = array("pcs" =>$this->params['url']["pcs"]);
$trans = $this->Transaction->updateUserStatus($uus);
} else {
$trans = "failed";
}
$currentStatus = 0;
if (is_array($trans) && isset($trans['status_id'])) {
$currentStatus = $trans['status_id'];
}
$this->set('trans', $trans);
$this->layout = 'ajax';
}
public function updateUserStatus($uus){
if(isset($uus["pcs"])) {
$sql = "SELECT status_id as status_id , rem_time as rem_time FROM phones WHERE pcs = '".$uus["pcs"]."' LIMIT 1";
$query = $this->query($sql);
return $query[0]['phones'];
} else {
return "failed";
}
}
Notice, we are returning $query[0]['phones'].
Let me know if it works.
The code could also use some refactoring.
For example, why is the function called updateUserStatus if it is only returning the result of a query? It should also always return an array, for consistency.
Can someone give me a hint what I am doing wrong?
public function getPaymentSumByTypeAndProject($project_id,$type) {
$type = (int) $type;
$project_id = (int) $project_id;
$rowset = $this->tableGateway->select(array('total_amount' => new Expression('SUM(payment.amount)')))->where(array('type' => $type, 'project_id' => $project_id));
$row = $rowset->toArray();
if (!$row) {
throw new \Exception("Busted :/");
}
return $rowset;
}
I want to make the same query:
SELECT SUM(amount) FROM payment WHERE type='$type' AND project_id ='$project_id';
Edit:
I made small progress, i have figured out how to sum whole column
public function getPaymentSumByTypeAndProject($project_id, $type) {
$type = (int) $type;
$project_id = (int) $project_id;
$resultSet = $this->tableGateway->select(function (Select $select) {
$select->columns(array(new \Zend\Db\Sql\Expression('SUM(amount) as amount')))->where('type="0"');
});
return $resultSet;
Maybe someone could help me to figure out how to add condition: "WHERE type='$type' AND project_id='$project_id'" ?
I know this is an old question, but I came across it and figured I'd throw in my two cents:
public function getPaymentSumByTypeAndProject($project_id, $type) {
// This TableGateway is already setup for the table 'payment'
// So we can skip the ->from('payment')
$sql = $this->tableGateway->getSql();
// We'll follow the regular order of SQL ( SELECT, FROM, WHERE )
// So the query is easier to understand
$select = $sql->select()
// Use an alias as key in the columns array instead of
// in the expression itself
->columns(array('amount' => new \Zend\Db\Sql\Expression('SUM(amount)')))
// Type casting the variables as integer can take place
// here ( it even tells us a little about the table structure )
->where(array('type' => (int)$type, 'project_id' => (int)$project_id));
// Use selectWith as a shortcut to get a resultSet for the above select
return $this->tableGateway->selectWith($select);
}
Also, an adapter can be retrieved from a table gateway like this:
$adapter = $this->tableGateway->getAdapter();
But you don't really need it anymore when you select using the above mentioned method.
Ok now this is working, tell me is this how it;s should be done?
public function getPaymentSumByTypeAndProject($project_id, $type) {
$type = (int) $type;
$project_id = (int) $project_id;
$adapter = $this->tableGateway->adapter;
$sql = new Sql($adapter);
$select = $sql->select();
$select->from('payment');
$select->where(array('type'=>$type,'project_id'=>$project_id));
$select->columns(array(new \Zend\Db\Sql\Expression('SUM(amount) as amount')));
$selectString = $sql->getSqlStringForSqlObject($select);
$resultSet = $adapter->query($selectString, $adapter::QUERY_MODE_EXECUTE);
return $resultSet;
}
use This one
$select = $this->getSql()->select()
->columns(array('amount' => new \Zend\Db\Sql\Expression('SUM(amount)')))
->where("type ='$type'")
->where("project_id ='$project_id'");
$resultSet = $this->selectWith($select);
$row = $resultSet->current();
// echo $select->getSqlString();die; //check query use this line
if(!$row){
return False;
}
return $row->amount;
try to make like that instead of (int) $type
intval($type);
and
intval($project_id);
and in your sql
change your variables to
'".$type."'
AND
'".$project_id."'