How can I put the id of the school_year? - php

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));
}

Related

Store multiple row table into array to allow for user updates

I have struggled with this concept for a while and am hoping someone can help, please. I can query database records if all values are stored in one row. The challenge I have is when the quantity values are stored on multiple rows but with a common key (e.g. order_id). I want to store into an array and then assign each value to an on-screen variable to allow user updates so that I can update the table again.
For example, if the table looks as follows:
id line part qty
-- ---- ---- ---
1 1 63 2
1 2 104 3
1 3 54 2
1 4 50 1
I have not had success with the following where I establish the number of rows and then try to build a foreach loop to capture the data:
$sql = 'SELECT *, COUNT(*) as $count FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
for ($x = 0; $x <= $count; $x++ {
$var($x) = $data['qty'];
}
If I can properly separate the values into an array and then reference them somehow, then I could do the following and get them displayed and easily update back to the database:
$var_1 = $data['63']; // part_id = 63
$var_2 = $data['104']; // part_id = 104
$var_3 = $data['54']; // part_id = 54
$var_4 = $data['50']; // part_id = 50
Change this:
$sql = 'SELECT *, COUNT(*) as $count FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$data = $q->fetch(PDO::FETCH_ASSOC);
for ($x = 0; $x <= $count; $x++ {
$var($x) = $data['qty'];
}
To something that makes sense like this
$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
echo $row['qty'];
};
UPDATE
$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$array = [];
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
$array['line_'.$row['line']] = $row;
};
UPDATE
The additional code that answers what I was looking for is as follows. Your answer was key to my understanding it all:
$sql = 'SELECT * FROM Order_Items where order_id = ?';
$q = $pdo->prepare($sql);
$q->execute(array($id));
$array = [];
while(false !== ($row = $q->fetch(PDO::FETCH_ASSOC))){
$qty['line_'.$row['line']] = $row['qty'];
};
$var_54 = $qty['line_54'];
$var_63 = $qty['line_63'];

Avoiding code repetition for MySQL queries (multiple while)

I have the following code:
<?php
include_once "connect.php";
$question_01 = mysqli_real_escape_string($con, $_POST['question_01']);
// $question_02 - $question_09 go here...
$question_10 = mysqli_real_escape_string($con, $_POST['question_10']);
$i = 0;
$array_sum=[];
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteners WHERE question_no = 1 AND answer_variant = '$question_01'";
$result = mysqli_query($con, $sql);
$final_array_1 = array();
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
$final_array_1 = $row;
$array_sum = array_map(function () {
return array_sum(func_get_args());
}, $array_sum, $final_array_1);
}
}
print_r($final_array_1);
As you can see, I need to repeat the code for each $question_##. Is there a smarter way of doing this other than repeating the code? I'm not only concerned about turning everything into a code spaghetti but also about the efficiency of the operations as in loading times.
Let me know if you need clarification.
Update: Basically it should increase the value of "question_no" in the query until it reaches 10 and pick the corresponding $_POST value for each question.
There are two ways, variable variables or arrays. I'd suggest arrays as they are less prone to throwing errors everywhere.
<?php
include_once "connect.php";
$questions = array();
$questions[1] = mysqli_real_escape_string($con, $_POST['question_01']);
// $question_02 - $question_09 go here...
$questions[10] = mysqli_real_escape_string($con, $_POST['question_10']);
$i = 0;
$array_sum=[];
while ($i < 10){
$i++;
$sql = "SELECT * FROM parteners WHERE question_no = $i AND answer_variant = '".$questions[$i]."'";
$result = mysqli_query($con, $sql);
$final_array_1 = array();
while ($row = mysqli_fetch_array($result, MYSQLI_NUM))
{
$final_array_1 = $row;
$array_sum = array_map(function () {
return array_sum(func_get_args());
}, $array_sum, $final_array_1);
}
}
print_r($final_array_1);
EDIT: The reason I used an array instead of just straight up using the POST variable in the while loop is so there is room before you run anything for validation (ensuring your question array contains 10 posted values etc)
I would build one SQL-Statement which contains all questions and anwsers and do the rest with programming logic. SQL-Queries in a loop are a bad idea, because you have to do a lot of overhead for getting a task done, which the database server can do better. Also you should use prepared statements for performance and security.
$query = "SELECT * FROM parteners WHERE (question_no = 1 AND answer_variant = ?) OR (question_no = 2 AND answer_variant = ?) OR (question_no = 3 AND answer_variant = ?) OR (question_no = 4 AND answer_variant = ?) OR (question_no = 5 AND answer_variant = ?) OR (question_no = 6 AND answer_variant = ?) OR (question_no = 7 AND answer_variant = ?) OR (question_no = 8 AND answer_variant = ?) OR (question_no = 9 AND answer_variant = ?) OR (question_no = 10 AND answer_variant = ?)"
$stmt = myqli_prepare($query);
mysqli_stmt_bind_param($stmt, 'ssssssssss', $question_01, $question_02, $question_03,.....);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
First, to make your code modern and efficient, you should be using PHP
Data Objects, or PDO for short. You will have access to prepared
statements, which are made exactly for this: you build a query
"template" and execute with different data, very efficiently and secure.
The loop is the proper way to do it. Also, your $questions array is a
bit unecessary since you can retrieve data from $_POST right inside
your loop. But if you want to use it, there is no need to "escape" the
string for the database, since it's handled by PDO. So you can build
your array in a easier way:
$questions = [
$_POST['question_01'],
$_POST['question_02'],
$_POST['question_03'],
# ...
$_POST['question_10'],
];
Your loop with PDO:
$dbh = ... # create your database handle, connect to it
$st = $dbh->prepare("
SELECT * FROM parteners
WHERE question_no = ? AND answer_variant = ?;
");
foreach (range(1, 10) as $i) {
$result = $st->execute([ $i, $questions[$i-1] ]);
# or, to build directly
$result = $st->execute([
$i, $_POST[ sprintf("question_%02d", $i) ]
]);
$final_array[] = $result->fetchAll(PDO::FETCH_NUM);
}
print_r($final_array);

How to put the id instead of year?

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));

Fetching data from relational database in codeigniter

I have got 2 tables; table1 and table2. Both of them are related to eachother with a common groupid I am able to query the second table successfully using the following code:
$query = $this->db->query("SELECT * FROM `table2` WHERE `memberid`='$id'");
$data['relation'] = $query->result_array();
Now using groupid result I want to query the first table i.e. table1
I have tried the following methods, without any success:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
}
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 1 ideally should be 2
The above code only returns the last row of the table1 however I am looking for all the results.
When I run the above code inside the "for" loop, it shows me a count of 33:
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'] = $query1->result_array();
$fine = array_merge($data, $data1);
print_r(count($fine)); // the count result is 33 ideally should be 2
}
I know how to achieve this in core php however not too sure how to do it in CI. I am new to CI, any help will be greatly appreciated.
Thanks,
Utpal
$ok = array();
for($ii = 0 ; $ii < count($data['relation']) ; $ii++){
$id = $data['relation'][$ii]['groupid'];
print_r ($id);
echo "<br>";
$query1 = $this->db->query("SELECT * FROM `group` WHERE `id`='$id'");
$data1['group'][$ii]= $query1->result_array();
}
//print_r($data1['group']);
$fine = array_merge($data, $data1);
print_r($fine);
You need to create a array ($data1) outside this for loop and define $query->result_array(); inside forloop as shown above

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