Filter Data Using Session Id - mysql

I want to filter data using session id. Have a table like below.
id | user_id | plan
1 | 1 |.sjhsjh.jpg
2 | 2 |bchdj.jpg
I want to filter that database value according to the login user.user id, which is the foreign key of user table. I have filter it before,but now its not working.
model
function get_plan(){
$this->db->select("floor_plan.id,floor_plan.image");
$this->db->where("user_id",$this->session->userdata['logged_in']['id']);
$this->db->from('floor_plan');
$query = $this->db->get();
return $query->result();
Session
<?php
if (isset($this->session->userdata['logged_in'])) {
$firstname = ($this->session->userdata['logged_in']['firstname']);
$email = ($this->session->userdata['logged_in']['email']);
$id = ($this->session->userdata['logged_in']['id']);
} else {
header("location: login");
}

change model as following.
function get_plan(){
$userdata=$this->session->userdata('logged_in');
$this->db->select("floor_plan.id,floor_plan.image");
$this->db->where("user_id",$userdata['id']);
$this->db->from('floor_plan');
$query = $this->db->get();
return $query->result();
}
session change as following.
<?php
if (isset($this->session->userdata('logged_in'))) {
$userdata=$this->session->userdata('logged_in');
$firstname = $userdata['firstname'];
$email = $userdata['email'];
$id = $userdata['id'];
} else {
redirect("login/index");
}

Related

PDO query returns multiple arrays. How to uniquely identify them?

This query returns 13 individual arrays:
$array = array($pgff_id, $pgfm_id, $pgmf_id, $pgmm_id, $mgff_id, $mgfm_id, $mgmf_id, $mgmm_id, $pgf_id, $pgm_id, $mgf_id, $mgm_id, $fid, $mid);
foreach($array as $id) {
$stmt = $db->prepare("SELECT birth_year, death_year FROM index WHERE id = ?");
$stmt->execute([$id]);
$data = $stmt->fetch(PDO::FETCH_ASSOC);
print_r shows that they look like this:
Array ([birth_year] => 1750 [death_year] => 1824)
Array ([birth_year] => 1770 [death_year] => 1836)
... etc
Is it possible to assign a number or name to these individual arrays? The results are not useful without a way to identify them.
I tried doing it like shown below. This way does number the arrays but orders the results as they are found in the table. I really need the results ordered as they are in $array (which the first method does manage).
$in = str_repeat('?,', count($array) - 1) . '?';
$sql = "SELECT birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$data = $stmt->fetchAll();
Taking your code and adding in id as an expression in the query would result in this:
$in = str_repeat('?,', count($array));
$sql = "SELECT id, birth_year, death_year FROM index WHERE id IN ($in)";
$stmt = $db->prepare($sql);
$stmt->execute($array);
$rows = $stmt->fetchAll();
foreach ($rows as $row) {
echo "here starts another row:<br>";
echo "id = ".$row["id"]."<br>";
echo "birth_year = ".$row["birth_year"]."<br>";
echo "death_year = ".$row["death_year"]."<br>";
}
So, that's how you can access it.
You can rearrange the data in the rows after you've received them from the database, again by using a foreach loop:
$birth = [];
$death = [];
foreach ($rows as $row) {
$id = $row["id"];
$birth[$id] = $row["birth_year"];
$death[$id] = $row["death_year"];
}
Now you can access both arrays to get the birth or death year based on the id like this:
echo $birth[4]. 'and '. $death[4];
where id is 4.

how to get the number of rows in mysql statements and return it?

I am currently having problem getting the number of rows in my code. here's my code:
$app->get('/banana/:state', function($state) use ($app){
$db = new DbOperation();
$today = date("j-M-Y");
if($state == "Indoor"){
$result = $db->getAllbananaindoor($today);
$response = array();
$response['messages'] = array();
$row = $result->fetch_assoc();
if($row > 3){
$temp = array();
$temp['text'] = 'Yes, you can plant banana seeds today indoors.';
array_push($response['messages'],$temp);
}
else {
$temp = array();
$temp['text'] = 'Nope. Today is not a good time to plant banana seeds indoors.';
array_push($response['messages'],$temp);
}
echoResponse(200,$response);
}
}
public function getAllbananaindoor($today){
$stmt = $this->con->prepare("SELECT * FROM garden WHERE humid >? AND time=? AND temp BETWEEN ? AND ?");
$hum = '50';
$one = '19';
$two = '24';
$stmt->bind_param("iiii",$hum, $today, $one, $two);
$stmt->execute();
$students = $stmt->get_result();
$stmt->close();
return $students;
}
In this I get the database data from a function getAllBananaindoor() which returns the result instead i want it return the number of rows and finally check whether $row is greater than 3 and then work on that. how can I do that? please help.
The MySQLi Result object has num_rows property defined.
$students = $stmt->get_result();
return $students->num_rows; // will return the number of rows

Implementing mysql intersection

I'm trying to do a filter search functionality in codeigniter. I have a table named products and my system has the functionality to filter these products by category and by date. I have a mysql code in mind which looks something like this:
SELECT * from products WHERE product_category='Cloth'
INTERSECT
SELECT * from products WHERE ('insert date logic here')
So it should return records (via id) from the same table named products. However, there's no INTERSECT in mysql so I don't know how to do this. Any help would be greatly appreciated!
This is my code just for the part of the product category
$this->db->limit($limit,$start);
$query = $this->db->query('SELECT * from product_advertised WHERE quantity > 0 AND prodcatid='.$prodcats[0].' LIMIT '.$start.','.$limit);
if(sizeof($prodcats > 1)) {
$query_str = "SELECT * FROM product_advertised WHERE quantity>0 AND ";
$str="";
for($i = 0;$i < sizeof($prodcats);$i++) {
if($i != sizeof($prodcats)-1) {
$str = $str. "prodcatid=".$prodcats[$i]." OR ";
}
else {
$str = $str. "prodcatid=".$prodcats[$i]." LIMIT ".$start.",".$limit;
}
}
$query_str .= $str;
$query = $this->db->query($query_str);
}
if($query->num_rows() > 0) {
foreach($query->result() as $row) {
$data[] = $row;
}
return $data;
}
return false;
Why wouldn't you just use and?
SELECT *
from products
WHERE product_category = 'Cloth' AND
('insert date logic here');

SQL update not committed

I am having a weird issue but I do not understand what is happening. I amcreated a function to update up to three columns (end_plan_date, balance and server) in a table (user) and 2 inserts in another table.
For some reason, my last update (column server of the user table) is not committed ($query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");) unless I give a value for at leat one of the two other values ($subamt or $subday).
Do you know why this query is not updating the user table with the server value I parsed?
function addBalance($subemail, $subamt,$subday,$userid,$serv) {
$q = "SELECT * FROM user WHERE email = '$subemail'";
$result = mysql_query($q, $this->connection);
$dbarray = mysql_fetch_array($result);
$endplan_date=$dbarray['end_plan_date'];
if($subday >0){
if($endplan_date=="0000-00-00" ){
$endplan_date = date('Y-m-d');
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}else{
$new_endplan_date = date('Y-m-d',strtotime($endplan_date . "+".$subday." days"));
}
$query = mysql_query("UPDATE user SET end_plan_date='$new_endplan_date' WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES ('$recdate','$userid','Plan Date','$subday')";
mysql_query($q, $this->connection);
}
if($subamt >0){
$query = mysql_query("UPDATE user SET balance=balance+".$subamt." WHERE email='$subemail'");
$recdate=gmdate('Y-m-d H:i:s');
$q = "INSERT INTO com_gest(recdate,userid,type,recvalue) VALUES '$recdate','$userid','Balance','$subamt')";
mysql_query($q, $this->connection);
}
$query = mysql_query("UPDATE user SET server='$serv' WHERE email='$subemail'");
return 0;
}
In your code u can't get directly this
$endplan_date=$dbarray['end_plan_date'];
for fetching this variable u have to use while loop like
while($dbarray = mysql_fetch_array($result);) {
$endplan_date=$dbarray['end_plan_date'];
}
There was an issue when calling this function.

How to get available values for SET field?

Is there any way to get available values for SET field in table?
Thank you.
You can retrieve the possible values for a SET field using DESCRIBE myTableName mySetColumn or SHOW COLUMNS FROM myTableName LIKE mySetColumn:
mysql> DESCRIBE myTableName mySetColumn;
+-------+-------------------------------------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+-------------------------------------------+------+-----+---------+-------+
| myset | set('Travel','Sports','Dancing','Dining') | YES | | NULL | |
+-------+-------------------------------------------+------+-----+---------+-------+
Informative article here, manual here.
SELECT `COLUMN_TYPE` FROM `information_schema`.`COLUMNS`
WHERE `TABLE_SCHEMA` = 'my_database_name'
AND `TABLE_NAME` = 'my_table_name'
AND `COLUMN_NAME` = 'my_set_column';
gives you only the type, e.g.
set('Travel','Sports','Dancing','Dining')
you'll still have to extract the set value on a textual base, but there's less clutter around it this way.
Full implementation from #Andy's link to the documentation:
/**
* #return array
* #param table DB table
* #param column Column name
* #desc Return an array of the possible values for a SET
*/
function get_set($table,$column)
{
$sql = "SHOW COLUMNS FROM $table LIKE '$column'";
if (!($ret = mysql_query($sql)))
die("Error: Could not show columns");
$line = mysql_fetch_assoc($ret);
$set = $line['Type'];
// Remove "set(" at start and ");" at end.
$set = substr($set,5,strlen($set)-7);
// Split into an array.
return preg_split("/','/",$set);
}
The above methods weren't exactly working for me, but I ended up with this and it works great. Posting in case this helps anyone else in the same situation. You'll just have to trim the string based on your results, as it will include your column name alongside the word 'set'.
<?php>
include ('database.php');
$query = "SHOW COLUMNS FROM Products LIKE 'Genre'";
$stmt = $con->prepare( $query );
$result = $stmt -> execute();
if ($result) {
$row = $stmt -> fetch(PDO::FETCH_ASSOC);
$genres = implode($row);
$genres = substr($genres,10,strlen($genres)-14);
//echo $genres;
$genres = preg_split("/','/",$genres);
//this is to populate my select box options with set values
echo "<select name = 'genre'>";
echo "<option>Select...</option>";
foreach ($genres as $key=>$value) {
echo "<option name = '$value' value = '$value'>$value</option>";
};
echo "</select>";
}
?>
Here is how to get the possible values of SET using PDO extension.
function get_set($table, $column)
{
global $db; //PDO DB Handler
$sql = "SHOW COLUMNS FROM $table LIKE :column";
$stmt = $db -> prepare($sql);
$stmt -> bindParam(":column", $column, PDO::PARAM_STR, 50);
try {
$result = $stmt -> execute();
$row = $stmt -> fetch(PDO::FETCH_ASSOC);
$set = $row['Type'];
$set = substr($set,5,strlen($set)-7);
// Split into an array.
return preg_split("/','/",$set);
} catch (PDOException $e) {
echo $e -> getMessage();
return false;
}
}
[Source]