error in subject registration - php

I'm facing a problem here. First off, what I'm doing here is subject registration system for students. I've set a part of code to limit the same student from registering the same subject again and again. But sadly, that has given me a reversed effect. My error is that when a student registered a subject, other students can't register that particular subject even though they have never registered it before. Any help would be much appreciated.
<?php
if(!isset($_POST['submit'])){
exit('Unauthorized access!');
}
$name = $_POST['name'];
$studentid = $_POST['studentid'];
$program = $_POST['program'];
$fintake = $_POST['fintake'];
$courseid = $_POST['courseid'];
include("include/config.php");
//this could be the problem,i'm not sure
$check_query = mysqli_query($link, "SELECT r_id FROM course_registration WHERE r_cid='$courseid' limit 1");
if(mysqli_fetch_array($check_query))
{
echo 'Error:Course ID:',$courseid,' already exists. Return';
exit;
}
$result = mysqli_query($link, "SELECT * FROM course_list WHERE c_cid = '$courseid'");
if(mysqli_fetch_array($result))
{
$sql = "INSERT INTO course_registration (r_name,r_sid,r_program,r_fintake,r_cid) VALUES('$name','$studentid','$program','$fintake','$courseid')";
if(mysqli_query($link,$sql))
{
exit('Success! Register course successfully. Homepage');
}
else
{
echo 'Sorry! Add data failed:',mysqli_error($link),'<br />';
echo 'Click here Return retry';
}
}
else
{
echo 'Sorry! Wrong course id.','<br />';
echo 'Click here Return retry';
}
?>
Database: course_registration
r_id r_name r_sid r_program r_fintake r_cid
1 TAN KOON ENG 0187904 DIP-CS 01-2015 DTP-3033
2 TAN KOON ENG 0187904 DIP-CS 01-2015 DCS-22104
3 CRISTIANO RONALDO 0190007 DIP-GT 09-2016 DGP-2254
4 CRISTIANO RONALDO 0190007 DIP-GT 09-2016 DGA-1224

Your checking courseid is exists in table but need to check courseid is exists for particular student so you need to add where clause like this
SELECT r_id FROM course_registration WHERE r_cid='$courseid' AND r_sid='$studentid'"

you can try this add and studentid in where
$check_query = mysqli_query($link, "SELECT r_id FROM
course_registration WHERE r_cid='$courseid' AND r_sid='$studentid'");

In your given case, you are checking the course id in the database and limiting to 1 only hence, it reports an error in your case. To check whether a student has enrolled into course or not. You must also check the student id with courseid. Maybe, this query might help you:
SELECT r_id FROM course_registration WHERE r_sid='$studentid' AND r_cid='$courseid'"

Related

Create a "Secret Santa" generator using MySQL and PHP

I am trying to create a Secret Santa system using a PHP page and a MySQL database to store the details so if someone forgets their match they can re-request it.
Step 1: I created a random number generator based on the number of people in the list in the database.
Count Function:
$maxSQL = "SELECT COUNT(id) as total FROM secretsanta";
$maxRS = mysqli_query($conn, $maxSQL);
$maxQuery = mysqli_fetch_array($maxRS);
$maxpersons = $maxQuery['total'];
Then the Random Number Generator:
$assigned = rand(1,$maxpersons);
Step 2: Test if the random number matches the persons own id and regenerate a new number if true.
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id);
Step 3: Write the paired id to the persons database record.
$assignSQL = "UPDATE secretsanta SET assigned = '".$assigned."' WHERE secretsanta.id = ".$id;
if (mysqli_query($conn, $assignSQL)) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . mysqli_error($conn);
}
The Problem: Now I need to check that other people aren't assigned to that person or otherwise some could miss out and others would get more than others.
I tried to implement a function that contained a query to test each record to see if that number already existed and was hoping to add it as a condition to perhaps a while or do while statement?
if (!function_exists('checkRandom')){
function checkRandom($funcid){
$Check_SQL = "SELECT assigned FROM secretsanta ORDER BY id ASC";
$Check_RES = mysqli_query($conn, $Check_SQL);
if (Check_RES) {
while ($CheckArray = mysqli_fetch_array($Check_RES, MYSQLI_ASSOC)) {
$CheckAsgn = $CheckArray['assigned'];
if ($funcid==$CheckAsgn) {return true;}else{return false;}
}
}
}
}
Then implement it into the do while statement like this:
do {
$assigned = rand(1,$maxpersons);
} while ($assigned==$id||checkRandom($assigned));
No luck so far...HELP!.. please :)
P.S. I know there are websites that already do this, I just don't trust them to give out mine and family email address' if I can make my own private version myself.
Using your method, the first few assignments will be done with no problem, but imagine the last unassigned entry and how many times it will try a random number only to find the person with that id is already assigned..
I'm gonna give you another approach to your problem: for each user that you want to assign a santa to, make a new SELECT statement with a WHERE clause that lets you select only those users that are not assigned yet.
check out my code and see if that helps you. I just typed this and didnt test it so there could be some mistakes.
// load all unassigned users into an array
$unassignedUsers = [];
$query = "SELECT id, assigned FROM secretsanta WHERE assigned is NULL";
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedUsers[] = $row;
}
if(count($unassignedUsers) == 1){
echo 'There is only 1 unassigned user. Therefore he cannot be matched';
} else {
// for loop for each user in DB that is not assigned yet
//for ($i = 1;$i <= count($unassignedUsers); $i++){
$i = 0;
foreach($unassignedUsers as $user)
// if its the second-to-last iterations of the for-loop, check for legality of the last one
if(count($unassignedUsers) - $i == 1){
$lastUserID = $unassignedUsers[count($unassignedUsers)-1]['id'];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id = ".$lastUserID;
$res = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($res);
if ($rowcount){
// last user is still unassigned
$query = "UPDATE secretsanta SET assigned = '".$lastUserID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
} else {
// select all unassigned users
$unassignedIDs = [];
$query = "SELECT id FROM secretsanta WHERE assigned is NULL AND id <> ".$user['id'];
$res = mysqli_query($conn, $query);
while($row = mysqli_fetch_assoc($res){
$unassignedIDs[] = $row['id'];
}
// get a random id from $unassignedIDs
$randomIndex = rand(0, count($unassignedIDs)-1);
$randomID = $unassignedIDs[$randomIndex];
// assign $randomID to user
$query = "UPDATE secretsanta SET assigned = '".$randomID."' WHERE id = ".$user['id'];
if(mysqli_query($conn, $query)){
echo "Record with id ".$user['id']." updated successfully";
} else {
echo "Error updating record: ".mysqli_error($conn);
}
}
$i++;
}
}
last edit: refactored whole code so it is able to be run multiple times and only assigns new users who are not assigned yet.
Step 1 is dependent on have a contiguous set of ids for the people. Think what happens if '3' leaves the company and it hires 6 to replace them....1,2,4,5,6 ($maxpersons=5)
"Now I need to check" - no you are still trying to solve the problem by guessing then seeing if your guess worked. Use an algorithm which is always going to return a correct result. The method below requires the addition of a temporary field 'sequence' of type float.
mysqli_query($conn,"UPDATE secretsanta SET sequence=RAND()");
$first=false;
$prev=false;
$all=mysqli_query($conn, "SELECT * FROM secretsanta ORDER BY sequence, id");
while ($r=mysqli_fetch_assoc($all)) {
if (false===$first) {
$first=$r['id'];
} else {
save_pair($prev, $r['id']);
}
$prev=$r['id'];
}
save_pair($prev, $first);
(but with better error checking)

Need help calculating wins and losses from points scored

I am creating a website in php to log ping pong scores for my school, and currently the player who wins will log the WinnerID, LoserID, PointsFor, PointsAgainst. I have two tables with the following relationships.
Table: users
user_ID (PK)
username
Elo
Table: games
game_id (PK)
WinnerID (FK)
LoserID (FK)
PointsFor
PointsAgainst
My insert statement in the php file is:
INSERT INTO games(WinnerID,LoserID,PointsFor,PointsAgainst) VALUES('$Winner_ID','$Loser_ID','$userscore','$oppscore')"
Here is what I have tried, but it doesn't display the scores correctly.
SELECT min(u.username) 'Username', COUNT(g.WinnerID) 'Wins', sum(g.PointsFor) 'Points For', sum(g.PointsAgainst) 'Points Against', u.Elo 'Ranking'
from games g
LEFT JOIN users u
on g.WinnerID = u.user_id
Group by g.WinnerID
As you can see by the image above, the points for and points against totals don't add up. Currently, it only displays the stats for whoever was winner. Meaning if PlayerA wins 21-5, it will show up from the select statement, but PlayerB will not show a score of 5-21. Any help is appreciated.
PHP code for page to enter scores:
if(isset($_POST['btn-post']))
{
$opponent = $_POST["opponent"];
//$opponent = array_key_exists('opponent', $_POST) ? $_POST['opponent'] : false;
$userscore = mysql_real_escape_string($_POST['userscore']);
$oppscore = mysql_real_escape_string($_POST['oppscore']);
if($userscore != $oppscore)
{
if($userscore > $oppscore)
{
$Winner_ID = $_SESSION['user'];
$query = mysql_query("SELECT user_id FROM users WHERE username = '".$opponent."'");
$result = mysql_fetch_array($query) or die(mysql_error());
$Loser_ID = $result['user_id'];
$query1 = mysql_query("SELECT Elo FROM users WHERE user_id=".$_SESSION['user']);
$result1 = mysql_fetch_array($query1) or die(mysql_error());
$winnerRating = $result1['Elo'];
$query2 = mysql_query("SELECT Elo FROM users WHERE user_id=".$Loser_ID);
$result2 = mysql_fetch_array($query2) or die(mysql_error());
$loserRating = $result1['Elo'];
$rating = new Rating($winnerRating, $loserRating, 1, 0);
$results = $rating->getNewRatings();
if(mysql_query("UPDATE users SET Elo = " . $results['a'] . " WHERE user_id=".$_SESSION['user']))
{
}
else
{
?>
<script>alert('There was an error while entering winners(user) ranking...');</script>
<?php
}
if(mysql_query("UPDATE users SET Elo = " . $results['b'] . " WHERE user_id=".$Loser_ID))
{
}
else
{
?>
<script>alert('There was an error while entering losers(opp) ranking..');</script>
<?php
}
}
elseif($oppscore > $userscore)
{
$Loser_ID = $_SESSION['user'];
$query = mysql_query("SELECT user_id FROM users WHERE username = '".$opponent."'");
$result = mysql_fetch_array($query) or die(mysql_error());
$Winner_ID = $result['user_id'];
//get rating from user table in database
$query1 = mysql_query("SELECT Elo FROM users WHERE user_id=".$_SESSION['user']);
$result1 = mysql_fetch_array($query1) or die(mysql_error());
$loserRating = $result1['Elo'];
$query2 = mysql_query("SELECT Elo FROM users WHERE user_id=".$Loser_ID);
$result2 = mysql_fetch_array($query2) or die(mysql_error());
$winnerRating = $result1['Elo'];
$rating = new Rating($winnerRating, $loserRating, 1, 0);
$results = $rating->getNewRatings();
$results = $rating->getNewRatings();
if(mysql_query("UPDATE users SET Elo = " . $results['b'] . " WHERE user_id=".$_SESSION['user']))
{
}
else
{
?>
<script>alert('There was an error while entering losers(user) ranking...');</script>
<?php
}
if(mysql_query("UPDATE users SET Elo = " . $results['a'] . " WHERE user_id=".$Winner_ID))
{
}
else
{
?>
<script>alert('There was an error while entering winners(opp) ranking...');</script>
<?php
}
}
if(mysql_query("INSERT INTO games(WinnerID,LoserID,PointsFor,PointsAgainst) VALUES('$Winner_ID','$Loser_ID','$userscore','$oppscore')"))
{
?>
<script>alert('Your scores were successfully entered');</script>
<?php
}
else
{
?>
<script>alert('There was an error while entering your score...');</script>
<?php
}
}
else
{
?>
<script>alert('There cannot be a tie in ping pong, please re-enter your scores...');</script>
<?php
}
}
?>
Your query fails because it doesn't take into account the rows where the player loses. You can fix that by using unions. The following query should do what you want:
SELECT username AS "Username",
SUM(wins) AS "Wins",
SUM(PF) AS "Points For",
SUM(PA) AS "Points Against",
elo AS "Ranking"
FROM (
(SELECT users.user_ID,
users.username AS username,
COUNT(games.WinnerID) AS wins,
SUM(games.PointsFor) AS PF,
SUM(games.PointsAgainst) AS PA,
users.Elo AS elo
FROM users, games
WHERE games.WinnerID = users.user_ID
GROUP BY users.user_ID)
UNION ALL
(SELECT users.user_ID,
users.username AS username,
0 AS wins,
SUM(games.PointsAgainst) AS PF,
SUM(games.PointsFor) AS PA,
users.Elo AS elo
FROM users, games
WHERE games.LoserID = users.user_ID
GROUP BY users.user_ID)
) AS t
GROUP BY username
ORDER BY user_ID;
Note that in the "losing query" the field PointsAgainst should be counter as the player's "points for" and vice-versa.
Try it as an inner join, and get rid of the MIN() on the username column:
SELECT u.username, COUNT(g.WinnerID),
SUM(g.PointsFor), SUM(g.PointsAgainst), u.Elo
FROM users u, games g
WHERE u.user_id = g.WinnerID
GROUP BY u.username, u.Elo;
Also, before anyone else takes you to task, you should be using mysqli instead of mysql (or better yet, PDO) and you should be using prepared statements instead of dynamic SQL.
Your
INSERT INTO games(WinnerID,LoserID,PointsFor,PointsAgainst) VALUES('$Winner_ID','$Loser_ID','$userscore','$oppscore')
query contains the $userscore and $oppscore values in a potentially wrong order. The $Winner_ID and $Loser_ID may change in your conditional processing, but $userscore and $oppscore are not similarly flipped at that time.
Also your conditional structure is in general unnecessarily verbose. It seems like you should be able to just determine the winner and loser ID and score first, and then do all your processing once instead of resorting to error-prone copy-paste duplication of near-identical code.

transfer signup_data from registrationtbl to userstbl

Good day does anyone can help me about my problem?
i have a signup_form all the data inputted will insert to my registrationtbl, my problem is the code below just delete the data from registrationtbl. how can i move the data to the userstbl and remove it from the registrationtbl? thank you . hope someone may help me..
the code is also came from one of the topics here..
<?php
$con=mysqli_connect("localhost","root","","scouts");
if ( isset($_GET['id']) ) {`enter code here`
$id = $_GET['id'];
$result = mysqli_query($con,"SELECT * FROM registration WHERE id='$id'");
while($row = mysqli_fetch_array($result))
{
echo $row['idno'] . " " . $row['surname'];
echo "<br>";
}
$row = mysqli_query($con,"INSERT INTO users (surname, firstname, middlename, gender, idno, password, signup_date) 'SELECT * from registration WHERE id =$id");
$sql = mysqli_query($con,"DELETE FROM registration WHERE id='$id'");
echo "its deleted";
}
?>
why are you using 2 tables:
simply use users table only, and add a status field to the table, when user registered the status may be 0, when registration approved change status to 1... so there is no need for 2 tables...
or if u have to use both tables, my suggession is the use of a database trigger to insert value to the second table from 1st.

Check whether data is at table

I asked something about in_array() and I already got that working. But now I have a different problem:
I have a table that says which services are assigned to hosts: services_hosts(service_id, host_id).
How can I see if the service that is selected is already assigned to that host, also selected? Basically, I want to see if the specific line (service_id, host_id) already exists in that table.
EDIT:
The problem is that I want to compare in a separate file that has functions that connect to DB:
function addServiceToHost($service_name, $host_id)
{
$query = "INSERT INTO monitoring_hosts_services (service_id, host_id) values ((SELECT service_id FROM monitoring_services WHERE name = '".$service_name."'), '".$host_id."')";
$result = #pg_exec($this->conn, $query);
if ($row = pg_fetch_row($result))
{
"blabla error msg"
exit;
}
return $this->parseResultObj($result);
}
I might not unserstand your question correctly but would this do the trick:
SELECT * FROM ServerHostsTable WHERE service_id = '5' AND host_id = '8'
$query = ("SELECT * FROM ServerHostsTable WHERE service_id = '5' AND host_id = '8'")
if(mysql_num_rows($query)>0)
{
//the item is in the db
}
else
{
//not in the db
}
hope this helps
your question is not very clear, but from what I understand you want to test if a specific row is inserted into a database table. you could do this like this:
$result=mysql_query("SELECT service_id FROM services_hosts WHERE service_id=$theserviceid AND host=$thehostid");
if($row=mysql_fetch_row($result){
echo "already in the db";
} else {
echo "not in the db!";
}
I would run this query.
$sql = "SELECT COUNT(*) AS ret\n";
$sql.= "FROM services_hosts\n";
$sql.= "WHERE service_id = $service_id\n";
$sql.= "AND host_id = $host_id";
The result should be one row with one field (named ret):
0 - the service is not present on the host
1 - service is present on the host
enything else - there is a problem with table in database

use a while mysql_fetch_array and UPDATE during the loop - PART TWO

I apologize for not knowing how else to do this. I went to add to my other question, and I could not figure out how to append this to it.
I am trying to apply your answer to the previous question in another place.
In this instance I have a bit more going on but thought I could do the same thing as above -with the adjustment of changing id for user_name, since the ids would not match table to table, but the user_name does. I know I am biting off a lot for my first project but I really like this coding stuff. Hope I am not pulling on too many shirt tails. Thanks for your help.
Heres the code. Its placing the same user_name in every row(like the previous question was)
<?php
$Var1 =$_POST['Var1'];
require("connection.php");
mysql_query("UPDATE table1 SET actor = '$Var1'");
$result = mysql_query("SELECT * FROM table2 WHERE subject ='$Var1'");
while($row = mysql_fetch_array($result))
{ $un = $row['user_name'];
$a =$row['subject'];
$a_val = $row['subject_val'];
$sql=mysql_query("UPDATE table3 SET user_name='$un', subject='$', subject_val= $a_val WHERE user_name=".$row['user_name']);
}
mysql_close($connection);
?>
This is the last time I answer this kind of question. I'm also adding some optimization.
<?php
var expires = (isset($_POST['var1']) ? $_POST['var1'] : die("no VAR");
require_once("connection.php");
mysql_query("UPDATE table1 SET actor = '$var1'") or die("I cannot run , reason : ".mysql_error());
$result = mysql_query("SELECT * FROM table2 WHERE subject ='$var1'") or die("I cannot run , reason : ".mysql_error());
while($row = mysql_fetch_array($result)) {
extract($row); // field name as variable , content as value , so be sure that the fields have the right name
/*
$user_name = $row['user_name'];
$subject =$row['subject'];
$subject_val = $row['subject_val'];
*/
$sql="UPDATE table3 SET user_name='".$user_name."', subject='".$subject."', subject_val= ".$subject_val." WHERE user_name='".$user_name."'";
mysql_query($sql) or die("I cannot run , reason : ".mysql_error());
}
mysql_close();
?>
Changed the key of third table to user_name - then
$sql="UPDATE table3 SET user_name='".$user_name."', subject='".$subject."', subject_val= ".$subject_val." WHERE user_name='".$un."'";
worked!!
thanks for the help!!

Categories