zend update is deleting old values - php

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;
}

Related

Multiple Insert with dropdown codeigntier

I have3 table with name frm_data_aset,frm_monitor,frm_lokasi
I want if I insert on frm_data_aset column monitor_aset with dropdown from tabel monitor and lokasi from tabel lokasi. on table monitor column lokasi updated with data same at I insert from tabel data_Aset
this my structure :
enter image description here
enter image description here
now I get error :
Unknown column 'frm_monitor' in 'where clause'
UPDATE frm_monitor SET lokasi_monitor = '123' WHERE frm_monitor IS NULL
this my controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id= $this->input->post('kd_monitor', TRUE);
$data = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data);
$this->M_data_aset->insert($data);
redirect(site_url('data_aset'));
}
}
this my model M_monitor
function update_lokasi($id,$data){
$this->db->where('frm_monitor', $id);
$this->db->update('frm_monitor', $data);
}
and this my dropdown monitor at form insert data_aset
<option value="0">Pilih Monitor</option>
<?php
$monitor = $this->db->get('frm_monitor')->result();
foreach ($monitor as $row){
echo "<option value='$row->kd_monitor' ";
echo $row->kd_monitor==$monitor_aset?'selected':'';
echo ">". strtoupper($row->kd_monitor)."</option>";
}
?>
try changing your model query as like this
function update_lokasi($id,$data){
$this->db->where('id_monitor', $id);
$this->db->update('frm_monitor', $data);
}
Before that make sure that the post for 'kd_monitor' in the controller is not null
You should rename the $data variable being passed to $this->M_monitor->update_lokasi() because it will overwrite $data that is going to be passed to $this->M_data_aset->insert() with only 'lokasi_monitor' array on it. Or even better try rename both $data to prevent confusion.
Modify your controller :
{
$this->_rules();
if ($this->form_validation->run() == FALSE) {
$this->create();
} else {
$data_aset = array(
'lokasi_aset' => $this->input->post('lokasi_aset',TRUE),
'monitor_aset' => $this->input->post('monitor_aset',TRUE),
);
$id = $this->input->post('kd_monitor', TRUE);
$data_monitor = array(
'lokasi_monitor' => $this->input->post('lokasi_aset'),
);
$this->M_monitor->update_lokasi($id,$data_monitor);
$this->M_data_aset->insert($data_aset);
redirect(site_url('data_aset'));
}
}
And change 'frm_monitor' to 'kd_monitor' on the conditional query :
function update_lokasi($id,$data){
$this->db->where('kd_monitor', $id);
$this->db->update('frm_monitor', $data);
}

MySQL Update with field being a concatenated string

function updateUser($userData, $statsID) {
$fields = '';
$config = 0;
while(list($key,$val)= each($userData)) {
if($config++ != 0){
$fields .= ' , ';
}
$col = $key;
$val = $val;
$fields .= "$col='$val'";
}
//echo $fields;
global $dbhandle;
$query = mysqli_query($dbhandle, "UPDATE data SET $fields WHERE statsID = '$statsID'");
echo var_export($query); <--returns NULL
In this code, I pass in an array as noted below:
$sendData = array('name'=>$name,'race'=>$race,'rank'=>$rank,'highestRank'=>$highestRank,'commander'=>$commander,'atkSld'=>$atkSld,'atkMerc'=>$atkMerc,'defSld'=>$defSld,'defMerc'=>$defMerc,'untSld'=>$untSld,'untMerc'=>$untMerc,'spies'=>$spies,'sentries'=>$sentries,'morale'=>$morale,'tff'=>$tff,'strike'=>$strike,'strikeRank'=>$strikeRank,'defense'=>$defense,'defenseRank'=>$defenseRank,'spy'=>$spy, 'spyRank'=>$spyRank, 'sentry'=>$sentry, 'sentryRank'=>$sentryRank, 'fort'=>$fort,'siege'=>$siege,'economy'=>$economy,'tech'=>$tech,'conscription'=>$conscription,'gold'=>$gold,'tbg'=>$tbg,'gameTurns'=>$gameTurns,'covertLvl'=>$covertLvl);
I have confirmed all the data is set and correct. The statsID passes in correctly and when I echo field, it gives me exactly what is required to fulfill my query and in the correct format (key='value' , key ='value' , key ='value etc)
EDIT: Problem solved, I have updated my code to reflect the solution. For some reason I had to call global $dbhandle prior to the query string. If someone could tell me why that would be great!

PHP failed to load string from other function as parameter

public function test_passing_string() {
$this - > load - > model(array('registration/Registration_model', 'Jawaban_lab_model'));
$registration = new Registration_model();
$jawaban_lab = new Jawaban_lab_model();
$id = "kuda4";
$jawaban_lab - > load($id); //load jawaban_lab from id
$manualy_written_registration_number = "REG/FM/130102-0001";
echo "registration number from jawaban_lab->registration_number : ".$jawaban_lab - > registration_number
.
"<br> registration number from manualy_written_registration_number : ".$manualy_written_registration_number;
//$registration->load($jawaban_lab->registration_number);
$registration - > load($manualy_written_registration_number);
echo "<br> patient id : ".json_encode($registration - > PatientID);
}
Before go to the question, I will explain my code.
On test_passing_string() function, I call 2 model, and create object for each model there are $registration and $jawaban_lab.
To load data from model I create a load() function. load() has two parameters: column_value and column_name. The default value for column_name is that model's Primary Key.
BUT
The problem comes from
$registration->load($jawaban_lab->registration_number);
I can't retrieve any $registration object data, then I test it by passing the value manually by write this:
$manualy_written_registration_number = "REG/FM/130102-0001";
$registration - > load($manualy_written_registration_number);
And the result appear, doesn't that mean my load() function is fine?
Then I check value inside $jawaban_lab->registration_number by echoing it, surprisingly it display same value as my $manualy_written_registration_number variable.
This is screenshoot in my browser when I run test_passing_string() function:
Using $manualy_written_registration_number value
Using $jawaban_lab->registration_number value
Why can't I use the value from
$jawaban_lab->registration_number even though it has the same value as
my manually writen registraiton number?
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
// using custom column.
$query = $this->dbs->get_where($this::DB_TABLE, array(
$column_name => $column_value
));
} else {
// using column primary key .
$query = $this->dbs->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $column_value
));
}
if ($query->row()) {
$this->populate($query->row());
}
}
I use multiple database using CodeIgniter 3, registration_model from SQL server and jawaban_lab from MySQL, jawaban lab have column registration_number to store registration_model primary key
var_dump
First of all thanks to rlanvin and Nirajan N Raju
from rlanvin's comment, i find out the problem is come from codeigniter's query helper, because when i enable codeigniter profiling sql server query return "SELECT CASE WHEN (##OPTIONS | 256) = ##OPTIONS THEN 1 ELSE 0 END AS qi"
so i think codeigniter might be cannot generate query so i create the query manually
i change
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
// using custom column.
$query = $this->dbs->get_where($this::DB_TABLE, array(
$column_name => $column_value
));
} else {
// using column primary key .
$query = $this->dbs->get_where($this::DB_TABLE, array(
$this::DB_TABLE_PK => $column_value
));
}
if ($query->row()) {
$this->populate($query->row());
}
}
to this
public function load($column_value, $column_name = NULL) {
$query = NULL;
if ($column_name != NULL) {
$query = $this->dbs->query("SELECT * FROM " . $this::DB_TABLE . " WHERE " . $column_name . " LIKE '" . trim($column_value) . "'");
} else {
$query = $this->dbs->query("SELECT * FROM " . $this::DB_TABLE . " WHERE " . $this::DB_TABLE_PK . " LIKE '" . trim($column_value) . "'");
}
if ($query->row()) {
$this->populate($query->row());
}
}

how to retrieve last insert id in uuid codeigniter

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;
}

Class returns integer instead of object while trying to get column data

Just getting into OOP, and changing from mysql queries to PDO. I am trying to create a class that will return the column names and meta data for a table. This is so I can output copy/paste data for all the tables I use. I have used such a tool, based on the mysql extension, for ages and it spits out variants such as complete SELECT/INSERT/UPDATE queries. Amongst other things I now want to add DECLARE listings for Stored Procedures - so getting meta data like type and length are essential. With about 150 tables across two schemas, such automation is essential.
With uncertainty about the reliability of getColumnMeta I hunted for code and found what looked good in a Sitepoint answer. I have attempted to wrap it in a class and mimic its original context but I am simply getting a number 1 when I try to echo or print_r the response. I have also had 'not an object' error messages while trying solutions.
This is the calling code
$db_host="localhost";
$db_username='root';
$db_pass='';
$db_name='mydatabase';
try{
$db= new PDO('mysql:host='.$db_host.';dbname='.$db_name,$db_username,$db_pass, array(PDO::ATTR_PERSISTENT=>false));
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING);
}
catch(PDOException $e){echo "Error: ".$e->getMessage()."<br />"; die(); }
include 'ColMetaData.php'; //the file containing the class for getting a column listing for each table
$coldat= new supplyColumnMeta($db);
$tablemet=$coldat->getColumnMeta('groups'); // a manual insertion of a table name for testing
echo $tablemet;
And this is the class that sits in the include file
class supplyColumnMeta{
public function __construct($db){
$this->db=$db;
}
/**
* Automatically get column metadata
*/
public function getColumnMeta($table)
{$this->tableName=$table;
// Clear any previous column/field info
$this->_fields = array();
$this->_fieldMeta = array();
$this->_primaryKey = NULL;
// Automatically retrieve column information if column info not specified
if(count($this->_fields) == 0 || count($this->_fieldMeta) == 0)
{
// Fetch all columns and store in $this->fields
$columns = $this->db->query("SHOW COLUMNS FROM " . $this->tableName, PDO::FETCH_ASSOC);
foreach($columns as $key => $col)
{
// Insert into fields array
$colname = $col['Field'];
$this->_fields[$colname] = $col;
if($col['Key'] == "PRI" && empty($this->_primaryKey)) {
$this->_primaryKey = $colname;
}
// Set field types
$colType = $this->parseColumnType($col['Type']);
$this->_fieldMeta[$colname] = $colType;
}
}
return true;
}
protected function parseColumnType($colType)
{
$colInfo = array();
$colParts = explode(" ", $colType);
if($fparen = strpos($colParts[0], "("))
{
$colInfo['type'] = substr($colParts[0], 0, $fparen);
$colInfo['pdoType'] = '';
$colInfo['length'] = str_replace(")", "", substr($colParts[0], $fparen+1));
$colInfo['attributes'] = isset($colParts[1]) ? $colParts[1] : NULL;
}
else
{
$colInfo['type'] = $colParts[0];
}
// PDO Bind types
$pdoType = '';
foreach($this->_pdoBindTypes as $pKey => $pType)
{
if(strpos(' '.strtolower($colInfo['type']).' ', $pKey)) {
$colInfo['pdoType'] = $pType;
break;
} else {
$colInfo['pdoType'] = PDO::PARAM_STR;
}
}
return $colInfo;
}
/**
* Will attempt to bind columns with datatypes based on parts of the column type name
* Any part of the name below will be picked up and converted unless otherwise sepcified
* Example: 'VARCHAR' columns have 'CHAR' in them, so 'char' => PDO::PARAM_STR will convert
* all columns of that type to be bound as PDO::PARAM_STR
* If there is no specification for a column type, column will be bound as PDO::PARAM_STR
*/
protected $_pdoBindTypes = array(
'char' => PDO::PARAM_STR,
'int' => PDO::PARAM_INT,
'bool' => PDO::PARAM_BOOL,
'date' => PDO::PARAM_STR,
'time' => PDO::PARAM_INT,
'text' => PDO::PARAM_STR,
'blob' => PDO::PARAM_LOB,
'binary' => PDO::PARAM_LOB
);
}
Here's the problem:
public function getColumnMeta($table)
{
$this->tableName=$table;
// Clear any previous column/field info
$this->_fields = array();
$this->_fieldMeta = array();
$this->_primaryKey = NULL;
// Automatically retrieve column information if column info not specified
if(count($this->_fields) == 0 || count($this->_fieldMeta) == 0)
{
// Fetch all columns and store in $this->fields
$columns = $this->db->query("SHOW COLUMNS FROM " . $this->tableName, PDO::FETCH_ASSOC);
foreach($columns as $key => $col)
{
// Insert into fields array
$colname = $col['Field'];
$this->_fields[$colname] = $col;
if($col['Key'] == "PRI" && empty($this->_primaryKey)) {
$this->_primaryKey = $colname;
}
// Set field types
$colType = $this->parseColumnType($col['Type']);
$this->_fieldMeta[$colname] = $colType;
}
}
return true;//<<--- not returning an object/array!
}
Your getColumnMeta method returns a boolean, true. The string representation of this value is, of course, 1. If you want this method to return all of the meta-data, change the return statement to something like:
return array(
'fields' => $this->_fields,
'meta' => $this->_fieldMeta,
'primary' => $this->_primaryKey
);
There are some other issues with your code, too, but seeing as this is not codereview.stackexchange, I'm not going to go into too much details. I will say this, though: Please, try to follow the coding standards that most major players adhere to: these standards can be found here: PHP-FIG.
Oh, and if you want to show the meta-data, don't echo them, but rather var_dump or print_r them, seeing as you return an array or an object.
Or at least echo json_encode($instance->getColumnMeta($table)); to get a correct string representation of the returned value(s).

Categories