limit input to a certain number for a sql table - php

I have a SQL database within which I have a series of different tables. Basically, I am creating an exam day and adding exams to it.
Example:
(examtable) Exam 1
(exams) Physics, Biology, Chemistry, P.E
These both are linked.
Now currently how this works is when I create an exam in the examtable, I can add an unlimited amount of exams to it, but in real life that obviously does not make sense.
So what I am trying to do is have some sort of input when creating the exam that can limit the amount of exams that can be entered to it.
So for example if I create Exam 2 and limit input to 3, then only 3 exams can be added to it.
I have tried to find something online but cannot seem to get anywhere, could someone please help?
Thanks.

Add another column to your table called mostExams
when creating a new exam just,
$db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$stmnt = $db->query("SELECT `mostExams` FROM `exams` WHERE `classId`='" . $thisClassId . "'");
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$mostExams = $row['mostExams'] ;
}
//php to only allow $mostExams number of exams.
$stmnt = $db->query("SELECT `id` FROM `exams` WHERE `classId`='" . $thisClassId . "'");
if ($stmnt->rowCount() >= $mostExams){
echo 'You cannot add any more exams. Change mostExams in the SQL database to allow more.';
}else{
//HTML form to add an exam
}
You may want to add some code to check and see if you already have some exams and subtract that from most exams. You just need to think outside the box a little bit!

I don't understand very well your question but here it goes:
You can use sql in php to count the number of exams from examstable:
'SELECT COUNT(*) FROM examstable;'
And then in PHP :
'if ($no_exams > 3 ) { echo "No more exams can be added."}
else insert into the database the exam.'

Related

Many to many relationships - Moving data from many tables to a single table

I have a table with users and one with labels
A label can have many users and a user can have many labels, so a Many to Many relationship
A joining table is needed, that's why I have label_user
Below you can see pictures of what they contain with example data:
Users:
https://i.stack.imgur.com/E5E6O.png
Labels:
https://i.stack.imgur.com/1NFjq.png
label_user:
https://i.stack.imgur.com/tW2Uo.png
Let's say I have 5000 users and I can sort them by gender. Let's say 2800 of them are males, how can I assign them all to a label?
Here's some things I tried:
public function add_users_to_label($label_id, $condition, $value)
{
$db = new Database();
$conn = $db->db_connect();
$label_id = escape_string($conn, $label_id);
$query = $conn->query("INSERT INTO `label_user`(`label_id`, `user_id`) SELECT :label_id, psid FROM `iris_messenger_users` WHERE $condition = $value");
$query->bind_param("iss", $label_id, $condition, $value);
if ($query->execute()) {
return true;
}
else {
return "Error inserting data: " . $conn->error . "\n";
}
}
On the user side I have a simple form with select that let's you select a label and then this code:
if(isset($_POST['label-select'])) {
if ($_GET['show_only_gender'] == 'male') {
$condition = 'gender';
$user->add_users_to_label($_POST['label-select'], $condition, $_GET['show_only_gender']);
}
}
Basically, I want to get all users that are male and assign them to a label and put that into label_user with respectively the label_id and the user_id(psid)
Even if this worked I'd still have to do it 2699 times more. What can I do here to optimize and make it to run with 1 query if possible?
I don't think using foreach and running it as much times as there are users is the best option, is it?
Is there any better approach I can take to make this possible?
Although what you are describing does not make sense to have a "label" associated with a person for this specific component, the gender is already on the user table you should be able to get all male based on
select * from user where gender = 'male'
no need to JOIN to a label table on this field. Similarly if you were trying to find people based on a name starting with something... you would not create a label for the name either. Query directly from the table that has that specific component association.
Now, to answer your question, how to insert into the label table for each instance in bulk, you could do something like... I am doing this based on some label ID = 123 as just an example in your labels table that represents gender.
I am doing a LEFT-JOIN in the select so we dont try to add for any user IDs that are already on file do not try to get re-added.
insert into label_user
( label_id,
user_id )
select
123 as label_id,
U.id as user_id
from
users U
left join label_user LU
on U.id = LU.user_id
AND LU.label_id = 123
where
U.gender = 'male'
AND LU.user_id IS NULL
You obviously need to adjust for php.

How to update database values for a whole day

I am building a web application, for travelling. I have managed to get users to be able to insert how much they have spent on each category (i.e. travel, accomodation, food, etc) into the database once from a form. However, I want them to be able to contiously add to the total value of each category for just that day using the same form, and then everyday have a new total for each category as well.
I'm not quite sure how I would do that at the moment.
Here is my code so far for inserting the values into the database from my form (which works):
if(isset($_POST['addinfo_button'])){
$Food = $_POST['food'];
$Transport = $_POST['transport'];
$Accom = $_POST['accomodation'];
$Entertain = $_POST['entertainment'];
$Souvenir = $_POST['souvenirs'];
$Misc = $_POST['miscellaneous'];
$Date = date("Y-m-d");
$Trip_id;
$sql = "SELECT * FROM trips WHERE id =$user_id_session AND date1 <= '$Date' && date2 >= '$Date'";
$records = mysql_query($sql);
while($trip=mysql_fetch_assoc($records)){
$Trip_id = $trip['trip_id'];
}
$foreignkey = $user_info['id'];
$sql = $con->query("INSERT INTO todays_spend (food, transport, accomodation, entertainment, souvenirs, miscellaneous,date, trip_id, id)Values('{$Food}', '{$Transport}', '{$Accom}', '{$Entertain}','{$Souvenir}', '{$Misc}','{$Date}','{$Trip_id}','{$foreignkey}')");
header('Location: budgetbuddy.php');
}
Would I have to do something similar to this? or modify this one slightly?
Could not write code for you. But I can give you an Idea how you can achieve this having only one form.
Create a table with your needs.I mean your entertainement, food, etc along with their name and Id. If you can make user enter their name or anything that users can uniquely identified. Then things go easier. When a user enter their how much they spent insert into table along with their name or identifier. Next time same user enter details simply find if already user has anything updated on same day , if user added anything before simply update the table by adding previously existing values to new values. Update them. Now you easily even find how much each user spent on particuler catogery.Hope it helps. Thank you.

Delete one column from table, Update another with PHP MYSQL

I have two tables. One table is the matches table (e2wedstrijden) and another table is my scoring table with the points earned etc. (e2teams).
Now I have that I can delete a match from the e2wedstrijden table. And this is working fine.
But I want that if I delete a match from that table. It also add or decrease points to the table ("e2teams"). I tried to compare the tables but this is not working.
So I want for example:
If($row['thuisscore'] == $row['uitscore']) what are to row names in my e2wedstrijden table. So if these two are the same (like 0-0 or 1-1 or something) Than it needs to decrease 1 point from the table e2teams. But only by the teams that are the same as the rows "Thuisteam" and "Uitteam" in my e2wedstrijden table. So the Row Thuisteam (in "e2wedstrijden") Needs to find the same result in ("e2teams") row Team. And this needs to be done the same with the Row Uitteam (in "e2wedstrijden") Needs to find the same result in ("e2teams")
Thuisteam and Uitteam = Dutch for hometeam and awayteam. I think my fault is that the system can't link the 'Thuisteam' from e2wedstrijden to the Team in e2teams but don't know how to solve it
This is my deletematches.php, It deletes the match but doesn't decrease or adds points:
<?php
if(!isset($_COOKIE['E2ingelogd'])) {
header("location:../../index.php");
}
include "../../connect.php";
$dbhandle = mysql_connect($hostname, $username, $password) or die("Could not connect to database");
$selected = mysql_select_db("login", $dbhandle);
$result = mysql_query("SELECT * FROM e2wedstrijden WHERE ID = ".$_GET['del']."");
while($row = mysql_fetch_assoc($result)){
if( $row['thuisscore'] == $row['uitscore']){
echo $row['thuisscore'];
mysql_query("UPDATE e2teams SET Punten = Punten-1 WHERE Team ='".$row['Thuisteam']."'");
mysql_query("UPDATE e2teams SET Gespeeld = Gespeeld-1 WHERE Team = ('".$row['Thuisteam']."'");
mysql_query("UPDATE e2teams SET Verloren = Gelijk-1 WHERE Team ='".$row['Uitteam']."'");
echo "Team is deleted";
}else{
echo 'Update Error!';
}
}
$table_1_delete = mysql_query("DELETE FROM e2wedstrijden WHERE ID = ".$_GET['del']."");
?>
This is my e2teams table:
And this is my E2wedstrijden table:
So i need something like:
UPDATE e2teams SET Punten = Punten-1 WHERE Team = Look in table ("e2wedstrijden) deleted Thuisteam and deleted Uitteam
Hope you can help
You've placed an extra parentheses in the 2nd query for "gespeeld" right after the equal sign:
mysql_query("UPDATE e2teams SET Gespeeld = Gespeeld-1
WHERE Team = ('".$row['Thuisteam']."'");
Is this what isn't updating?
Without being 100% sure on how your data model works, it might make sense at refactoring what you have. Something that might be useful would be to create a view of the summary table and just update the data from the child/master table.... aggregating in the view layer. Views in mysql can be seen here.
If you are stuck with the data model you have (legacy application, etc.) you can possibly look at triggers if you have to modify data in two tables you might want to consider stored procedures or triggers, discussed here and here.
The third thing that comes to mind, is around correlated sub-queries and how you could reference the another table in a sort of update-from. However, you're ID's aren't surrogate keys in this situation.
Also, have a look at sql injection; I haven't looked at PHP in a while but those sql statements kind of look like they are created with sting composition
Good luck,

how to fetch data from database dynamically for multiple user in PHP and MySQL

This question is bit complex atleast for me. Well, I am working on a project and need some bit more help..
Actually i have a module , where when 1 user login he get limited data from 1 table and he update its records. That is done !
second thing, the issue : i have 5 user who will login and will work on data.
but no user should get same data, like we have 1000 records.
Then when 1st user login: he get 10 records from 1 - 10.
2nd user login : he get next 10 ; 11- 20.
same so on..
and when next day they login ; they get records from 51.
because 5 user last day worked on first 50 data records.
My issue is how to achieve that 2 goals ?
do i need a framework for this ?
or it can be done using simple php n sql ?
any support will be helpful for me. :)
Ok. This is just a raw answer to give you a better idea. This is how you will insert the login .
Consider having a table containing following fields,
Table Name: Temp_Table
user, assigned_rows_last_no, date_assigned
<?php
$con=mysqli_connect("example.com","hiren","abc123","my_db");
// These things can be included into a single file say config.php and including in every file so that you dont need to specify connection string everytime.
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//This query required to be included into the file, which is exactly after login.php
$sql = mysqli_query($con,"SELECT assigned_rows_last_no FROM Temp_Table ORDER BY assigned_rows_last_no DESC LIMIT 1");
// This is because I want the last row number assigned to the user.
IF ($sql == 0) // Check whether the return answer is NULL or not.
{
// If the result is empty than add new entry of the user with defined row number.
// Suppose that current username can be retrieved from SESSION and stored into a variable.
$insertquery = mysqli_query($con, "INSERT INTO Temp_Table Values ('" . $username . $"', 10, CURDATE()");
mysqli_close($con);
}
else
{
// Select the last entry of row and add 10 to it. Ex. User2 has been assigned to 11-20, table contains 20 in the row of user2, now user3 comes, this query will select the row_no, add 10 and insert again into the table (i.e. value 30 which means 21-30.)
settype($sql, "int");
$sql = $sql + 10;
$insertquery = mysqli_query($con, "INSERT INTO Temp_Table Values ('" . $username . $"', '" . $sql . "', CURDATE()");
mysqli_close($con);
}
mysqli_close($con);
?>
The field Date will help you to recognize the entries of today, so that you can set your logic for "There should be no duplicate entries for the same user on same day"
Now, Make you own page, which check the above mentioned things, and assign the rows to the users.
Note: This code will only be able to clear out the logic for you, I am not sure whether it will work in your code without any changes.
You don't need a extra framework. Simply done with php 'n' sql!
Why you don't save the last edited lines (linenumbers) in a extra SQL-Table? Maybe with the username / userid.

Counting from field in table then updating to a different field in a different table

Quite a complex question:
At the moment I have a table called "timetable". This is updated when someone books a slot (this is for a radio booking system). What I would like is a PHP file that I can have run every 15 minutes as a cron job. In PHP script what I'd like it to do is count how many slots a radio presenter has booked via the "username" field in the "timetable" table. Then I would like it to update a field in another table called "users" in a field called "slot_count" with the amount of slots which were found in the "timetable" table under their "username".
At the moment I have a script which pulls all the booked slots with their presenter "username"'s into a table:
<?php
include("../config.php");
include("functions.php");
if($logged["level"] == "HDJ" OR $logged["level"] == "SA") {
echo "<table width=\"580px\" class=\"board\" border=\>";
$order = "SELECT * FROM timetable WHERE username <> 'No DJ'";
$result = mysql_query($order);
// Error checking
if (!$result) {
// output error, take other action
}
else {
while ($row=mysql_fetch_array($result)){
// Append all results onto an array
$rowset[] = $row;
}
}
foreach ($rowset as $row) {
echo "<tr><td>" . htmlspecialchars($row['username']) . "</td></tr>";
}
} else {
echo ("<div class=\"caution\">Access is denied.</div>");
}
?>
Any ideas?
Storing this redundant data in your users table is unnecessary. As long as the tables are indexed appropriately the join and count are trivial -
SELECT users.*, COUNT(timetable.username) AS num_slots
FROM users
LEFT JOIN timetable
ON users.username = timetable.username
GROUP BY users.id
Can't it be done using one sql statement doing both COUNT() and UPDATE:
UPDATE users
SET slot_count = (SELECT COUNT(*) FROM timetable WHERE timetable.username = users.username)
Assumption: the username field contains the same value for the same radio presenter in both users and timetable tables. Otherwise they wouldn't match. You should be able to run this query directly against MySQL from the cron job (instead of doing the PHP script).

Categories