How does if else work? - php

How do i start on an if else statement to restrict?
Fields in database :
No_of_vacancy (shows the number of positions available in the company)
Assigned (shows the number of student assigned to company)
EG
ABC Co
No of vancacy = 2
Assigned student = 2
I have done the necessary statement
UPDATE job_details,
student_details
SET
assigned = assigned + 1
WHERE
student_details.jobscope1 = job_details.jobscope
AND student_details.jobscope1 = 'IT';
The above statement works fine. meaning each time query runs. 1 student will be added under assigned field in database. I want the query to stop after assigned field matches the no of vacancy field to avoid duplication.
My logic is that i have to use if else statement to restrict the amount of assigned students from going over the no of vacancy available which is 2.
how do i start?

And if you simply add, to the where, and (assigned + 1) < job_details.No_of_vacancy ?

Related

create an event on PhpMyAdmin

i have a table named request where i store name, last name,user_id, category amount and points. its a money request i made so amount can vary all the time.
and i have a table named user. that stores user id, category, name, last name
what i want to accomplish is create an event that triggers everyday at 23:00 and search for all user based on there category and update the table user if it finds any user category with he following condition.
category id 1,2,3 all user at the begin are 1, if user category is 1 and points are = 4000 then update table user by changing user category to 2 example
<?php
$points = data->info_from_db;
$user_category = data->info_from_db;
if ($user_category == 1 && $points == 400)
{
///update users set category ='2'
}
else {
echo "no update today";
}
?>
this can be done by php? all i need is to first get all sum(points) of each user and their category and update if the condition is true.

SELECT query is only SELECTING/CHECKING the first row, how do I SELECT/CHECK all

I have this simple query:
$q5 = "select listingid FROM userlisting WHERE userid = '$_SESSION[UserID]'";
$r5 = mysql_query($q5) or die(mysql_error());
$a5 = mysql_fetch_array($r5);
The userlisting table is a many to many relationship. It is used as a lookup table. Each userid can be associated with multiple listingids and vice versa.
Also in my file (a html template file) I have this code
if(!empty($_SESSION[UserID]) and $a5['listingid'] == $_GET['id']) :
So I am wanting to check if the listingid column in userlisting table = the id of the page (well, it is a property website and it is the id of the property). As each user can be associated with many listingids I need to be able to check multiple rows. But for some reason it only checks the very first row.
In the userlisting table there is the following test entries:
userid | listingid
1 1
1 2
So one user associated to two listingids. However, it is acting like this userid is only associated with listingid 1, the very first row.
You are only grabbing the first entry.
$a5 = mysql_fetch_array($r5);
This does not fetch the whole query result, but only the first row. If there is none, it will return false.
You have to create a loop to get more results.

results table in php

I am having trouble understanding how a loop I have created works.
I have input fields on another page, which where results are sent to the results table in my database, with team name, team score, opposition score, opposition name.
Now the page where the results are entered mirrors the current contents of the results table so that previously entered scores appear already in the correct input field, and the ones with no socres enetered are at 0.
This page works perfectly in that a score that is edited, replaces the score in the results table, blank ones are left blank etc.
Howwever, I need to use these results to update my league table table in my database.
Currently I have a rather large loop, which (after I have fetched team name, team score, opposition score, opposition name, from the results table), works out how many points to give that team, and the opposing team, plus how many to add to the 'win' column and the 'loss' column etc of my league table.
The problem I have is that it will only ever do one result per team, because on each iteration of the loop, as soon as it finds a matching if statement (ie if team_score>opposition score) it updates the table, before running through the other results to find that teams results.
Because an edited result needs to be treated as an edited result, not an additional result, this is the only way I have been able to find to get even close.
here is a snippet of the code. There are many more if statementswithin the for loop but they are not needed to describe the problem I am having.
$query = $database->query("SELECT team_name, team_score, opposition_score, opposition_name from results_a");
while ($row = $query->fetch(PDO::FETCH_NUM)) {
$team[] = ($row[0]);
$team_score[] = ($row[1]);
$opposition_score[] = ($row[2]);
$opposition[] = ($row[3]);
}
$count=count($team);
for ($i = 0; $i < $count; $i++) {
$team_bonus[$i] = $team_score[$i] / 2;
$opposition_bonus[] = $opposition_score[$i] / 2;
//TEAM WINS, NO OPPOSITION BONUS
else if (($team_score[$i] > $opposition_score[$i]) && ($team_bonus[$i] > $opposition_score[$i])) {
$team_points[]+=3;
$team_win[]+=1;
$team_draw[]+=0;
$team_loss[]+=0;
$team_extra[]+=0;
$opposition_points[]+=0;
$opp_win[]+=0;
$opp_draw[]+=0;
$opp_loss[]+=1;
$opp_extra[]+=0;
$team_played[]+=1;
$opposition_played[]+=1;
}
$team_gd[] = $team_score[$i] - $opposition_score[$i];
$opposition_gd[] = $opposition_score[$i] - $team_score[$i];
//UPDATE LEAGUE TABLE
$query = $database->query("UPDATE pool_a SET played='$team_played[$i]',
win='$team_win[$i]',
draw='$team_draw[$i]',
loss='$team_loss[$i]',
goals_for='$team_score[$i]',
goals_against='$opposition_score[$i]',
goal_difference='$team_gd[$i]',
bonus_points='$team_extra[$i]',
points='$team_points[$i]'
where team_name = '$team[$i]'");
$query2 = $database->query("UPDATE pool_a SET played='$opposition_played[$i]',
win='$opp_win[$i]',
draw='$opp_draw[$i]',
loss='$opp_loss[$i]',
goals_for='$opposition_score[$i]',
goals_against='$team_score[$i]',
goal_difference='$opposition_gd[$i]',
bonus_points='$opp_extra[$i]',
points='$opposition_points[$i]'
where team_name='$opposition[$i]'");
The+= within the if statement are useless, because instead of going to the next row where the team name is the first teams name, it runs the query, then when that teams name appears again, it replaces the data next time the query runs.
Very stuck, have spent a lot of time on this!
If you need any more info let me know.
Many thanks

PHP/MySQL make top 10 out of selection

A user can input it's preferences to find other users.
Now based on that input, I'd like to get the top 10 best matches to the preferences.
What I thought is:
1) Create a select statement that resolves users preferences
if ($stmt = $mysqli->prepare("SELECT sex FROM ledenvoorkeuren WHERE userid = you"))
$stmt->bind_result($ownsex);
2) Create a select statement that checks all users except for yourself
if ($stmt = $mysqli->prepare("SELECT sex FROM ledenvoorkeuren WHERE userid <> you"))
$stmt->bind_result($othersex);
3) Match select statement 1 with select statement 2
while ($stmt->fetch()) {
$match = 0;
if ($ownsex == $othersex) {
$match = $match + 10;
}
// check next preference
4) Start with a variable with value 0, if preference matches -> variable + 10%
Problem is, I can do this for all members, but how can I then select the top 10???
I think I need to do this in the SQL statement, but I have no idea how...
Ofcourse this is one just one preference and a super simple version of my code, but you'll get the idea. There are like 15 preference settings.
// EDIT //
I would also like to see how much the match rating is on screen!
Well, it was a good question from the start so I upvoted it and then wasted about 1 hour to produce the following :)
Data
I have used a DB named test and table named t for our experiment here.
Below you can find a screenshot showing this table's structure (3 int columns, 1 char(1) column) and complete data
As you can see, everything is rather simple - we have a 4 columns, with id serving as primary key, and a few records (rows).
What we want to achieve
We want to be able to select a limited set of rows from this table based upon some complex criteria, involving comparison of several column's values against needed parameters.
Solution
I've decided to create a function for this. SQL statement follows:
use test;
drop function if exists calcMatch;
delimiter //
create function calcMatch (recordId int, neededQty int, neededSex char(1)) returns int
begin
declare selectedQty int;
declare selectedSex char(1);
declare matchValue int;
set matchValue = 0;
select qty, sex into selectedQty, selectedSex from t where id = recordId;
if selectedQty = neededQty then
set matchValue = matchValue + 10;
end if;
if selectedSex = neededSex then
set matchValue = matchValue + 10;
end if;
return matchValue;
end//
delimiter ;
Minor explanation
Function calculates how well one particular record matches the specified set of parameters, returning an int value as a result. The bigger the value - the better the match.
Function accepts 3 parameters:
recordId - id of the record for which we need to calculate the result(match value)
neededQty - needed quantity. if the record's qty matches it, the result will be increased
neededSex - needed sex value, if the record's sex matches it, the result will be increased
Function selects via id specified record from the table, initializes the resulting match value with 0, then makes a comparison of each required columns against needed value. In case of successful comparison the return value is increased by 10.
Live test
So, hopefully this solves your problem. Feel free to use this for your own project, add needed parameters to function and compare them against needed columns in your table.
Cheers!
Use the limit and offset in query:
SELECT sex FROM ledenvoorkeuren WHERE userid = you limit 10 offset 0
This will give the 10 users data of top most.
You can set a limit in your query like this:
SELECT sex FROM ledenvoorkeuren WHERE userid <> yourid AND sex <> yourpreferredsex limit 0, 10
Where the '0' is the offset, and the '10' your limit
More info here
you may try this
SELECT sex FROM ledenvoorkeuren WHERE userid = you limit 0, 10 order by YOUR_PREFERENCE

query to count MySQL rows

Trying to get a count (to later multiply with a rate) of names in upto (if data is present in one or more) four rows. In other words, there is a price per person occupying a room. So, I want to count the number of persons in the room by names entered on the form and saved in the database table.
I could simply add a field where the user also selects the number of people in addition to completeing the name fields but this seems redundant (and prone to error).
Setup
Table: 1.clients which has columns:
id,
tourbk_id,
tourstart,
roomtype1,
client1_name,
client2_name,
client3_name,
client4_name
Question
I have a query which currently checks the roomtype to the per person price for that room type and is working to produce the result but, of course, it is only returning (for two people in a room) the price person for double occupancy.
E.g.: (per person prices)... single = $10; double = $20; triple = $30; quad = $40
My current result for double room is $20 (which echo's next to "Price per person". I need a query to count the total persons in this double and multiple times the rate ... "Total: query[$20 * 2]"
How do I code a query to count the "client_name" entries in a table?
Here I've added a virtual column named ClientCount which is the count of clients in the room. I like to use client1_name > '' because it works whether you use blanks or NULLs, and saves me from asking a question.
SELECT
id,
tourbk_id,
tourstart,
roomtype1,
client1_name,
client2_name,
client3_name,
client4_name,
CASE WHEN client1_name > '' THEN 1 ELSE 0 end +
CASE WHEN client2_name > '' THEN 1 ELSE 0 end +
CASE WHEN client3_name > '' THEN 1 ELSE 0 end +
CASE WHEN client4_name > '' THEN 1 ELSE 0 end ClientCount
FROM TBL
You ought to consider normalising your schema by having a separate client_names table that relates a single name column to a single booking identifier: multiple clients would then be represented by multiple records in that new table. You would count clients with:
SELECT COUNT(*) FROM client_names WHERE booking_id = ...
However, with your current structure (and assuming that the name columns are NULL if there is no such client), you could do:
SELECT (client1_name IS NOT NULL)
+ (client2_name IS NOT NULL)
+ (client3_name IS NOT NULL)
+ (client4_name IS NOT NULL)
AS client_count
FROM clients
-- etc.
and, as a round-about way of doing it I thought of the following which also works (will just need to make a case for the 1, 2, 3, and 4 ["if roomtype1='sgl', then $mult=1, if roomtype='dbl', then $mult=2...] multiplyer to check for the other room types):
$total = ($roomrate['roomprice'] * 2);
echo "Total this booking : ";
echo $total;
thanks to all for the help!

Categories