I got two table which I would like to query from, which the users table and the user_job table
users table structure
user_job table
What I want to achieve is to write a MySQL query in CodeIgniter to display user information from users table if user_status in users table is "Active" And if there is no row in user_job table where user_job_status is equal to "On Probation" or user_job_status is equal to "Active"
In simple English, I want to display a user information if a user not currently on a job.
My current Codeigniter Model code is:
//get all user that are not currently assigned to a position
function get_idle_user(){
$this->db->select('*');
$this->db->from('users');
$this->db->join('user_job', 'user_job.user_id_fk = users.user_id', 'INNER');
$this->db->where('users.user_status','Active');
$this->db->where("(user_job.user_job_status != 'Active' OR user_job.user_job_status != 'On Probation')", NULL, FALSE);
$this->db->group_by('users.user_id');
if($query = $this->db->get()){
return $query;
}else{
return false;
}
}
The problem with this code that it will still display user information if there is a row related to a user and user_job_status does not satisfy the where condition above.
Please Help.
I believe this is what you are after ...
$db->select('user_id_fk,COUNT(*) as `Tally`');
$db->where('user_job_status','On Probabtion');
$db->or_where('user_job_status','Active');
$db->group_by('user_id_fk');
$sub = $db->get_compiled_select('user_job_table');
$db->join("($sub) ujt",'ujt.user_id_fk = users.user_id AND Tally = 0','left');
$db->where('user_status','Active');
// View this query in full
//echo $db->get_compiled_select('users_table');
// Get the data
$data = $db->get('users_table')->result_array();
Note:
You don't need select('*') - it isn't needed
You don't need ->from() - it can be used in the get() element
I have left in the get_compiled_select which will allow you to see the full query and get an idea what its doing. You should comment out the $data line if you uncomment the echo line.
What this query is doing is saying get all users from the job_table which don't have the status Active or On Probation and a list of User ID's. That way you can then get Active users from the users_table and users with a tally of 0.
Related
Hey I want to create like system in php But I am facing some problem on it ...
How can I create Like system that allow only one like per one user??
This is my code
<?php
if(isset($_POST['like'])){
$q = "SELECT * FROM likes WHERE `username` = '".$_SESSION['recieveruser']."'";
$r = mysqli_query($con, $q);
$count = mysqli_num_rows($r);
if ($count == "0") {
$q1 = "INSERT INTO likes (`username`, `likecount`)VALUES('".$_SESSION['recieveruser']."', '1')";
$result1 = mysqli_query($con, $q1);
} else {
while($row = mysqli_fetch_array($r)) {
$liked = $row['likecount'];
}
$likeus = ++$liked;
$q2 = "UPDATE likes SET likecount='".$likeus."' WHERE username = '".$_SESSION['recieveruser']."'";
$result2 = mysqli_query($con, $q2);
}
}
give me some suggestions
I want only one like per user
In this code every user can give Many likes to another user but I want only one like per one user and I want to display the name of the user who gave like if it's possible
This is only user like code...
I created simliar like system on my website. In my likes table, I had these columns:
Id of comment, that has been liked
Id of user who liked
Id of like (for removal)
When user clicked like, I inserted new row into likes table, with two known values. ID of like was autoincremented.
To show number of likes, I filtered by id of comment and grouped by users id (just to be sure). The number was obtained using count.
select count(*) from likes where comment_id = 666 group by user_id;
Even if you let user insert multiple times, the like counts only as one. But best would be to check, if current user already liked and dont let him do that. For this task, insert on duplicate key update could be used, to spare if exists db request (select).
You should not use the code you posted above. First of all, your code is vulnerable to SQL-Injections and therefore you should use Prepared Statements (https://www.php.net/manual/de/mysqli.quickstart.prepared-statements.php). Second, $_SESSION variables are depricated (https://www.php.net/manual/en/reserved.variables.session.php).
Lets assume you want users only to be able to like a post once. Then, instead of the column likecount you would need a post-id which uniquely identifies the post.
Define the combination post-id and username as a primary key in your database.
Now your code just have to check whether you find the username with the according post-id in the table likes.
In case you do not find the username with the according post-id in the table, you have to INSERT the username and the post-id
I'm making a notifications widget on my website and I'm trying to make it so that if a notification is marked as read, that notification ID will be inserted into another table (table 'b') along with their username so that it is marked as read. Now the problem that I run into is when displaying all notifications (whether they're read or unread) I don't know how to indicate if the notification exists in the secondary table
The currently SQL query is as follows:
$qry = "SELECT * FROM notifications WHERE (notif_recipient = '$user') ORDER BY notif_date DESC";
What I'd like to do is make the query much more complex in order to indicate if a notification exists in another table, so something along the lines of:
$qry = "SELECT notif_id,notif_message,(CASE SELECT notif_is_read AS '1' WHERE notif_id.notifications = notif_id.notifications_read ELSE SELECT notif_is_read AS '0') FROM notifications WHERE (notif_recipient = '$user') ORDER BY notif_date DESC";
Is something like this possible or is it as preposterous as my lack of ability for writing SQL queries
As Marc B had suggested, I decided to use LEFT JOIN in order to identify which messages currently exist in the secondary table, with my query looking as such:
$qrytest = "SELECT notifications.notif_id,notifications.notif_message,notifications.notif_flag,notifications.notif_poster,notifications.notif_date,notifications_read.notif_read_count FROM notifications LEFT JOIN notifications_read ON notifications.notif_id=notifications_read.notif_id WHERE ((notif_recipient = 'all') OR (notif_recipient = '$id')) ORDER BY notif_date DESC,notif_flag DESC";
This in turn will return the results of my primary table (notifications) and if the same notification id exists in my secondary table, I decided to echo out that table's ID count, if the entry does not exist it will simply return as null
$exists = $row['notif_read_count'];
if ($exists !== ''){
// When NOT returning as null do something
} else {
// When exist returns as null do something
}
I've been using Grocery Crud to develop a simple local application that allows users to register themselves and like bands and rate them and select people they know that are also registered in the application.
Entities:
Person(person_id,person_URL, fullname, hometown)
Band(band_id,band_URL,band_name,country,genre)
Relationships:
Likes(person_id,band_id,rate)
Knows(person_id,known_person_id)
My questions are:
1) I want to return a table of person and known person like below:
KNOWS
person_id | fullname | known_person_id | known_fullname
but I can't use *set_relation_n_n* function 'cause the relationship is (Person -> Likes -> Person), so it's giving me error. The other solution I came up with is making a custom table making a query to return the values I want and show it in the table (code below). The custom table returned is correct but when I render it to my Grocery Crud table, I need to specify $crud->columns('person_id', 'fullname', 'known_person_id', 'fullname'), and it cannot differentiate the fullname of the person and the fullname of the known person. How would I make it in order to be able to show the table that way?
2) I have the same issue in another table but could manage that using the function *set_relation_n_n* 'cause it's a relationship (Person -> Likes -> Band), so since it's 2 different entities it didn't return me a error. The problem is that the query (code below) returns me the whole table and I want only 25 records per page. When I try to use "LIMIT 25" in the query, it returns me ONLY 25 records and the "next page" button doesn't work. Any solutions?
Below, all the information:
CODE for question 1:
function knows_management()
{
$crud = new grocery_CRUD();
$crud->set_model('model_socialnetwork');
$crud->set_table('knows');
$crud->set_subject('Known');
$crud->basic_model->set_query_str('SELECT tb1.person_id, tb1.fullname, tb1.known_person_id, person.fullname FROM (SELECT person.person_id, person.fullname, knows.known_person_id FROM person INNER JOIN knows ON person.person_id = knows.person_id) tb1 INNER JOIN person ON tb1.known_person_id = person.person_id');<br>
$crud->columns('person_id','fullname','known_person_id','fullname');
$output = $crud->render();
$this->_socialnetwork_output($output);
}
CODE for question 2:
function likes_management()
{
$crud = new grocery_CRUD();
$crud->set_model('model_socialnetwork');
$crud->set_table('likes');
$crud->set_subject('Like');
$crud->columns('person_id','fullname','band_id','band_name', 'rate');
$crud->basic_model->set_query_str('SELECT tb2.person_id, tb2.fullname, tb2.band_id, band.band_name, tb2.rate FROM(SELECT tb1.person_id, person.fullname, tb1.band_id, tb1.rate FROM(SELECT person.person_id, likes.band_id, likes.rate FROM person INNER JOIN likes ON person.person_id = likes.person_id) tb1 INNER JOIN person ON tb1.person_id = person.person_id) tb2 INNER JOIN band ON tb2.band_id = band.band_id');
$output = $crud->render();
$this->_socialnetwork_output($output);
}
Question 1) What if you use an alias name in your query, for example
SELECT tb1.person_id, tb1.fullname as Tb1fullName, tb1.known_person_id, person.fullname as PersonFullName
Question 2) I would not recommend you to add LIMIT directly / manually in your query. In the file application/config/grocery_crud.php, you have two options directly related to pagination
You should use and configure them properly
// The default per page when a user firstly see a list page
$config['grocery_crud_default_per_page'] = 25;
....
//Having some options at the list paging. This is the default one that all the websites are using.
//Make sure that the number of grocery_crud_default_per_page variable is included to this array.
$config['grocery_crud_paging_options'] = array('10','25','50','100');
I'm developing in php/sql a web application where users will be able to post items that they'd like to sell ( kinda like ebay ). I want non-members to be able to comment on the items or ask queries about items.
My problem is I want to display each item as well as any comment/query made about that item, in a similar manner as the way Facebook wall works.
I want to "append comments"(if any) to each item. The comments table is linked to the items table via column item_id. And the items table is linked to users table via column user_id. I have left joined users table with items table to display item details, i tried to left join comments table as well so that there are 3 joined tables.
That fails because no comments are displayed and only one item is displayed, despite there being multiple entries in each table. Here is the code i,m using.
$database->query
('
SELECT sale.*, query.*, users.id AS userid, users.username as user
FROM sale
LEFT JOIN users ON sale.user_id = users.id
LEFT JOIN query on sale.id = query.item_id
where category = "$category" ORDER BY sale.id DESC
');
$show = " "; //variable to hold items and comments
if ($database->count() == 0) {
// Show this message if there are no items
$show .= "<li class='noitems'>There are currently no items to display.</li>" ;
} else {
$show .= "<li>";
while ( $items = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show item details in html
";
while( $query = $database->statement->fetch(PDO::FETCH_ASSOC) )
{
$show .= "
//show queries below item details
";
}
$show .= "</li>" ;
}
Welcome to Stackoverflow!
I recommend you taking a look at pdo. If you are already using mysql_ functions, then I recommend you switch. More on that can be found here.
Now that your pointed to the direction of to what functions to use when connecting/running queries, you now should create your tables. I use phpmyadmin for managing my database, I find it very good, but it's up to you what you use. Once you've decided on the service you use to manage your database, you should then learn how to use it by doing some google searches.
Now you need to set up your table and structure it correctly. If you say you're having items, then you should make a table called items. Next create the columns to the properties of the items. Also I recommend reading about Database Normalization, which is a key aspect of setting up your SQL tables Etc.
Once you have everything set up, you've connected to your database successfully Etc. You now need to set up the "Dynamic Page". What I mean by this is, there's only one page, say called 'dynamic', then a variable is passed to the url. These are called GET HTTP requests. Here's an example of what one would look like: http://example.com/item?id=345.
If you've noticed, you'll see the ? then the id variable defined to 345. You can GRAB this variable from the url by accessing the built in PHP array called $_GET[]. You can then type in your variable name you want to fetch into the []'s. Here's an example.
<?php
$data = $_GET['varname']; // get varname from the url
if(isnumeric($data)){ // is it totally made out of numbers?
$query = "SELECT fieldname FROM table WHERE id=:paramname";
$statement = $pdo->prepare($query); // prepare's the query
$statement->execute(array(
'paramname'=>$data // binds the parameter 'paramname' to the $data variable.
));
$result = $statement->fetch(PDO::FETCH_ASSOC); // grabs the result of the query
$result = $result['fieldname'];
echo 'varname was found in the database with the id equal to:'.$data.', and the result being: '.$result;
}
?>
So now you can see how you can grab the variable from the url and dynamically change the content with-in the page from that!
Hope this helped :)
I have two tables: 'competitions' and 'entries'. On my competition table, I have a "completed" column that tells me if the competition has been run. On my entries table I have a user ID column and a competitions ID column. I am trying to create a JOIN in which I see if the user is able to compete by checking all the rows in the 'entries' table and then for each particular row checking if the corresponding competition ID is completed in the 'competitions' table. I'm not very strong with my joins and so far am slightly lost. This is what I have so far but it's not working properly:
$this->db->select('*');
$this->db->from('entries');
$this->db->join('competitions', 'competitions.id = entries.competition_id');
$this->db->where('entries.user_id', $user_id);
$this->db->where('competitions.complete', '0'); //0 for incomplete, 1 for complete
$query = $this->db->get();
if ($query->num_rows() > 0) {
return FALSE; //user is currently in an active competition
}else {
return TRUE; //user is not in an active competition
}
I am currently working in Codeigniter but an explanation in regular PHP would be fine also. Thanks so much for the help!
You may use left or right joins for better result you wish to get...
$this->db->join('table2','table1.id = table2.id','LEFT/RIGHT');
I thnk you can also use inner,outer joins...May hope it is useful