Check or Add to DB quickly - php

I'm using apache, php, mysql and code igniter and I have a database set up. In the database I have two columns that both need to be unique in combo: latitude and longitude.
So I set up the database using this call:
alter table pano_raw add unique index(lat, lng)
Now when I insert values into the two columns (lat and lng) if the value is the same, the database should reject the write correct?
function addNewSet($data)
{
$this->db->insert('sets', $data);
}
This function should return a true or false, depending on the success of the read or write correct?
So now how so I alter it so that when it will return the row_id of the inserted record or return FALSE? If the write worked, I need the row_id, if it didn't I need FALSE so I can alter the code that called this function.
Would this work? I don't think so. Ideas?
function addNewSet($data)
{
$this->db->insert('sets', $data);
return $this->db->insert_id();
}

By default it wont return false, it will have a database error before returning false.
If you really want this, you need to go to application/config/database.php and change set this to false $db['default']['db_debug'] = FALSE;
Then you should be able to do this (assuming your table has an id field set to auto increment)
function addNewSet($data) {
if ($this->db->insert('sets', $data)) {
return $this->db->insert_id();
} else {
return FALSE;
}
}

Try this:
function addNewSet($data)
{
$result = $this->db->insert('sets', $data);
if ( $result )
return $this->db->insert_id();
return false;
}

You can use $this->db->affected_rows(); after inserting the data to check if any record was added (or affected).
So
function addNewSet($data)
{
$this->db->insert('sets', $data);
if($this->db->affected_rows()==1)
{
return $this->db->insert_id();
}
else
{
return false; // nothing was added!
}
}
Should do it (untested).

Related

At the time of update my where condition is not working

In my first table(ts_users) update opening user_opening_balance at the same time, I want to update that user_opening_balance in my second table(ts_voucher) column is voucher_amount. But in my second table table(ts_voucher) voucher_amount updates all columns amount.
My code:
public function updateConsignor($myData){
extract($myData);
$this->db->set('user_full_name' , $user_full_name);
$this->db->set('user_opening_balance' , $user_opening_balance);
$this->db->where('user_id', $user_id);
if($this->db->update('ts_users')){
$userId = $myData['user_id'];
$this->db->trans_begin();
$openingBalTrxn = array(
'voucher_amount' => $myData['user_opening_balance'],
);
$this->db->update('ts_voucher', $openingBalTrxn);
$this->db->where('voucher_person_account_id',$userId);
if ($this->db->trans_status() === false){
$this->db->trans_rollback();
return false;
}else{
$this->db->trans_commit();
return true;
}
return $query_result;
return true;
}else{
return false;
}
}
I am giving where condition
$this->db->update('ts_voucher', $openingBalTrxn);
$this->db->where('voucher_person_account_id',$userId);
for update one record it updates all voucher_amount column record
you need to run first your .where before your .update. See documentation here
$this->db->where('voucher_person_account_id',$userId);
$this->db->update('ts_voucher', $openingBalTrxn);
Your update query false. where clause first and other condition where first than update function call just copy this function and fix your problem.
public function updateConsignor($myData){
extract($myData);
$this->db->set('user_full_name' , $user_full_name);
$this->db->set('user_opening_balance' , $user_opening_balance);
$this->db->where('user_id', $user_id);
if($this->db->update('ts_users')){
$userId = $myData['user_id'];
$this->db->trans_begin();
$openingBalTrxn = array(
'voucher_amount' => $myData['user_opening_balance'],
);
$this->db->where('voucher_person_account_id',$userId);
$this->db->update('ts_voucher', $openingBalTrxn);
if ($this->db->trans_status() === false){
$this->db->trans_rollback();
return false;
}else{
$this->db->trans_commit();
return true;
}
return $query_result;
return true;
}else{
return false;
}
Your update operation is working before the 'where' condition has a chance to work. That's why it's updating all records. Simply put the where condition first, then update.

codeigniter query builder will update db with just about anything

I'm new to codeigniter and trying to get my mind around the query builder functionality. I currently have an update method where I pass user entered data to update a record in the db. I've noticed it seems to be successful no matter what kind of junk data I throw at it, and I'm wondering if there's a setting or something I need to change, or what.
As you can see below, in my model I'm bypassing the user entered value and putting in junk data and it is still successful. It just inserts 0000-00-00. DOB in the DB is a date datatype.
I always get a success result from this, and it updates the DB, so techically it was successful. I have controls in place to prevent junk data from ever being sent to the model, but it doesn't give me warm fuzzies knowing that it is behaving this way.
Controller:
$updateResult = $this->Patients_model->update_patient_profile($this->data['post_data']);
if($updateResult === true)
{
$this->data['patient_profile'] = $this->Patients_model->get_patient_profile($patientId);
$this->data['update_result'] = true;
$this->load->view('index', $this->data);
}
else
{
$this->data['update_result'] = false;
print_r($updateResult);
}
Model:
function update_patient_profile($data)
{
$patient_id = $data['patient_id'];
unset($data['patient_id']);
$data['dob'] = 'this is not even a date'; //will store 0000-00-00 in DB.
$this->db->where('patient_id', $patient_id);
$this->db->update($this->patientsTable, $data);
if($this->db->affected_rows()) {
return true;
}
else
{
return $this->db->error();
}
}
You can check with PHP and thorw an error for invalid date. try this:
function update_patient_profile($data)
{
$patient_id = $data['patient_id'];
unset($data['patient_id']);
$check_date = $data['dob'];
if(strtotime($check_date))
{
$data['dob'] = date("Y-m-d",strtotime($check_date)); // to confirm date is valid and equivalant to database format
}
else
{
throw new Exception("Invalid date", 1);
}
$data['dob'] = 'this is not even a date'; //will store 0000-00-00 in DB.
$this->db->where('patient_id', $patient_id);
$this->db->update($this->patientsTable, $data);
if($this->db->affected_rows()) {
return true;
}
else
{
return $this->db->error();
}
}

Last Insert ID on codeigniter with SQL Server returns false

Good Evening,
I got a problem with the last insert id function with active record codeigniter, it works fine in mysql. But when i try it on SQL Server, the result always return false. Please kindly take a look on my code:
function transactions_start($data) {
$this->db->insert($this->table, $data);
$id = $this->db->insert_id();
$q = $this->db->affected_rows();
if ($q > 0) {
return $id;
} else {
return FALSE;
}
}
this is the result of $this->db->last_query()
select ##IDENTITY as id
the var_dump() result always returning bool(false).
I'm developing this apps using MySQL and SQL Server, so i need to keep using the active record from codeigniter.
Any help would be great, thanks in advance!
The insert_id() function returns the id of last inserted row so you just check whether it is greater than 0 or not. Use it like
function transactions_start($data) {
$this->db->insert($this->table, $data);
$id = $this->db->insert_id();
if ($id > 0) {
return $id;
} else {
return FALSE;
}
}
Reference : https://ellislab.com/codeigniter/user-guide/database/helpers.html

How to implement database trigger in codeigniter?

I trying to implement database trigger in codeigniter, I want to update one specific table after the insert operation on other specific table. I am trying the following code but it not work for me.
this is function I written in my model:
<?php
public function enter_follower($follower_id, $following_id) {
$data = array('follower_user' => $follower_id,
'following_user' => $following_id
);
$this->db->insert('followers', $data);
//return $this->db->insert_id();
$this->db->query("
CREATE TRIGGER `UpdateFollower` AFTER INSERT ON followers
FOR EACH ROW
UPDATE business_users SET followerCount = followerCount + 1 WHERE user_id = $following_id
END");
if ($this->affected_rows() > 0) {
return true
} else {
return false
}
} ?>

Form Validation w/ sql + codeigniter

I'm working on creating a callback function in codeigniter to see if a certain record exists in the database, and if it does it'd like it to return a failure.
In the controller the relevent code is:
function firstname_check($str)
{
if($this->home_model->find_username($str)) return false;
true;
}
Then in the model I check the database using the find_username() function.
function find_username($str)
{
if($this->db->get_where('MasterDB', array('firstname' => $str)))
{
return TRUE;
}
return FALSE;
}
I've used the firstname_check function in testing and it works. I did something like
function firstname_check($str)
{
if($str == 'test') return false;
true;
}
And in that case it worked. Not really sure why my model function isn't doing what it should. And guidance would be appreciated.
if($this->home_model->find_username($str)) return false;
true;
Given that code snippet above, you are not returning it true. If that is your code and not a typo it should be:
if($this->home_model->find_username($str)) return false;
return true;
That should fix it, giving that you did not have a typo.
EDIT:
You could also just do this since the function returns true/false there is no need for the if statement:
function firstname_check($str)
{
return $this->home_model->find_username($str);
}
So the solution involved taking the query statement out of if statement, placing it into a var then counting the rows and if the rows was > 0, invalidate.
Although this is a more convoluted than I'd like.
I find your naming kind of confusing. Your model function is called 'find_username' but it searches for a first name. Your table name is called 'MasterDB'. This sounds more like a database name. Shouldn't it be called 'users' or something similar? I'd write it like this :
Model function :
function user_exists_with_firstname($firstname)
{
$sql = 'select count(*) as user_count
from users
where firstname=?';
$result = $this->db->query($sql, array($firstname))->result();
return ((int) $result->user_count) > 0;
}
Validation callback function :
function firstname_check($firstname)
{
return !$this->user_model->user_exists_with_firstname($firstname);
}

Categories