My else statement is not getting executed when it should. There are no errors in the code. It simply has to do with the flow of my query and foreach statement but I cannot seem to figure this out. Any ideas?
$id = $this->input->post('id');
$session_id = $this->input->post('session_id');
$q1 = $this->db->query("SELECT *
FROM default_cart
WHERE cookie_id = '$session_id'
AND product_id = '$id' LIMIT 1");
foreach($q1->result() as $row) {
if($row->cookie_id != $session_id && $row->product_id != $id) {
echo json_encode(array('error_code' => 'e100'));
} else {
$data = array('product_id' => $id,
'active' => 'Yes',
'cookie_id' => $session_id
);
$this->db->insert('default_cart', $data);
echo json_encode(array('success' => true));
}
}
First, I would like to suggest that there is no sense of looping through the query when there is only one record LIMIT 1 and no sense of if check while you have already checked the all parameters in the query WHERE cookie_id = '$session_id' AND product_id = '$id' just fetch the row returned by the query and check for empty or not.
$id = $this->input->post('id');
$session_id = $this->input->post('session_id');
$q1 = $this->db->query("SELECT * FROM default_cart
WHERE cookie_id = '$session_id' AND product_id = '$id' LIMIT 1");
$row=$q1->row();
if(!empty($row)) {
$data = array('product_id' => $id,
'active' => 'Yes',
'cookie_id' => $session_id);
$this->db->insert('default_cart', $data);
echo json_encode(array('success' => true));
}else{
echo json_encode(array('error_code' => 'e100'));
}
Related
I am getting a PHP error undefined variable in my code. I am using PDO to json_encode the output. When I test my code I am getting that error. How can I fix and avoid this in the future? Is my code structure ok? or do I need to improve it in order to avoid this problem
Undefined variable: ar
$sql = $conn->prepare("SELECT UserID, UsrPassword, ContactID, UserTypeID, UserStatus, ClientUpdate, ServerUpdate, Deleted FROM tblUsers WHERE ContactID = :contactid AND ServerUpdate > :lastchecked AND Deleted != :deleted", $cursor);
$sql->bindValue(":contactid", $ContactID);
$sql->bindValue(":lastchecked", $LastChecked);
$sql->bindValue(":deleted", 1);
if($sql->execute()){
$count = $sql->rowCount();
if($count > 0){
while ($row = $sql->fetch()) {
$decr = CryptRC4(FromHexDump($row['UsrPassword']), $key);
if($row['ServerUpdate'] > $row['ClientUpdate']){
$lupdate = date("Y-m-d h:i:s", strtotime($row['ServerUpdate']));
}
else{
$lupdate = date("Y-m-d h:i:s", strtotime($row['ClientUpdate']));
}
$ar[] = array(
'UserID' => $row['UserID'],
'UsrPassword' => $decr,
'ContactID' => $row['ContactID'],
'UserTypeID' => $row['UserTypeID'],
'UserStatus' => $row['UserStatus'],
'Deleted' => $row['Deleted'],
'LastUpdated' => $lupdate
);
}
}
}
else{
$ar[] = array(
"Message" => $sql->errorInfo(),
"sql" => $sql
);
}
print json_encode($ar);
you need to declare $ar variable as a array before if statement so the scope of variable is not limited and you can access this outside If else.
$sql = $conn->prepare("SELECT UserID, UsrPassword, ContactID, UserTypeID, UserStatus, ClientUpdate, ServerUpdate, Deleted FROM tblUsers WHERE ContactID = :contactid AND ServerUpdate > :lastchecked AND Deleted != :deleted", $cursor);
$sql->bindValue(":contactid", $ContactID);
$sql->bindValue(":lastchecked", $LastChecked);
$sql->bindValue(":deleted", 1);
$ar = array();
if(){
// You code goes here
}
else{
// You code goes here
}
print_r($ar);
seems if($count > 0){ condition is not satisfied ,Declare ar before this,hope this helps
$sql = $conn->prepare("SELECT UserID, UsrPassword, ContactID, UserTypeID, UserStatus, ClientUpdate, ServerUpdate, Deleted FROM tblUsers WHERE ContactID = :contactid AND ServerUpdate > :lastchecked AND Deleted != :deleted", $cursor);
$sql->bindValue(":contactid", $ContactID);
$sql->bindValue(":lastchecked", $LastChecked);
$sql->bindValue(":deleted", 1);
$ar = array();
if($sql->execute()){
$count = $sql->rowCount();
if($count > 0){
while ($row = $sql->fetch()) {
$decr = CryptRC4(FromHexDump($row['UsrPassword']), $key);
if($row['ServerUpdate'] > $row['ClientUpdate']){
$lupdate = date("Y-m-d h:i:s", strtotime($row['ServerUpdate']));
}
else{
$lupdate = date("Y-m-d h:i:s", strtotime($row['ClientUpdate']));
}
$ar[] = array(
'UserID' => $row['UserID'],
'UsrPassword' => $decr,
'ContactID' => $row['ContactID'],
'UserTypeID' => $row['UserTypeID'],
'UserStatus' => $row['UserStatus'],
'Deleted' => $row['Deleted'],
'LastUpdated' => $lupdate
);
}
}
}
else{
$ar[] = array(
"Message" => $sql->errorInfo(),
"sql" => $sql
);
}
print_r(json_encode($ar));
I have this problem, I have to update a record of a table that has the values of a serialized column. the call to the function works and passes the data correctly. I can enter the record, but I can not update. This is my code:
public function update($user_id, $array_check)
{
$arrayB = array();
$array_check = unserialize($array_check);
foreach ($array_check $key => $value) {
if($value["id"] == $array_check){
$idRow = $value["id"];
if($value["value"] == "0"){
$valueRow = "1";
}else{
$valueRow = "0";
}
}else{
$idRow = $value["id"];
$valueRow = $value["value"];
}
$row = array("id" => $idRow, "value" => $valueRow);
$arrayB[] = $row;
}
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id');
$row = $stmt->execute(array(':user_id' => $user_id, ':docs_selected' => serialize($arrayB) ) );
return $arrayB;
}
edit.
Replace this:
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = :docs_selected WHERE user_id = :user_id);
with:
$deseralized = serialize($arrayB);
$stmt = $this->_db->prepare('UPDATE data_docs SET docs_selected = '$deseralized ' WHERE user_id = '$user_id');
I am trying to update data with Ajax and PHP. The following script updating data, But its taking too much time to run.
PHP
$groupId = $_POST['group_id'];
$Id_array = $_POST['Id'];
$result_array = $_POST['result'];
$data = array();
if(count($_POST['data']) > 0 && !empty ($_POST['data'])){
foreach($_POST['data'] as $key => $array){
$row = array();
$row['team_id'] = intval($array['team_id']);
$row['Note'] = strip_tags(trim(strval($array['Note'])));
$data[$key] = $row;
}
for ($i = 0; $i < count($Id_array); $i++) {
$Id = intval($Id_array[$i]);
$result = strip_tags(trim(strval($result_array[$i])));
$sql1 = $db->prepare("UPDATE teams SET result = :result WHERE id = :id ");
foreach($data as $key => $array){
$sql1 ->execute(array(':result' => $result, ':id' => $Id));
}
$sql2 = $db->prepare("UPDATE teams SET note = :note WHERE team_id = :teamid AND group_id = :group_id");
foreach($data as $key => $array){
$sql2->execute(array(':note' => $array['Note'], ':teamid' => $array['team_id'], ':group_id' => $groupId ));
}
Network Timing
You don't need this loop:
foreach($data as $key => $array){
$sql1 ->execute(array(':result' => $result, ':id' => $Id));
}
It's updating the same ID repeatedly, since $Id doesn't change in the loop. Just do:
$sql1->execute(array(':result' => $result, ':id' => $Id));
once.
You can also get some small improvements by doing:
$sql1 = $db->prepare("UPDATE teams SET result = :result WHERE id = :id ");
$sql2 = $db->prepare("UPDATE teams SET note = :note WHERE team_id = :teamid AND group_id = :group_id");
just once, before any of the loops.
Another problem is that you have this loop:
foreach($data as $key => $array){
$sql2->execute(array(':note' => $array['Note'], ':teamid' => $array['team_id'], ':group_id' => $groupId ));
}
inside the for() loop, but it doesn't use any of the variables that change each time through the loop. So it's re-executing all the same queries for each ID in $Id_array.
Take it out of the loop.
With all these changes, the code now looks like:
$groupId = $_POST['group_id'];
$Id_array = $_POST['Id'];
$result_array = $_POST['result'];
$sql1 = $db->prepare("UPDATE teams SET result = :result WHERE id = :id ");
$sql2 = $db->prepare("UPDATE teams SET note = :note WHERE team_id = :teamid AND group_id = :group_id");
$data = array();
if(count($_POST['data']) > 0 && !empty ($_POST['data'])){
foreach($_POST['data'] as $key => $array){
$row = array();
$row['team_id'] = intval($array['team_id']);
$row['Note'] = strip_tags(trim(strval($array['Note'])));
$data[$key] = $row;
}
foreach ($Id_array as $i => $Id) {
$Id = intval($Id);
$result = strip_tags(trim(strval($result_array[$i])));
$sql1 ->execute(array(':result' => $result, ':id' => $Id));
}
foreach($data as $key => $array){
$sql2->execute(array(':note' => $array['Note'], ':teamid' => $array['team_id'], ':group_id' => $groupId ));
}
}
I would use a transaction instead of auto committing in a loop.
So,
//PDO::beginTransaction ( void )
$dbh->beginTransaction();
foreach () {
$smt->exec();
}
//PDO::commit ( void )
$dbh->commit();
Also, you only need to prepare a statement one time since you're binding your variables in the execute function, so try keeping any prepare statements out of a loop.
This should help with some of the overhead of the query in the loop.
I am trying to set the company name in a session and retrieve the same to connect to a different database, i am setting the session using $this->session->set_userdata($newdata); and retrieving the session using $companyName = $this->session->userdata['newdata']['company']; but somehow retrieval is not happening and i am unable to load the correct db for updating logout information i.e it simply does not update the pr_system_attendance table by connecting to a different db. I am getting the correct value if i echo $company; after $company = $row1->company; this is FYI
My model code is as follows:
function check_admin_login(){
$this->db->where('username', trim($this->input->post('username')));
$this->db->where('userpass ', sha1(trim($this->input->post('userpass'))));
$this->db->where('status', '1');
$this->db->where('deleted', '0');
$this->db->select('*');
$query = $this->db->get($this->myTables['users']);
if($query->num_rows() > 0){
$row = $query->row();
$this->db->where('userid', $row->id);
$this->db->select('firstname,lastname,profileimage,company');
$query1 = $this->db->get($this->myTables['users_details']);
$row1 = $query1->row();
$newdata = array(
'is_admin_logged_in' => true,
'admin_user_name' => $row->username,
'admin_userpass' => $row->userpass,
'admin_id'=>$row->id,
'admin_lastlogin'=>date("d-m-Y H:i:s",$row->lastlogin),
'admin_lastloginip'=>$row->lastloginip,
'lastrefresh'=>time(),
'company'=>$row1->company
);
$company = $row1->company;
$this->session->set_userdata($newdata);
$companyName = $this->session->userdata['newdata']['company'];
$this->update_admin_login_time($this->session->userdata('admin_id'));
$this->admin_init_elements->set_global_user($row->username,$row->userpass);
if($this->input->post('remember'))
{
$cookie = array('name' => 'username','value' => $row->username,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie);
}
$name = $row1->firstname.' '.$row1->lastname;
$cookie1 = array('name' => 'name','value' => $name,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie1);
$cookie2 = array('name' => 'image','value' => $row1->profileimage,'expire' => time()+7600,'secure' => false);
$this->input->set_cookie($cookie2);
return 'Login Successful';
}else{
return 'Incorrect Username or Password.';
}
}
function logout()
{
global $USER;
$companyName = $this->session->userdata['newdata']['company'];
$otherdb = $this->load->database("$companyName", TRUE);
$this->db->from("$companyName"."pr_users");
$query1 = $this->db->query("Select * from pr_system_attendance where userid = '".$USER->id."' and DATE(`login_time`) = CURDATE()");
date_default_timezone_set('Asia/Calcutta');
if($query1->num_rows() > 0)
{
$row = $query1->row();
$sql1 = "UPDATE pr_system_attendance set logout_time = '".date('Y-m-d H:i:s')."' where userid = '".$USER->id."' and DATE(`login_time`) = CURDATE()";
$query2 = $this->db->query($sql1);
}
$sql="UPDATE `".$this->myTables['users']."` SET
`if_online` = '0'
WHERE `id` = '".$USER->id."'" ;
$query=$this->db->query($sql);
}
Get session data with below line of code
//$companyName = $this->session->userdata['newdata']['company'];
$companyName = $this->session->userdata('company');
I have two different databases with table Phpfox_user , manual_userid and mobile table in them.There can be 3 users with same user_id but different mobile numbers stored in phpfox_user table and manual_userid and there GCM id in table mobile.(with mobile no column as well). Now i want to send notification to all mobile numbers with same user id .
Currently notification is only sent to a single manager only
function request_block($data){
//print_r($data);
$tower=new Tower;
$project=new Project;
$note=new Notification;
$fields=array('user_id', 'pay_opt', 'sale_type', 'hold_status', 'cost', 'is_manager_blocked', 'is_action_taken');
$params=array(
':user_id' => $data['user_id'],
':pay_opt' => $data['buy_opt'],
':sale_type' => $data['sale_type'],
':hold_status' => '1',
':cost' => $data['cost'],
':is_manager_blocked' => '0',
':is_action_taken' => '0',
':id' => $data['flat_id']
);
$where = 'where id= :id';
$tower->block_flat($fields, $params, $where);
$user_details=$tower->get_user_details($data['user_id']);
$flat_details=$tower->get_flat_details_cost($data['flat_id']);
$tower_main=$tower->get_tower_main_details($flat_details['tower_id']);
$project_details=$project->get_project_details($tower_main['project_id']);
$manager_details=$tower->get_user_details($project_details['manager_id']);
$manager_details=$tower->get_manualuser_details($project_details['manager_id']) ;
$mob_details=$tower->get_gcmid($manager_details['cf_mobile']);
$par['mobile']=$manager_details['cf_mobile'] ;
//print_r($flat_details); print_r($tower_main); print_r($project_details);
//$manager_details=$tower->get_user_details($project_details['manager_']);
$data['send_by']='user';
$data['user_id']=$data['user_id'];
$data['manager_id']=$project_details['manager_id'];
$data['message']='You have received a Booking request - by '.$user_details['full_name'].' '.$user_details['cf_mobile'].' for Flat no. '.$flat_details['flat_no'].' in '.$tower_main['tower_name'].' tower of '.$project_details['project_name'].' Project';
$data['msg_details']=$data['message'];
$data['notification_type']='user-to-manager';
$note->insert_notification($data);
$par['msg']=$data['message'];
if(count($mob_details)>=1 && $mob_details['gcmid']!='')
{
$fuck['notification_type']='user-to-manager';
$fuck['notification_text']=$par['msg'];
$fuck['user_id']=$data['user_id'];
$tt['message']=$fuck;
$tt['gcmid']=$mob_details['gcmid'];
send_notification($tt);
}
if(count($tower_images)>=1)
{
$result['data']=$tower_images;
} else {
$result['message']='No result found';
}
$result['message']='Flat block requested';
//print_array($par);
$result['status']='success';
send_sms($par);
$res=json_encode(array($result));
echo $res;}
These are the two functions that gets the user mobile numbers
public function get_user_details($user_id)
{
$params = array( ':user_id' => $user_id);
$sql = "SELECT * FROM phpfox_user, phpfox_user_custom where phpfox_user.user_id=phpfox_user_custom.user_id AND phpfox_user.user_id=:user_id";
$stmt = parent::query($sql, $params, '', 'main');
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
return $result[]=$row;
endwhile;
return $result;
}
public function get_manualuser_details($user_id)
{
$params = array( ':user_id' => $user_id);
$sql = "SELECT * FROM manual_userid where user_id=:user_id";
$stmt = parent::query($sql, $params);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
return $res=$row;
endwhile;
return $result;}
public function get_gcmid($data)
{
$mobile=str_replace('+','0',$data);
$params = array( ':mobile' => $mobile);
$sql = "SELECT * FROM mobile where mobile=:mobile";
$stmt = parent::query($sql, $params);
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) :
return $res=$row;
endwhile;
}