How to put the id instead of year? - php

Everyone please I really need help, I have a problem on how to put id's under the current_year. For an example in the image that's my data structure sample image. What are the ways to save it's id not the current year I am using $YearNow=Date('Y'); for the current year, I would something that if the current year is 2015 after if I submit it to the database, it will save the id under the current year like 2000
=======================
if the year of my pc is 2016 then 2016 = 2001(syearid). In my school_year table I have (syearid(pri), from_year, to_year). And my studentvotes(studeid(pri)autoincremtn ,candid,idno,syearid(foreign key)). Therefore if the year of my pc is 2016 as you can see that2016(from_year)is under of thesyearid 2001`
here's my code:
<?php
require_once('auth.php');
include('connection/connect.php');
$idnum=$_POST['idnum'];
$stat='voted';
$sqla = "UPDATE student
SET status=?
WHERE idno=?";
$qa = $db->prepare($sqla);
$qa->execute(array($stat,$idnum));
$edittable=$_POST['votes'];
$a=1;
$N = count($edittable);
$YearNow=Date('Y');
for($i=0; $i < $N; $i++)
{
$sql = "UPDATE candidates
SET votes=votes+?
WHERE candid =? ";
//don't know it's correct?
$years = array();
$sq12="select * from studentvotes,school_year where studentvotes.syearid = school_year.syearid AND school_year.from_year = $YearNow";
$result1= mysql_fetch_assoc($sq12);
for($i=0; $row = $result->fetch(); $i++){
$years[$row['syearid']] = $row['from_year'];
}
$q = $db->prepare($sql);
$q->execute(array($a,$edittable[$i]));
//$this part will have something to update
$sqlas =
"INSERT INTO studentvotes(candid,idno,syearid) VALUES (:m,:n,:o)";
$qs = $db->prepare($sqlas);
$qs->execute(array(':m'=>$edittable[$i],':n'=>$idnum,':o'=>$YearNow ));
}
header("location: notification.php?". http_build_query($query));
mysql_close($con);
?>

You are mixing the mysql and mysqli extension together and also using the wrong variable $result1. You can use like that for getting year id.
$sq12="select studentvotes.syearid from studentvotes,school_year where studentvotes.syearid = school_year.syearid AND school_year.from_year = $YearNow";
$result = $db->prepare($sq12);
$result->execute();
$result_final = $result->fetchAll(PDO::FETCH_COLUMN, 0);
$yearid = $result_final[0]; // get year id
Now you can insert it in your Query:
$sqlas = "INSERT INTO studentvotes(candid,idno,syearid) VALUES (:m,:n,:o)";
$qs = $db->prepare($sqlas);
$qs->execute(array(':m'=>$edittable[$i],':n'=>$idnum,':o'=>$yearid));

Related

Approach and Algorithm for checking availability for schedule using PHPmyadmin and SQL

UPDATED
I'm trying to create a basic schedule for all students in their final year to present their final project to 2 supervisors. I have successfully created a schedule with no constraints but now i need to create a schedule based on the supervisors availability.
Here is a detailed description of the problem.
A student is assigned a supervisor and a supervisor will supervise more than one student. The supervisor also teaches classes during the day. Now i need to create a schedule for all of the students to present to their supervisor and one additional supervisor that supervises other students. (for the moment I'm focusing on the supervisors that are assigned to the student and not the second one until i get it working.
I want to compare the supervisors availability for the slots time if they're free then assign them to the slot and then update the availability of that time to false to avoid double booking using a PHP sql query.
so...
What i have done so far:
// get all of the Slots.
$sql = "SELECT Slot_ID FROM slot WHERE StartTime < '18:00:00'";
$result = mysqli_query($con, $sql);
$DayTimeSlots = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$DayTimeSlots [] = $row;
}
}
// Store slots into simple array
function extractSlotId($DayTimeSlots){
return $DayTimeSlots['Slot_ID'];
}
$slots = array_map("extractSlotId",$DayTimeSlots);
// SHOW SLOTS
foreach ($slots as $slotID) {
echo " SlotID: = $slotID <br>";
}
// Get All students
$sql = "SELECT Student_ID FROM student WHERE PartTime =0";
$result = mysqli_query($con, $sql);
$FullTimeStudents = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$FullTimeStudents [] = $row;
}
}
// Store into a simple array
// Extract student id and Supervisor_ID
function extractStudentId($FullTimeStudents){
return $FullTimeStudents['Student_ID'];
}
$students = array_map("extractStudentId",$FullTimeStudents);
// Combine the Slot and Students array
$min = min(count($FullTimeStudents), count($DayTimeSlots));
$result = array_combine(array_slice($students , 0, $min), array_slice($slots, 0, $min));
foreach($result as $key=>$value){ // $Key = Student_ID, $value = Slot_ID
echo " $key : $value ";
// get supervisor ID
$sql = "select Supervisor_ID FROM student where Student_ID = $key";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$SuperID = $row['Supervisor_ID'];
echo "SuperID : $SuperID ";
// get slotID
$sql = "select Date, StartTime FROM Slot where Slot_ID = $value";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Date = $row['Date'];
$StartTime = $row['StartTime'];
echo "Slot Date : $Date Start Time : $StartTime ";
// get Date id
$sql = "select Date_ID FROM dates where Date = '$Date'";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$DateID = $row['Date_ID'];
echo "Date ID : $DateID ";
// Check if the supervisor is available
$sql = "select `$StartTime` FROM supervisor_availability where Date_ID = $DateID AND Supervisor_ID = $SuperID";
$query = mysqli_query($con, $sql);
$row = mysqli_fetch_array($query);
$Available = $row["$StartTime"];
echo "Is the Lecture Available? : $Available ";
$Time = "`$StartTime`";
if($Available == 1){
$sql = "INSERT INTO student_slot (Student_ID, Slot_ID) VALUES ($key, $value)";
$result = mysqli_query($con, $sql);
$sql = "UPDATE `supervisor_availability` SET $Time = '0' WHERE `supervisor_availability`.`Supervisor_ID` = $SuperID AND `supervisor_availability`.`Date_ID` = $DateID" ;
$result = mysqli_query($con, $sql);
} else if ($Available == 0) {
// Not sure what to do here.
// Can i make the Slot it's currently checking go to the end of the
// array for a different student and then check the next slot and come
// back to it.
}
}
I'm using echo for debugging.
The algorithm works fine if the Supervisor is available, it assigns it correctly and then updates the Supervisors availability for that time slot
Just need help with how to handle it if they're not available.
Any help or advice would be appreciated.
Supervisor_Availability Slot Table Student Table Date Table DB_Structure

How can I put the id of the school_year?

My problem is when I save my student_votes like this:
I want that instead of the year will be save I would like to save the id. For an example, if today's year is 2016 then it will be save 2000(because it is the id of the year 2015). The first image is the studentvotes table,
it should be like syearid =2000 if the year is 2015 or if 2016 will be syearid =2001
here's my code:
<?php
require_once('auth.php');
include('connection/connect.php');
$idnum=$_POST['idnum'];
$stat='voted';
$sqla = "UPDATE student
SET status=?
WHERE idno=?";
$qa = $db->prepare($sqla);
$qa->execute(array($stat,$idnum));
$edittable=$_POST['votes'];
$a=1;
$N = count($edittable);
$YearNow=Date('Y');
for($i=0; $i < $N; $i++)
{
$sql = "UPDATE candidates,student,school_year
SET votes=votes+?
WHERE candid =? AND school_year.syearid = candidates.syearid
AND school_year.from_year like $YearNow ";
$q = $db->prepare($sql);
$q->execute(array($a,$edittable[$i]));
//I think because of this code
$sqlas = "INSERT INTO studentvotes(candid,idno,syearid) VALUES (:m,:n,:o)";
$qs = $db->prepare($sqlas);
$qs->execute(array(':m'=>$edittable[$i],':n'=>$idnum,':o'=>$YearNow));
}
header("location: notification.php?". http_build_query($query));
mysql_close($con);
?>
Need Help guys! thanks
I got your question finally:
after:
$qa->execute(array($stat,$idnum));
put something like: (I am not sure what database layer you use, this is mysqli example)
/** #var mysqli $con */
$years = array();
$data = $con->query('SELECT syearid, from_year FROM school_year')->fetch_all(MYSQLI_ASSOC);
foreach($data as $row)
$years[$row['syearid']] = $row['from_year'];
and update your
$qs->execute(array(':m'=>$edittable[$i],':n'=>$idnum,':o'=>$YearNow));
to
$qs->execute(array(':m'=>$edittable[$i],':n'=>$idnum,':o'=>$years[$YearNow]));
you can also query this after your operations:
UPDATE studentvotes AS sv
JOIN school_year AS sy ON sv.syearid = sy.syearid
SET sv.syearid = sy.from_year
and btw, please, put those preparations above the for loop, main purpose of prepare statements is efficiency
$q = $db->prepare("UPDATE candidates,student,school_year
SET votes=votes+?
WHERE candid =? AND school_year.syearid = candidates.syearid AND school_year.from_year like $YearNow");
$qs = $db->prepare("INSERT INTO studentvotes(candid,idno,syearid) VALUES (:m,:n,:o)");
for($i=0; $i < $N; $i++)
{
$q->execute(array($a, $edittable[$i]));
$qs->execute(array(':m'=>$edittable[$i],':n'=>$idnum,':o'=>$YearNow));
}

restrict database row insert by a number?

Based on my codes, i need to restrict the insertion of the data by 3, i mean is like after the insertion of 3 data row, it will be restricted from inserting in data. Is that possible? For more information, is like the borrow inserting 3 times, then it cannot be inserted anymore. Is there anyway to do so? I am still learning php by the way, thank you.
if(isset($_POST['selector']))
$id=$_POST['selector'];
else
$id = '';
$member_id = $_POST['member_id'];
$due_date = $_POST['due_date'];
$isbn = $_POST['due_date'];
if ($id == '' ){
//header("location: borrow.php");
if(isset($_POST['isbn'])){
$isbn = $_POST['isbn'];
$query = mysql_query("select book_id from book WHERE isbn = '$isbn'")or die(mysql_error());
$count = mysql_num_rows($query);
if($count > 0){
$row = mysql_fetch_array($query);
$bookid = $row['book_id'];
$date = date('Y-m-d');
}
mysql_query("insert into borrow (member_id,book_id,date_borrow,due_date) values ('$member_id','$bookid','$date','$due_date')")or die(mysql_error());
}
else{
header("location: borrow.php");
}
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
}else{
mysql_query("insert into borrow (member_id,date_borrow,due_date) values ('$member_id',NOW(),'$due_date')")or die(mysql_error());
$query = mysql_query("select * from borrow order by borrow_id DESC")or die(mysql_error());
$row = mysql_fetch_array($query);
$borrow_id = $row['borrow_id'];
$N = count($id);
for($i=0; $i < $N; $i++)
{
mysql_query("insert borrowdetails (book_id,borrow_id,borrow_status)
values('$id[$i]','$borrow_id','pending')")or die(mysql_error());
}
header("location: borrow.php");
}
You just have to count number of user row before to make a new insert :
$query = mysql_query("SELECT COUNT(*) AS count FROM borrow WHERE member_id = '".$member_id."'");
$row = mysql_fetch_assoc($query);
if ( $row['count'] >= 3 )
echo('Max insert');
Also, check this : Why shouldn't I use mysql_* functions in PHP?
I'm not sure I understand you correctly.
You can restrict the number of rows returned by SELECT query using the LIMIT clause.
Make sure you either put an ORDER BY clause in there or determine that you don't care 'which' 3 rows will get inserted.
See here:
http://dev.mysql.com/doc/refman/5.0/en/select.html

Predefined counter not updating in select statement

Here's a simplified code similar to what I'm using. In this one, I'm pulling Names from ID's.
$counter = 0;
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
$maxusers = 10;
while($counter<$maxusers) {
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
What I get is the same name, the counter in the select statement stays at 0.
I had to put the definition of the $select statement and the $result inside the loop, it redefines everything every time we enter the while loop, looks like the code below. That doesn't seem practical and optimal to me. What are the best work-around for situations like these? I'm not really familiar with variable scopes in PHP, I haven't found any good documentation on that matter when it comes to sql functions.
$counter = 0;
$maxusers = 10;
while($counter<$maxusers) {
$select = "SELECT nID,nName WHERE nID = $counter";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
$counter++
}
Here's the code that I've actually written.
$selectFirst = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter AND nDateTime BETWEEN $today AND $tomorrow";
$selectLast = "SELECT TOP 1 nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID = $usercounter DateTime BETWEEN $today AND $tomorrow DESC";
$resultFirst = sqlsrv_query($bscon, $selectFirst);
$resultLast = sqlsrv_query($bscon, $selectLast);
$selectnumberofUsers = "SELECT TOP 1 nUserIdn FROM TB_USER ORDER by nUserIdn DESC";
$usersmaxq = sqlsrv_query($bscon, $selectnumberofUsers);
$usersmax = sqlsrv_fetch_object($usersmaxq)->nUserIdn;
while($usercounter<$usersmax){
$usercounter = $usercounter + 1;
while($rowfirst = sqlsrv_fetch_array($resultFirst)) {
$intime = $rowfirst['nDateTime'];
}
echo $intime." ".$usercounter."<br />";
}
Your issue doesn't have to do with variable scope. The $select variable is set once as string with the current value of $counter. Your second example works because this value is reset every time.
In your second example however, you're creating a sql statement that gets 1 row (assuming nID is unique), then looping through your result retrieve that one row. You're doing 10 sql calls, but you only need one if you modify your query like so:
$minusers = 0;
$maxusers = 10;
$select = "SELECT nID,nName WHERE nID >= $minusers AND nID < $maxusers ORDER BY nID";
$result = sqlsrv_query($connection, $select);
while($row = sqlsrv_fetch_array($result)) {
echo $row['nName'];
}
For your actual code, you should be able to get one record per nUserId by using GROUP BY. Try this:
$selectFirst = "SELECT nDateTime,nUserID FROM TB_EVENT_LOG WHERE nUserID >= $usersmin AND nUserID <= $usersmax AND nDateTime BETWEEN $today AND $tomorrow GROUP BY nUserID";

Php For loop not working properly inside another for loop?

Following is my code. The first part works perfectly, but the second loop is not producing any results. What this is doing is that it looks for the timetable, then takes out the classes in that, copies all the that and makes a new timtable with same data but a different name.
The other for loop is to add students into the classes of the time table. Ca some one be kind enough and help me out in this as I have been hitting my head on the wall for it now for 5 days.
Thank you in advance. The code:
<?php
$Q = "INSERT INTO time_table(name, term, year) VALUES
('".$name."', '".$term."', '".$year."')";
$res = $db->query($Q);
//for generating the max table id
$sql2 = "select MAX(table_id) as table_id
from time_table
";
$res2 = $db->query($sql2);
$count2 = $res2->num_rows;
$row2 = $res2->fetch_assoc();
$table_id = $row2['table_id'];
$Q = "SELECT class_id as tcid, day as d, teacher_id as tei, location as l
FROM class_time_table
WHERE term='".$copy."'";
$res = $db->query($Q);
$num_results = $res->num_rows;
for ($i = 0; $i <$num_results; $i++) {
$row = $res->fetch_assoc();
$Q4 = "SELECT * FROM students_class WHERE class_id = '".$row['tcid']."' and term = '".$copy."'";
$res4 = $db->query($Q4);
$row2 = $res4->fetch_assoc();
//for generating the max table id
$class_sysq = "select MAX(class_sys_id) as class_sys_id
from students_class
";
$class_sysr = $db->query($class_sysq);
$count_class_sys = $class_sysr->num_rows;
$class_row = $class_sysr->fetch_assoc();
$class_sys_idf = $class_row['class_sys_id']+1;
$Q5 = "INSERT INTO students_class (class_sys_id, teachers_id, location, max_students, class_term_fee, class_name, class_sub_name, term, year) VALUES ('".$class_sys_idf."', '".$row2['teachers_id']."', '".$row2['location']."', '".$row2['max_students']."', '".$row2['class_term_fee']."', '".$row2['class_name']."', '".$row2['class_sub_name']."', '".$term."', '".$year."')";
$res5 = $db->query($Q5);
//for generating the max table id
$max_c_id = "select MAX(class_id) as ci
from students_class
";
$r_mci = $db->query($max_c_id);
$count_class_sys = $r_mci->num_rows;
$mci_row = $r_mci->fetch_assoc();
$max_c_idf = $mci_row['ci'];
$query2 = "INSERT INTO class_time_table(class_id, teacher_id, table_id, location, day, term, year) VALUES
('".$max_c_idf."', '".$row['tei']."', '".$table_id."', '".$row['l']."', '".$row['d']."', '".$term."', '".$year."')";
$result2 = $db->query($query2);
$student_q = "SELECT students.first_name as fn, students.last_name as ln, students.email as e, students.mobile_phone as mp, students.home_phone as hp, students.gender as g, students.dob as dob, students.term_fee as tf, students.join_date as jd, students.date_added as da, student_attending_class.class_id as ci FROM students, student_attending_class, class_time_table where students.student_sys_id = student_attending_class.student_id and student_attending_class.class_id = class_time_table.class_id and class_time_table.class_id = '".$row['tcid']."'";
$student_res = $db->query($student_q);
$student_num_results = $student_res->num_rows;
for ($i = 0; $i < $student_num_results; $i++) {
$theRow = $student_res->fetch_assoc();
//for generating the new system id
$sql3 = "select MAX(student_sys_id) as ssi
from students";
$res3 = $db->query($sql3);
$count3 = $res3->num_rows;
$row8 = $res3->fetch_assoc();
$student_system_num = $row8['ssi']+1;
$query10 = "INSERT INTO students(student_sys_id, first_name, last_name, email, mobile_phone, home_phone, gender, dob, fee_due, registration_fee, term_fee, fee_paid, join_date, date_added) VALUES
('".$student_system_num."', '".$theRow['fn']."', '".$theRow['ln']."', '".$theRow['e']."', '".$theRow['mp']."', '".$theRow['hp']."', '".$theRow['g']."', '".$theRow['dob']."', '".$theRow['tf']."', 0, '".$theRow['tf']."', 0, '".$theRow['jd']."', '".$theRow['da']."')";
$result10 = $db->query($query10);
$query11 = "INSERT INTO student_attending_class(class_id, student_id, waiting_list) VALUES ('".$max_c_idf."', '".$student_system_num."', '0')";
$result11 = $db->query($query11);
}
}
?>
Don't use $i in the second loop but $n for instance.
i m not sure but you used same variable $i in both loop so maybe because of that your second loop not working. try another variable $j in second loop.
The code is poorly formatted, so it's easy to miss that you're using the same variable for both loops, hence when the second loop begins, the first loses track of its progress. Use foreach(), or a different variable name for the second loop.
You are probably getting a timeout due to having nested loops which both use the same variable, $i and it just keeps incrementing.
Try changing the second loop like so:
for($j = 0; $j < $student_num_results; $j++){
...
}

Categories