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));
Related
in my current project I have to create a JSON array, in which for each day a status with a colour is displayed in a calendar (FullCalendar) and additionally a button with a link is to be displayed for all days where an event is planned.
For this I have two SELECT's which both work on their own. I have already tried some things how to put the results of both SELECT's into one JSON array, but I keep getting the error 'Undefinded Variable'.
How do I have to pack the results of the two SELEC T's put together that all results are displayed correctly?
header('Content-Type: application/json');
include "../../../includes/db.php";
if(isset($_GET['team_id'])) {
$team_id = $_GET['team_id'];
}
$stmt = $connection->prepare("SELECT date FROM date");
$stmt->execute();
$result = $stmt->get_result();
while($row = $result->fetch_assoc()) {
$date = $row['date'];
$team_planner_user_status_present = 1;
$team_planner_user_status_absent = 2;
$team_planner_user_status_reservation = 3;
$stmt1 = $connection->prepare("SELECT
(
SELECT COUNT(*)
FROM team_planner_user
INNER JOIN user ON team_planner_user.user_id = user.user_id
WHERE user.team_id = ?
AND team_planner_user.date = ?
AND team_planner_user.team_planner_user_status = ?
) AS present,
(
SELECT COUNT(*)
FROM team_planner_user
INNER JOIN user ON team_planner_user.user_id = user.user_id
WHERE user.team_id = ?
AND team_planner_user.date = ?
AND team_planner_user.team_planner_user_status = ?
) AS absent,
(
SELECT COUNT(*)
FROM team_planner_user
INNER JOIN user ON team_planner_user.user_id = user.user_id
WHERE user.team_id = ?
AND team_planner_user.date = ?
AND team_planner_user.team_planner_user_status = ?
) AS reservation
");
$stmt1->bind_param("sssssssss", $team_id, $date, $team_planner_user_status_present,
$team_id, $date, $team_planner_user_status_absent,
$team_id, $date, $team_planner_user_status_reservation);
$stmt1->execute();
$result1 = $stmt1->get_result();
while($row1 = $result1->fetch_array()) {
$present = $row1['present'];
$absent = $row1['absent'];
$reservation = $row1['reservation'];
if($present >= 5) {
$color = '#a1ff9e';
} else if($present + $reservation >= 5) {
$color = '#fcff9e';
} else {
$color = '#ff9e9e';
}
}
$stmt1->close();
$stmt2 =$connection->prepare("SELECT * FROM game_planned INNER JOIN game_role ON game_planned.match_role_id = game_role.match_role_id WHERE team_id = ? AND game_planned_date = ?");
$stmt2->bind_param("ss", $team_id, $date);
$stmt2->execute();
$result2 = $stmt2->get_result();
while($row2 = $result2->fetch_array()) {
$match_role_name = $row2['match_role_name'];
$game_planned_id = $row2['game_planned_id'];
}
$data[] = array(
'start' => $date,
'display' => 'background',
'color' => $color,
);
if($result->num_rows === 0) {
echo "";
} else {
$data[] = array(
'title' => $match_role_name,
'url' => 'http://localhost/r6team-redesign/team/team.php?team=details-match-plan&match_planned_id='.$game_planned_id,
'start' => $date,
);
}
}
$stmt->close();
echo json_encode($data);
I am using this program here GameQ v3 and I have a database table called servers. the fields are id, game, ip, port and query_port. what I am trying to do is echo all servers and info in a table like a list I have managed to get the information from the database to the code below. every thing works fine until I add a 2 server to the list then it gives me an error
Uncaught GameQ\Exception\Server: Missing server info key 'type'!
GameQ\Server->__construct(Array) #1 GameQ\GameQ->addServer(Array) #2 {main} thrown
I'm not sure what I am doing incorrectly. but it works if I only have 1 server in the database.
$db = dbconnect();
$stmt = $db->prepare("SELECT * FROM servers");
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
if ($result->num_rows == 1) {
$row = $result->fetch_array();
$ID = $row['id'];
$GAME = $row['game'];
$IP = $row['ip'];
$PORT = $row['port'];
$QUERYPORT = $row['query_port'];
}
$GameQ = new \GameQ\GameQ();
$GameQ->setOption('timeout', 5); // seconds
$GameQ->addFilter ( 'normalize' );
$GameQ->addServer([
'id' => $ID,
'type' => $GAME,
'host' => $IP.':'.$PORT,
'options' => [
'query_port' => $QUERYPORT,
],
]);
$results = $GameQ->process();
print_r($results);
echo "<pre>";
print_r ( $results );
echo "</pre>";
1.Code after if block need to be inside if (to resolve variable-scope problem)
2.A while loop needed too for returning all records.
$db = dbconnect();
$stmt = $db->prepare("SELECT * FROM servers");
$stmt->execute();
$result = $stmt->get_result();
$stmt->close();
if ($result->num_rows > 0) {
while($row = $result->fetch_array()){
$ID = $row['id'];
$GAME = $row['game'];
$IP = $row['ip'];
$PORT = $row['port'];
$QUERYPORT = $row['query_port'];
$GameQ = new \GameQ\GameQ();
$GameQ->setOption('timeout', 5); // seconds
$GameQ->addFilter ( 'normalize' );
$GameQ->addServer([
'id' => $ID,
'type' => $GAME,
'host' => $IP.':'.$PORT,
'options' => [
'query_port' => $QUERYPORT,
],
]);
$results = $GameQ->process();
echo "<pre/>";print_r($results);
}
}
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');
Here is a script that upgrades joomfish (joomla translation component) from joomla 1.5 to 2.5:
$db = new PDO("mysql:host=localhost;dbname=db;charset=UTF8", "root", "pass");
$stmt = $db->prepare("select distinct(jfc.reference_id),c.catid,jfc.language_id,c.modified,c.modified_by,c.version,c.modified_by ,c.ordering,c.created_by,c.metadesc ,c.created_by_alias from jos_jf_content jfc ,jos_content c where jfc.reference_id = c.id and jfc.reference_table = 'content' ");
$stmt->execute();
$results = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach($results as $row) {
$count_row = $db->prepare("select * from jos_jf_content where reference_id = ? and language_id = ?");
$count_row->bindValue(1, $row['reference_id']);
$count_row->bindValue(2, $row['language_id']);
$lang_code = $db->prepare("select lang_code from j25_languages where lang_id = ?");
$lang_code->bindValue(1, $row['language_id']);
$lang_code->execute();
$l_code = $lang_code->fetch(PDO::FETCH_OBJ);
$language_code = $l_code->lang_code;
$count_row->execute();
$title ="";
$fulltext ="";
$introtext ="";
$alias ="";
$published ="";
while($col = $count_row->fetch(PDO :: FETCH_ASSOC))
{
if($col['reference_field'] == "title")
{
$title = $col['value'];
}
if($col['reference_field'] == "fulltext")
{
$fulltext = $col['value'];
}
if($col['reference_field'] == "introtext")
{
$introtext = $col['value'];
}
if($col['reference_field'] == "alias")
{
$alias = $col['value'];
}
$published = $col['published'];
}
$exe = $db->prepare("insert into j25_content (`title`,`alias`,`introtext`,`fulltext`,`published`,`catid`,`created`,`created_by`,`created_by_alias`,`modified`,`modified_by`,`version`,`ordering`,`metadesc`,`language`) values(:title,:alias,:introtext,:fulltext,:published,:categoryid,:created,:created_by,:created_by_alias,:modified,:modified_by,:version,:ordering,:metadesc,:language_code)");
$exe->execute(array(':title' => $title,':alias' => $alias,':introtext' => addslashes($introtext),':fulltext' => addslashes($fulltext),':published' => ".$published.",':categoryid' => $row['catid'],':created' => date("Y-m-d H:i:s"),':created_by' => $row['created_by'],':created_by_alias' => "".$row['created_by_alias']."",':modified' => date("Y-m-d H:i:s"),':modified_by' =>$row['modified_by'],':version' => $row['version'],':ordering' => $row['ordering'],':metadesc' => $row['metadesc'],':language_code' => $language_code));
$i = $db->lastInsertId('id');
$asst = $db->prepare("select asset_id from j25_categories where id = ? ");
$asst->bindValue(1, $row['catid']);
$asst->execute();
$asst_id = $asst->fetch(PDO::FETCH_OBJ);
$cassetid = $asst_id->asset_id;
$sel = $db->prepare("select lft,rgt FROM `j25_assets` where id = (SELECT max(id) FROM `j25_assets`)");
$sel->execute();
$select = $sel->fetch(PDO::FETCH_OBJ);
$left = $select->lft;
$right = $select->rgt;
$left=$left+1;
$right = $right+1;
$stmt = $db->prepare("insert into j25_assets (`parent_id`,`lft`,`rgt`,`level`,`name`,`title`) values(:cassetid,:left,:right,:level,:name,:title)");
$stmt->execute(array(':cassetid' => $cassetid,':left' => $left,':right' => $right,':level' => 4,':name' => "com_content.article.".$i,':title' => $title));
$insertedId = $db->lastInsertId('id');
$update = $db->prepare("update j25_content set asset_id = ? where id = ?");
$update->bindValue(1, $insertedId);
$update->bindValue(2, $i);
$update->execute();
$stmt = $db->prepare("insert into j25_jf_translationmap (language,reference_id,translation_id,reference_table) values (:language_code,:reference_id,:translation_id,:content)");
$stmt->execute(array(':language_code' => $language_code,':reference_id' => $row['reference_id'],':translation_id' => $i,':content' => 'content'));
}
Line of code:
$language_code = $l_code->lang_code;
Returns:
Trying to get property of non-object
I'm not an author of the script and not good in PHP, but I've tried to print_r($l_code->lang_code); and I got expected result en-GB from [lang_code] => en-GB. What I need to change in this code? Thanks.
The line $language_code = $l_code->lang_code > 0; sets $language_code to boolean value. Try var_dump($l_code); and var_dump($language_code); to debug your results. You should also check if $l_code actually is an object, or perhaps null was returned. Hope that helps.
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'));
}