Joomla 3x - Profile Fields - mysql

I have added a checkbox to the user profile and need to know how to get a list of all the user email addresses where they have checked the checkbox. I would like to just run a SQL query, but can't see where the value is stored.

All the profile data is stored in #__user_profiles table. To retrieve the data from the profile table you can perform this query
// Get a db connection.
$db = JFactory::getDbo();
// Create a new query object.
$query = $db->getQuery(true);
// Select all records from the user profile table where key begins with "checkbox.".
// Order it by the ordering field.
$query->select($db->quoteName(array('user_id', 'profile_key', 'profile_value')));
$query->from($db->quoteName('#__user_profiles'));
$query->where($db->quoteName('profile_key') . ' LIKE '. $db->quote('\'checkbox.%\''));
// Reset the query using our newly populated query object.
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
You will get object list of all those users who clicked on your checkbox. Remember to use the profile_key name in place of checkbox

Ok - I have now managed to answer my own question (I took an export of the database as a SQL file, ticked the checkbox as a test user, made another export and then compared the files to see what had changed).
The values are stored in the jos_fields_values table. The query below assumes that there is only one checkbox - if you have more than one you will need to query the field_id as well, Replace xxx with the prefix of your Joomla installation.
SELECT email FROM xxx_users INNER JOIN xxx_fields_values ON xxx_users.ID=xxx_fields_values.item_id

Related

Yii2 - getting sum of a column

I found this in the guide, but have no idea how to implement the same
yii\db\Query::count(); returns the result of a COUNT query. Other
similar methods include sum($q), average($q), max($q), min($q), which
support the so-called aggregational data query. $q parameter is mandatory
for these methods and can be either the column name or expression.
Say for example I have a table name 'billing' with columns:
name amount
charge1 110.00
charge2 510.00
Total - 620.00
How I implement using
yii\db\Query::sum('amount');
I have also tried like
$command = Yii::$app->db->createCommand("SELECT sum(amount) FROM billing");
yii\db\Query::sum($command);
but page generates error.
Thanks.
The first part of code you tried appears to be attempting to use Query Builder. In this case, you must create an instance of a query, set the target table, and then compute the sum:
Via Query Builder
(http://www.yiiframework.com/doc-2.0/guide-db-query-builder.html):
$query = (new \yii\db\Query())->from('billing');
$sum = $query->sum('amount');
echo $sum;
The second part of code you tried appears to be attempting to use Data Access Objects. In this case, you can write raw SQL to query the database, but must use queryOne(), queryAll(), queryColumn(), or queryScalar() to execute the query. queryScalar() is appropriate for an aggregate query such as this one.
Via Data Access Objects
(http://www.yiiframework.com/doc-2.0/guide-db-dao.html):
$command = Yii::$app->db->createCommand("SELECT sum(amount) FROM billing");
$sum = $command->queryScalar();
echo $sum;
Within a model the sum could also be fetched with:
$this->find()->where(...)->sum('column');
You can directly use yii query concept in Search Model
$this->find()->from('billing')->where(['column'=>value])->sum('amount');
OR
$this->find()->where(['column'=>value])->sum('amount');
Outside the Model (Billing is model name)
Billing::find()->where(['column'=>value])->sum('amount');
i hope your model name is Billing
inside Billing model use
$this->find()->sum('amount');
in other models
Billing::find()->sum('amount');

Inserting multiple selected dropdown values into a single column

Iam having a form which contaings of name,id etc..in this form iam getting dropdown from the same table only some ids here iam selecting multiple values and that should be inserted into db but only one value is inserting into the table remaining is not inserting can any one help me regarding this.
Model:
$data=array(
'first_name'=>$this->input->post('first_name'),
'exam_id'=>$this->input->post('exam_id'),
);
$this->db->insert('table',$data);
This is my dropdown
$this->table = 'table';
$exam = $this->dropdown('exam_id','examr_id');
return $exam;
This is my view:
$exam['']='--Select --';
$exam_id="id='exam_id' ";
if($this->input->post('exam_id')) $selected=$this->input->post('exam_id');else $selected='';
echo form_multiselect('exam_id',$exam,$selected,$exam_id);?>
any one help me it will be more helpfull for me
When you select multiple values and check that selected value pass in your url using GET or POST method. And than split your requested data using implode function. and save into database.

How to add multiple query WHERE statements that may or may not have a value

I'm creating a form that allows the user to search a database for different criteria: location, city, min price, max price, etc.
I have a "base" select statement: SELECT * FROM table.
In the search form there are several text boxes and dropdowns that may or may not have values, depending on what the user wants to search by.
I'm having trouble figuring out how to add WHERE clauses to the sql statement when there may or may not be a value to use for a particular table column (based on the user's selection).
Thanks for anyone's help!
In the code where you generate the SQL, check what fields the user has entered and append more checks to the query as you find more input from the user. Quick example in PHP:
$sql = "SELECT * FROM table";
$where_checks = array();
if (isset($_POST['city']))
$where_checks[] = "city = '{$_POST['city']}'";
if (isset($_POST['location']))
$where_checks[] = "location = '{$_POST['location']}'";
// Add more stuff here
if (count($where_checks) > 0)
$sql .= " WHERE " . implode('AND', $where_checks);
// run query
I have intentionally left out sanitation / escaping of the post input to keep the example simple. But you obviously must sanitize the input as well.
Mind the extra space before the WHERE otherwise the query will be broken.
Use this approach
select
columns
from
table
where
(location=#location or #location is null) and
(city=#city or #city is null) and
.
.

MySQL Query - Check if data row contains a user_id

I have a sessions table and what I am trying to do is run a query to check if a certain account is logged in.
My query looks like this:
SELECT id FROM sessions WHERE data LIKE '%4%'
But with a query like that, if the user_id of "14" is logged in, that query will return True. How do I check to see if a certain number exists and matches exactly?
Include the delimiters in your search:
WHERE data LIKE '%:4;%'
why don't you add another field for user_id to the session table?
EXAMPLE:
I have a site where a user can only be logged in from one location at a time. If they try and log in from another location (IE start a new session) then i kill all of their previous logins.
So as part of my login script:
// log this user out of any other active sessions
$sql = sprintf("DELETE
FROM sessions
WHERE id_user=%s",
mysql_real_escape_string($_SESSION['id_user'])
);
// Associate this session with this user
$sql = sprintf("UPDATE sessions
SET id_user=%s
WHERE id=%s",
mysql_real_escape_string($_SESSION['id_user']),
session_id()
);
and so i can have id_user as an additional field in my session FKed to my user table... its a little more normalized and lets you do quick "Who is currently using this site" queries without too much parsing and fuss.

Erratic Problems Adding User ID to MySQL Table of User Lists

I have a site where users can log-in and add items to a list.
The user logs in and the session stores their e-mail, which I use to identify them in a user table.
Then, they can input a list item and add to a list table that contains their ID and their list items.
Sometimes the ID is added and sometimes it comes up null (however, the list item text is always added). This seems erratic because most of the time the ID is included.
Any ideas? The table type is MyISAM. I'm new to programming, btw.
Here's an example of my code:
<?php
session_start();
$item = $_REQUEST['item'];
$email = $_SESSION['email'];
if ($item)
{
mysql_connect("localhost","root","") or die("We couldn't connect!");
mysql_select_db("table");
$query = mysql_query("SELECT ID FROM users WHERE email='".$_SESSION['email']."'");
$result = mysql_result($query,0);
$user_id = $result;
mysql_query("INSERT INTO items (user_ID,item_name) VALUES('$user_id','$item')");
So every time I test it by logging into my site myself, no problems. But increasingly, I have users who try to add items and it creates a record where item_name shows up correctly but user_ID is set to 0 (default).
First off, read what I said about SQL injection attacks in the comments to your question.
It would be a good idea to store the user_id in the $_SESSION so you wouldn't have to query for it every time based on the email... but if you insist on just having the email in the $_SESSION, then you actually only need one query. Adjusted code:
<?php
session_start();
$item = mysql_real_escape_string($_REQUEST['item']);
if (!empty($item) && isset($_SESSION['email']))
{
mysql_connect("localhost","root","") or die("We couldn't connect!");
mysql_select_db("table");
mysql_query("INSERT INTO items (user_ID, item_name) VALUES ((SELECT ID FROM users WHERE email='{$_SESSION['email']}'), '$item')");
}
Like Jeff Watkins said, the session could be timed out, so it would be a good idea to first check if it's set using isset().
Otherwise if you stored the userid in the session, you could just reference it directly as $_SESSION['user_id'] instead of doing a subquery in the insert.