Hey guys im quite new into programming and i would like some assistance...I store my sessions into a database table and each session row has a user_data array which contains the values email and logged_in.
I want to search that table for every session entry and print only the email from the user_data array (to server as a "who's online") but i get very confused with the multiple arrays.
$email = $this->session->userdata('email'); //That's how i read the single session now
I hope that this could will be useful for you.
i get the data from ci_session table and after that i ge the last activity you can get your
email the same way.
my model function where i get data from ci_session table
function get_alls()
{
$this->db->select('t1.*');
$this->db->from('ci_session AS t1');
$query = $this->db->get();
return $query;
}
inside my controller i called it.
$recs = $this->main_model->get_alls();
//echo unserialize($recs->row()->user_data); exit;
foreach($recs->result() AS $item)
{
if($item->last_activity+300<strtotime("now"))
{
$mhd = unserialize($item->user_data);
$this->ci_forms = array('loged'=> '0');
$this->crud_model->UpdateUid('users',$this->ci_forms,$mhd['userid']);
}
}
Related
I have a php class
<?php
class Students
{
public $sesscode;
public $db_data;
function __construct($sesscode)
{
$this->sesscode = $sesscode;
$this->db_data = dbfetch(null, "SELECT * FROM students WHERE code = ?", [$this->sesscode]); //this simply returns data from db
$this->db_data = (empty($this->db_data)) ? $this->createProfile() : $this->db_data[0];
}
public function createProfile()
{
dbquery(null, "INSERT INTO students (code) VALUES (?)", [$this->sesscode]);
return dbfetch(null, "SELECT * FROM students WHERE code = ?", [$this->sesscode])[0];
}
public function updateAccount($row, $key, $val)
{
$data = json_decode($this->db_data[$row], true);
if (!$data) {
$data = [
$key => $val,
];
} else {
$data[$key] = trim($val);
}
dbquery(null, "UPDATE students SET account = ? WHERE code = ?", [json_encode($data), $this->sesscode]);
}
public function getData($row)
{
return json_decode($this->db_data[$row], true);
}
}
?>
Usage:
$student = new Student($sesscode); //sesscode is just some string
if (!empty($_POST)){
$student->updateAccount("account", "course", $_POST['course']);
//see class code/updateAccount method above for parameters. This means update dB table row "account", decode json and set course to post value of course
$student->updateAccount("account", "email", $_POST['email']);
$student->updateAccount("account", "phone", $_POST['phone']);
$student->updateAccount("account", "institution", $_POST['institution']);
}
My problem is, only the last line executes (and no, it isn't overwriting the data)
Moving the line that sets phone to take the place of institution will set phone and ignore those above it.
The line
$data = json_decode($this->db_data[$row], true);
resets the value of $data every time your updateAccount account function runs. It resets it to the value you fetched from the database when you created the object. Therefore this doesn't take account of any changes you've made in previous calls to updateAccount. So in fact it does overwrite your data, but probably just quite not in the way you imagined.
You need to either:
a) keep $data in-memory as a (private) property of the class rather than resetting it each time updateAccount runs,
or
b) re-fetch the existing data from the database each time updateAccount runs,
or
c) Store your data in relational format (with fields in separate columns) instead of as JSON within a single column - meaning you could update individual fields without interfering with the others,
and/or
d) provide a version of updateAccount where multiple values can be updated simultaneously - running separate UPDATE queries for each field is very inefficient.
I'm have a live website that uses PHP and a mySQL database. I'm looking to use d3 to create a few visualizations. But I don't know how to alter the data as it is stored in the SQL database before directly encoding it in a JSON for d3. My PHP:
$activity_array = $array;
while ($activity = mysqli_fetch_assoc($get_all_activities)) {
// $user_name = find_user_by_id($activity['user_id']);
// echo $user_name['last_name'];
$activity_array[] = $activity;
}
echo json_encode($activity_array);
However, due to how my mysql database is set up, users are set up as numbers, so that what I get back in the JSON looks like:
[{"id":"93","date":"2020-05-01","user_id":"37","user_notes":"This user has blah blah."},...]
When I use this JSON to generate a graph in d3, I want it to show the actual user's name, not "37". In the PHP code above I commented out the query I have to get the user's name from their user_id, but then I have no idea how to get that into my JSON.
Thanks for the help!
You just need to modify the appropriate entry in the $activity array with the username retrieved by the second query:
$activity_array = $array;
while ($activity = mysqli_fetch_assoc($get_all_activities)) {
$user_name = find_user_by_id($activity['user_id']);
$activity['user_id'] = $user_name['last_name'];
$activity_array[] = $activity;
}
echo json_encode($activity_array);
It would however probably be easier to modify the $get_all_activities query to JOIN to the users table and fetch the username in that query directly.
I am working on an android app which uses APIs made with php. Here, i am dynamically creating columns and their values.
I am verifying the API via postman and a strange thing happens every time, While looping through the Json Object what i am doing is first creating column and then inserting its values.
The problem is only the 1st iteration saves the element and rest of them only creates the column but does not insert the values. I don't know if i am doing anything wrong, below is my php code.
<?php
include("connection.php");
$data = file_get_contents('php://input');
$json_data = json_decode($data);
foreach($json_data as $key => $val) {
$column_name = $key ;
$c_column_name = preg_replace('/[^a-zA-Z]+/', '', $column_name);
$column_value = $val ;
$table_name = "test2";
$email = "ht#t.com";
$result = mysqli_query($conn,"SHOW COLUMNS FROM $table_name LIKE '$c_column_name'");
$exists = (mysqli_num_rows($result))?TRUE:FALSE;
if($exists) {
$query1 = "INSERT INTO $table_name($c_column_name)VALUES('$column_value') ";
$data0=mysqli_query($conn,$query);
if($data0)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Column existed, Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column existed, data not inserted."));
}
}
else{
$query2="ALTER TABLE $table_name ADD COLUMN `$c_column_name` varchar(50) NOT NULL";
$data1=mysqli_query($conn,$query2);
if($data1){
$query3="INSERT INTO $table_name($c_column_name)VALUES('$column_value')";
$data2=mysqli_query($conn,$query3);
if($data2)
{
echo json_encode(array("success"=>"true - insertion","message"=>"Successfully data sent."));
}
else{
echo json_encode(array("success"=>"false - insertion","message"=>"Column created but data not inserted."));
}
}
else
{
echo json_encode(array("success"=>"false - column creation","message"=>"Failed to create column.'$column_name', '$table_name', '$conn'"));
}
}
}
?>
Here is the Json Object through postman.
{"Shape":"rewq","Trans.No.":"yuuiop","Color":"qwert"}
Please help me with this, any help or suggestions are highly appreciated.
The second column name is Trans.No. which contains a dot, this is why it fails, probably you have an error as a result which prevents further columns from being created.
I think it would be much better to have a table with this structure:
attributes(id, key, value)
and whenever a key-value pair is received, you just insert/update it, depending on the logic you need to be executed. Your current model will create a separate row for each attribute, which is probably not what you want to achieve.
EDIT
Based on the information received in the comment section I reached the following conclusion:
You could create the missing columns first and then generate the insert statement with all the columns, having a single insert.
But it would be better to not create a separate column for each value, as the number of columns could quickly get out of hand. Instead you could have a table:
myentity(id, name)
for storing the entities represented by the JSON and
attributes(id, myentity_id, key, value)
for storing its attributes. This would be a neat schema with all the dinamicity you could want.
hello i want to create function with returning data, for example when i have the function advert i want to make it every time show what i need, i have the table id, sub_id, name, date, and i want to create the function that i can print every time what i need advert(id), advert(name), i want to make it to show every time what i need exactly and i want to save all my result in array, and every time grab the exactly row that i want
<?php
function advert($data){
$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
$data = array(
'id' => $row['id']
);
}
return $data;
}
echo advert($data['id']);
?>
but my result every time is empty, can you help me please?
There are so many flaws in this short piece of code that the only good advice would be to get some beginners tutorial. But i'll put some effort into explaining a few things. Hopefully it will help.
First step would be the line function advert($data), you are passing a parameter $data to the method. Now later on you are using the same variable $data in the return field. I guess that you attempted to let the function know what variable you wanted to fill, but that is not needed.
If I understand correctly what you are trying to do, I would pass in the $id parameter. Then you can use this function to get the array based on the ID you supplied and it doesnt always have to come from the querystring (although it could).
function advert($id) {
}
Now we have the basics setup, we want to get the information from the database. Your code would work, but it is also vulnerable for SQL injection. Since thats a topic on its own, I suggest you use google to find information on the subject. For now I'll just say that you need to verify user input. In this case you want an ID, which I assume is numeric, so make sure its numeric. I'll also asume you have an integer ID, so that would make.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
}
Then I'll make another assumption, and that is that the ID is unique and that you only expect 1 result to be returned. Because there is only one result, we can use the LIMIT option in the query and dont need the while loop.
Also keep in mind that mysql_ functions are deprecated and should no longer be used. Try to switch to mysqli or PDO. But for now, i'll just use your code.
Adding just the ID to the $data array seems useless, but I guess you understand how to add the other columns from the SQL table.
function advert($id) {
if (!is_int($id))
return "possible SQL injection.";
$query = mysql_query("SELECT * FROM advertisement WHERE id = $id LIMIT 1");
$row = mysql_fetch_assoc($query);
$data = array(
'id' => $row['id']
);
return $data;
}
Not to call this method we can use the GET parameter like so. Please be advised that echoing an array will most likely not give you the desired result. I would store the result in a variable and then continue using it.
$ad = advert($_GET['id']);
if (!is_array($ad)) {
echo $ad; //for sql injection message
} else {
print_r($ad) //to show array content
}
Do you want to show the specific column value in the return result , like if you pass as as Id , you want to return only Id column data.
Loop through all the key of the row array and on matching with the incoming Column name you can get the value and break the loop.
Check this link : php & mysql - loop through columns of a single row and passing values into array
You are already passing ID as function argument. Also put space between * and FROM.
So use it as below.
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$data."'");
OR
function advert($id)
{
$query = mysql_query("SELECT * FROM advertisement WHERE id = '".$id."'");
$data = array();
while($row = mysql_fetch_assoc($query))
{
$data[] = $row;
}
return $data;
}
Do not use mysql_* as that is deprecated instead use PDO or MYSQLI_*
try this:
<?php
function advert($id){
$data= array();
//$id = $_GET['id'];
$query = mysql_query("SELECT *FROM advertisement WHERE id = $id");
while($row = mysql_fetch_assoc($query)){
array_push($data,$row['id']);
}
return $data;
}
var_dump($data);
//echo advert($data['id']);
?>
I am using Codeigniter's Session class to store session values in the database. Contained within the userdata field is the user's username and other values.
I want to get the username from each userdata field where the lastactivity is >= let's say 5 minutes.
The only way I can think to accomplish this is:
search for users active in last 5 minutes
get the userdata for each row returned
unserialise userdata
extract username
However this seems like the long way. Is there a cleaner/better way to do this?
Try this code.
$query = $this->db->select('user_data')->get('ci_sessions');
$user = array(); /* array to store the user data we fetch */
foreach ($query->result() as $row)
{
$udata = unserialize($row->user_data);
/* put data in array using username as key */
$user[$udata['user_name']] = $udata['user_role'];
}
from the result array, u can fetch needed information.