I'm currently making a graduation website for my school where grads are supposed to submit a comment as well as submit votes for a poll.
The database has 4 tables, one for the student information, one for questions, one for comments which has a foreign key referencing snum from students and one for the poll(called survey) which has 2 foreign keys, one referencing snum again and one referencing the question id.
This is the code my seniors left for me. What it's supposed to do is create blank rows in the comments and survey tables to be updated later. However what it actually does is send everything in the comment table twice (so if there were 300 students, I would end up with 600 rows in the comments table and 0 in the survey table)
I'm still quite new to MySQL and PHP and only learned it about a month ago. If anyone can help or suggest a better way of approaching this, it would be much appreciated.
$sql_query = "SELECT snum FROM students;";
$result = mysqli_query($link,$sql_query);
while ($list = mysqli_fetch_array($result)) {
$snum[] = $list['snum'];
}
$sql_query = "SELECT qid FROM questions WHERE want = 1;";
$result = mysqli_query($link,$sql_query);
while ($question_list = mysqli_fetch_array($result)) {
$qid[] = $list['qid'];
}
for ($i = 0; $i < count($snum); $i++)
{
$sql_query = "INSERT INTO comments (snum, comment) VALUES ('{$snum[$i]}' , NULL);";
$result = mysqli_query($link,$sql_query);
for ($a = 0; $a < count($qid); $a++) {
$sql_query = "INSERT INTO survey (snum, qid, male, female) VALUES ('{$snum[$i]}', {$qid[$a]}, NULL, NULL);";
$result = mysqli_query($link,$sql_query);
}
}
UPDATE 1:I think I found what the problem is. When I try to output $qid[$a], I get a null value. In the table, qid is a smallint unsigned, not null, auto_increment and is the primary key.
Try this code
<?php
$sql_query = "SELECT snum FROM students";
$result = mysql_query($link,$sql_query);
while ($list = mysql_fetch_array($result)) {
$snum[] = $list['snum'];
}
$sql_query = "SELECT qid FROM questions WHERE want = '1' ";
$result = mysql_query($link,$sql_query);
while ($question_list = mysql_fetch_array($result)) {
$qid[] = $list['qid'];
}
for ($i = 0; $i < count($snum); $i++){
$sql_query = "INSERT INTO comments (snum, comment) VALUES ('".$snum[$i]."' , '');";
$result = mysql_query($link,$sql_query);
for ($a = 0; $a < count($qid); $a++) {
$sql_query = "INSERT INTO survey (snum, qid, male, female) VALUES ('".$snum[$i]."','".$qid[$a]."', '', '');";
$result = mysql_query($link,$sql_query);
}
}
?>
This was solved by using mysqli_free_result($result) between the two select queries
$sql_query = "SELECT snum FROM students;";
$result = mysqli_query($link,$sql_query);
while ($list = mysqli_fetch_assoc($result))
{
$snum[] = $list['snum'];
}
mysqli_free_result($result);
$sql_query = "SELECT qid FROM questions WHERE want = 1;";
$result = mysqli_query($link,$sql_query);
while ($question_list = mysqli_fetch_assoc($result))
{
$qid[] = $list['qid'];
}
Related
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
I have an array like below:
$array = ['184717453','184717454','184717455','184717456','184717457'];
and I've a table and there is a mobileno coulmn. Some mobileno field contains 0 value. I want to update that field which contain 0 value using the above array.
Using first array element will update the first mobileno field which contain 0 value, 2nd array element will update the 2nd mobileno field which contain 0 value and so on...
Till now i've tried:
$array = ['184717453','184717454','184717455','184717456','184717457'];
$clid = count($array);
$sql = mysqli_query($conn,"SELECT * FROM `tbl_subscription` WHERE mobileno = 0");
$rowcount=mysqli_num_rows($sql);
for ($i = 0; $i < $clid; $i++) {
for($j = 0; $j<$rowcount; $j++) {
$sql = "UPDATE `tbl_subscription` SET mobileno='$array[$i]' WHERE mobileno = 0";
$res = mysqli_query($conn, $sql);
}
}
It's not working as i wanted. Currently it's update all the field which contain 0 value using only first number 184717453. How can i do this please help me.
i have designed a solution for you, here i have assumed a field named id which your table tbl_subscription may have this field and it will work for sure, try the code below
<?php
$array = ['184717453','184717454','184717455','184717456','184717457'];
$clid = count($array);
$sql = mysqli_query($conn,"SELECT * FROM `tbl_subscription` WHERE mobileno = 0");
$rowcount=mysqli_num_rows($sql);
for ($i = 0; $i < $clid; $i++) {
$sql = mysqli_query($conn,"SELECT `id` from `tbl_subscription` WHERE mobileno = 0");
if(mysqli_num_rows($sql)>0)
{
$arr=mysql_fetch_array($sql)
$sql = "UPDATE `tbl_subscription` SET mobileno='$array[$i]' WHERE id = ".$arr['id'];
$res = mysqli_query($conn, $sql);
}
}
?>
See the MySQL manual for UPDATE: http://dev.mysql.com/doc/refman/5.0/en/update.html
The last argument LIMIT should do what you want to archieve.
#Phylogenesis I just trying below code in my local machine using LIMIT as per René Hoffmann suggestion. But it takes too much time to execute.
$array = ['184717453','184717454','184717455','184717456','184717457'];
$clid = count($array);
for ($i = 0; $i < $clid; $i++) {
$sql = "UPDATE `tbl_subscription` SET mobileno='$array[$i]' WHERE mobileno = 0 LIMIT 1";
$res = mysqli_query($conn, $sql);
}
$array = ['184717453','184717454','184717455','184717456','184717457'];
$clid = count($array);
$sql = mysqli_query($conn,"SELECT * FROM `tbl_subscription` WHERE mobileno = 0");
$rowcount=mysqli_num_rows($sql);
$i=0;
while($fetch = mysqli_fetch_array($sql))
{
$sql = "UPDATE `tbl_subscription` SET mobileno='$array[$i]' WHERE mobileno = 0 and id = '".$fetch['id']."' ";
$res = mysqli_query($conn, $sql);
$i++;
}
You have also check the id in your query to update only specific row.
I have the following table:
CREATE TABLE list(
country TINYINT UNSIGNED NOT NULL,
name VARCHAR(10) CHARACTER SET latin1 NOT NULL,
name_index INT UNSIGNED NOT NULL,
UNIQUE KEY(country, name), PRIMARY KEY(country, name_index)) ENGINE = INNODB
I want to:
Given: ($country, $name, $new_index)
Check if a row with country = $country && name = $name exists.
If the row exists, get the index $index = name_index.
If the row doesn't exist, add it and then get the index.
I can do the following using many queries, but I am looking for an efficient way to do it, using only one query. Is this possible?
It's not possible with only one query.
You CAN do this:
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$numrows = mysql_num_rows($query);
if($numrows == 1) {
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
$sql = "INSERT INTO (your table) (country, name)
VALUES('$country','$name')";
$query = mysql_query($sql);
$check = mysql_num_rows($query);
if($check > 0) {
$sql = "SELECT name_index FROM (your table) WHERE country = '$country' AND
name = '$name' LIMIT 1";
$query = mysql_query($sql);
$row = mysql_fetch_row($query);
$index = $row[0];
} else {
echo "Error occured while trying to insert new row";
}
}
Hope this helps :).
I want to update the database of the sort order column to increase its value by one if the the new value inserted into the database clashes with the value that is already in the database. May I know how should I go about doing it? Please help! Thanks!
Below is my code (I am not sure whether am I on the right track):
$result = mysql_query("SELECT sortorder FROM information ORDER BY id ASC;");
if($result >= 1 ){
$i=1;
while ($initialorder = mysql_fetch_assoc($result))
{
$initialorder = $initialorder["sortorder"];
if ($sortorder == $initialorder ){
$result6 = mysql_query("SELECT * FROM information
WHERE `sortorder` = '$sortorder'");
$row6 = mysql_fetch_array($result6);
$removethis1 = $row6['id'];
$result7 = mysql_query("UPDATE information
SET `sortorder`= ((SELECT `sortorder`
FROM (SELECT MAX(`sortorder`) AS
'$initialorder' FROM information) AS '$initialorder') + 1)
WHERE id='$removethis1'");
}
$query = "INSERT INTO `information`
(`id`,`page`,`description`,`status`,`sortorder`,`keyword`,`date_added`)
VALUES
('$id','$title','$description','$status',
'$sortorder','$keyword','$date_added')";
$result = mysql_query($query, $conn);
header('Location: index.php?status=1&title='.$title);
$i++; }
}
You can do this:
INSERT INTO ON `information`
...
DUPLICATE KEY UPDATE
sortorder = '".$sortorder + 1." '
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++){
...
}