I have 2 tables. One is for students and one of subjects. I want to fetch data from the students and subjects tables on same page. In front of student 1 subject 1 subject 2 subject 3. Then in front of student 2 subject 1 subject 2 subject 3. It is to submit result.
I have done this.
Than I have to insert this in 3rd table of results. I have successfully inserted students in result table. And subjects. But on the time of marks, I am unable to insert. I used a multidimensional array. I am unable to insert marks data into array. How can I do this?
Let me show some snapshots.
My multidimensional array is not working, and I don't know how to do this. Kindly help me out.
This is a detailed pic: This is the detailed snapshot.
// count students
$sql = "SELECT * FROM tb_students";
$run = mysqli_query($mysqli,$sql);
$total_students = mysqli_num_rows($run);
$numbers=$total_students;
for($i=1;$i<=$numbers;$i++)
{
while ($rows = mysqli_fetch_assoc($run)) {
$id = $rows['student_id'];
$name = $rows['student_name'];
?>
<tr>
<td>Name</td>
<td hidden><input type="text" value="<?php echo $id?>" name="student_id[]" /></td>
<td><?php echo $name ?> </td>
</tr>
<input type="hidden" value="<?php echo $numbers;?>" name="numbers" />
<?php
$sel_sub = "SELECT * FROM subjects WHERE class_name = '1st year'";
$run_sub = mysqli_query($mysqli,$sel_sub);
$total_sub = mysqli_num_rows($run_sub);
for ($k=0; $k < $total_sub ; $k++) {
while ($rows = mysqli_fetch_assoc($run_sub)) {
$sub_id = $rows['sub_id'];
$sub_name = $rows['sub_name'];
?>
<tr>
<td><?php echo $sub_name; ?></td>
<td hidden><input type="" value="<?php echo $sub_id;?>" name="sub_id[]" /></td>
<input type="hidden" value="<?php echo $total_sub;?>" name="subject" />
<td><input type="text" name="marks[][]" placeholder="Marks" /></td>
</tr>
<?php
}
}
?>`
and this is isnert query
<?php
$mysqli = mysqli_connect("localhost","salman","salman1214","shan");
if(mysqli_connect_errno())
die("Connection failed".mysqli_connect_error());
$s = '';
for($i=0;$i<$_POST['numbers'];$i++)
{
for($j=0;$j<$_POST['subject'];$j++)
{
$s = "insert into result(student_id,exam_name, subject_name, sub_marks) values";
$s .="('".$_POST['student_id'][$i]."','".$_POST['exam_name']."','".$_POST['sub_id'][$j]."','".$_POST['marks'][$i][$j]."'),";
$s = rtrim($s,",");
if(!mysqli_query($mysqli,$s))
echo mysqli_error();
else
echo "Records Saved <br />";
$sub_list = $_POST['marks'][$i][$j];
echo $sub_list;
}
}
mysqli_close($mysqli);?>
I don't want to say if this way is the best way.
But, your problem is you are using the lines in the loops which should not. Try this:
<?php
$mysqli = mysqli_connect("localhost","salman","salman1214","shan");
if(mysqli_connect_errno())
die("Connection failed".mysqli_connect_error());
$s = '';
$s = "insert into result(student_id,exam_name, subject_name, sub_marks) values";
for($i=0;$i<$_POST['numbers'];$i++)
{
for($j=0;$j<$_POST['subject'];$j++)
{
$s .="('".$_POST['student_id'][$i]."','".$_POST['exam_name']."','".$_POST['sub_id'][$j]."','".$_POST['marks'][$i][$j]."'),";
}
}
$s = rtrim($s,",");
if(!mysqli_query($mysqli,$s))
echo mysqli_error();
else
echo "Records Saved <br />";
mysqli_close($mysqli);?>
Related
I am trying to create a form, basing on information picked from the database using a while loop. I need some guidance on how to go about this. When form is supposed to return multiple values (of students) and then a text field for inputting marks is assigned to the students returned, which should allow the user input the marks and then submit the form.
Here is the code i have sofar
<form method="post">
<?php
//picking student details
$sql = mysql_query("SELECT *
FROM student, class, subject, assesment
WHERE
student.class_id = '$assesment_class'
AND subject.idsubject = '$assesment_subject'
AND subject.subject_option = 'Major'
AND class.idclass = student.class_id
AND class.idclass = subject.class_id
AND assesment.subject_idsubject = subject.idsubject
AND assesment.idassesment = '$ass'
");
$Count = mysql_num_rows($sql); //counting the the selected rows
if($Count > 0){
while($row = mysql_fetch_array($sql)){
//picking database values
$student_id = $row["idstudent"];
$student_names = $row["student_names"];
//Query for checking results
$sql1 = mysql_query("SELECT *
FROM result, student_has_result, grade, student, assesment
WHERE
student_has_result.student_id = '$student_id'
AND student_has_result.student_class_id = '$assesment_class'
AND student_has_result.assesment_id = '$ass'
AND student_has_result.result_id = result.idresult
AND result.grade_idgrade = grade.idgrade
AND student_has_result.assesment_id = assesment.idassesment
AND student_has_result.student_id = student.idstudent
AND student_has_result.result_id = result.idresult");
$Count1 = mysql_num_rows($sql1); //counting the the selected rows
if($Count1 > 0){
while($row = mysql_fetch_array($sql1)){
//picking database values
$mark = $row["mark"];
//echo $mark;
}
}else{
$mark = "";
}
?>
<tr>
<td><?php echo $student_names; ?></td>
<td>
<input type="text" name="result" placeholder="<?php echo $mark; ?>"/>
<input type="hidden" name="student" value="<?php echo $student_id; ?>"/>
<input type="hidden" name="assesment" value="<?php echo $ass; ?>"/>
</td>
</tr>
<?php
}
?>
<tr>
<td></td>
<td><button name="submit-results-button" type="submit" class="btn btn-success">-Submit Students Results Now-</button><br><br></td>
</tr>
</form>
Any guidance will be highly appreciated.
Good day! I am having a problem in storing values in my database. The flow of the program is the user will input in how many subject he will get. For example, he/she can put 6 subjects. So it will release 6 input types with values equal to text. My problem is I don't get 6 rows in my database as the user take 6 inputs.
HTML/PHP
<form method="POST">
<table>
<tr>
<td>SUBJECT CODE/SUBJECT DESCRIPTION/SEMESTER</td>
</tr>
<?php $counter=1 ;
while($counter <= $subj){?>
<tr>
<td>
<select name="sub">
<?php $select=mysql_query("SELECT * FROM subject
WHERE course_code = '$course' AND semester = '$sem'");
while($rows=m ysql_fetch_assoc($select)){
$code=$rows['subj_code'];
$desc=$rows['subj_desc'];
$units=$rows['units'];
$yr=$rows[ 'year_level'];
?>
<**option value="<?php echo $codes[$code]; ?>">
<?php echo $code. " - ".$desc; ?>
</option>**
<?php } ?>
</select>
</td>
<td>
</td>
</tr>
<?php $counter++; } } ?>
<tr>
<td>
<input type="submit" name="add" value="add subjects">
</td>
</tr>
</table>
</form>
PHP/SQL
<?php
if (isset($_POST['add'])) {
$data = array();
$subject = $_POST['sub'];
$sem = $_SESSION['sem'];
for ($i = 0; $i < count($subject); $i++) {
$subject = mysql_real_escape_string($subject[$i]);
$sem = mysql_real_escape_string($sem[$i]);
$yr = mysql_real_escape_string($yr[$i]);
$fac = mysql_real_escape_string($fac[$i]);
$col = mysql_real_escape_string($col[$i]);
$set = mysql_query("SET foreign_key_checks = 0");
if (!$set) {
die("Foreign key SET failed");
} else {
$insertmid = mysql_query("INSERT INTO grade_midterm
(midterm_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject', '$user','$fac','$col')");
if (!$insertmid) {
die("Failed to insert midterm" . mysql_error());
} else {
$insertfinal = mysql_query("INSERT INTO grade_final
(final_grade, semester, year_level, subj_code, stud_id, fac_id, col_code)
VALUES ('NA','$sem','$yr','$subject','$user','$fac','$col')");
if (!$insertfinal) {
die("Failed to indert final");
} else {
$set2 = mysql_query("SET foreign_key_checks = 1");
echo "<script>alert('Success Adding Subject');</script>";
}
}
}
}
}
?>
You have a select box with name sub in your loop
<select name="sub">
this means every next selectbox will overwrite the previous one
use
<select name="sub[]">
to create a array in your $_POST variable
I have a table named positions. This table has the list of the different positions that the admin has added in the listOfPositions.php like President, Vice-President, etc. After adding different positions, he can now add the different people under that position. And that's where my problem is. How will I have an auto increment input name for the names of the people depending on how many positions it has in the table positions ?
I tried using javascript, but it increments only in the html and not reflecting to the php when I try to save. My current code where the adding of the names of different persons depending on the position is the ff:
<script type="text/javascript" src="http://code.jquery.com/jquery-git.js"></script>
<form action="post_officers.php" method="post"><br>
<center><select name="year">
<?php
for($i=date('Y'); $i>1999; $i=$i-2) {
$selected = '';
$year2 = $i-2;
if ($year == $i) $selected = ' selected="selected"';
echo ('<option value="'.$year2. "-" . $i .'" '.$selected.'> '.$year2.'-'.$i.'</option>'."\n");
}
?>
</select></center>
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name" /></td>
</tr>
</table>
<?php
}
?>
<input type="submit" name="submit" value="SAVE"/>
</form>
<script>
$("input[name='file']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='position']").each(function(ind) {
$(this).attr(ind + 1);
});
$("input[name='name']").each(function(ind) {
$(this).attr(ind + 1);
});
</script>
And this is my php code:
<?php
include ('dbcontroller.php');
date_default_timezone_set('Asia/Manila');
$year = mysqli_real_escape_string($conn,$_POST['year']);
if(isset($_POST['submit'])) {
$result = mysqli_query($conn,"SELECT * FROM officers WHERE year = '$year'");
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
echo "<script type='text/javascript'>alert('Year already exists.'); window.location.href='create_alumni_officers.php';</script>";
}
else {
for ($i = 1; $i <= 8; $i++) {
$name = mysqli_real_escape_string($conn,$_POST['name'.$i]);
$position = mysqli_real_escape_string($conn,$_POST['position'.$i]);
$file=(rand(1000,100000)."-".$_FILES['file'.$i]['name']);
$type=($_FILES['file'.$i]['type']);
$size=$_FILES['file'.$i]['size'];
$loc=($_FILES['file'.$i]['tmp_name']);
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($file);
// make file name in lower case
$final_file=str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
}
}
?>
And this doesn't work at all. Any help? I hope you guys understood what I'm trying to ask.
This is the best way to do it:
<?php
include_once('dbcontroller.php');
$sql = "SELECT * FROM positions ORDER BY pos_id ASC";
$result = mysqli_query($conn, $sql);
/* assign an onchange event handler */
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<table id="options-table">
<tr>
<td><input type="file" name="file[<?php echo $position; ?>]" /></td>
<td><input type="hidden" name="position[<?php echo $position; ?>]" value="<?php echo $position; ?>" /><?php echo $position; ?></td>
<td><input type="text" name="name[<?php echo $position; ?>]" /></td>
</tr>
</table>
<?php
}
?>
You don't need the javascript to change input attributes. Remove it.
In php use foreach loop like:
If you are still getting errors I will need to see the output of print_r($_POST);
<?php
$files = $_FILES['file'];
$positions = $_POST['position']; //use this for the foreach loop because it will always have a value
$names = $_POST['name'];
foreach($positions as $key=>$position){
$file = #$files[$key];
$name= #$names[$key];
//Do your magic for each user here
$name = mysqli_real_escape_string($conn,$name);
$position = mysqli_real_escape_string($conn,$position);
$filename = rand(1000,100000)."-".$file['name'];
$type = $file['type'];
$size = $file['size'];
$loc = $file['tmp_name'];
$new_size=$size/1024; // file size in KB
// make file name in lower case
$new_file_name = strtolower($filename);
// make file name in lower case
$final_file = str_replace(' ','-',$new_file_name);
if(move_uploaded_file($loc, '../officers-avatars/'.$final_file)) {
echo "Page is loading, please wait...";
$result = mysqli_query($conn,"INSERT INTO officers VALUES (id, '$year', '$position', '$name', '$final_file', '$new_size', '$type')")
or die(mysqli_error($conn));
echo ("<script type='text/javascript'>window.location.href='alumni_officers.php';</script>");
}
}
?>
As I indicated in the contents, removing context switches miss fide will greatly increase the readability of your code. I'll illustrate below a bit as well as answer the question.
To get what you're after, you could do this:
while ($row = mysqli_fetch_array($result)) {
$position = $row['position'];
?>
<br><br>
<table id="options-table">
<tr>
<td><input type="file" name="file" /></td>
<td><input type="hidden" name="position" /><?php echo $position; ?></td>
<td><input type="text" name="name<?php echo $position; ?>" /></td>
</tr>
</table>
<?php
}
However, to illustrate a small example of removing these contextual switches mid code, see below and pardon but this is air code, if you want a more specific example, just ask.
Let's say you often use the tag thoughout your site in forms. You could drop out of php each time and just write out the straight html. Or, you could create a class, or even a simple function for the html output thusly:
Function opt($int, $parms = '') {
Return '<Option '.$parms.'>'. $int.'</option>';
}
Now your code would look more like this:
While ($r =mysqli_fetch_array ($result)) {
Extract ($r); // learn this, no sense assigning them 1 by 1
$options .= opt($databaseobject, 'name="foo" value="'. $databaseobjectid.'"');
}
Echo $options;
I am writing a basic CMS system and have come across something which should be seemingly simple -but is beginning to frustrate me.!
I am trying to pass an array through a select option field to populate a list of categories in which I can save a post.
I have a 'posts' form which comprises of 3 fields. Title, content and Category ID (CatID).
When the user creates a post, they can select the category they wish to assign the post assigned to by using a drop down list - (this is populated by using a different form).
So the technical bit; -
MySQL DB:-
categories = catname (char60 PRIMARY), catid (INT10, AI)
posts = id (bigint20 PRIMARY), catid (int10 PRIMARY), title (text), content (varchar255)
Example of categories populates: catname = Home / catid = 1 ...etc
Output.php ;
<?php
function display_post_form($post = '') {
$edit = is_array($post);
?>
<form action="<?php echo $edit ? 'edit.php' : 'add.php' ; ?>" method="post">
<table border="0">
<tr>
<td> Title:</td>
<td> <input type="text" name="title" value="<?php echo $edit ? $post['title'] : '' ; ?>" size="60" /> </td>
</tr><tr>
<td> Content:</td>
<td> <textarea id="editor1" name="content" value="<?php echo $edit ? $post['content'] : '' ; ?>"> </textarea> </td>
</tr><tr>
<td> Category:</td>
<td><select name="catid">
<?php
$cat_array = get_categories($catid, $catname);
foreach($cat_array as $thiscat) {
echo "<option value=\"".$thiscat['catid']."\" ";
if (($edit) && ($thiscat['catid'] == $post['catid'])) {
echo " selected";
}
echo ">".$thiscat['catname']."</option>";
}
?>
</select>
</td>
</tr><tr>
<td> Button:</td>
<td <?php if (!$edit) { echo "colspan=2"; } ?> align="center">
<?php
if ($edit)
echo "<input type=\"hidden\" name=\"_id\" value=\"". $post['id'] ."\" />";
?>
<input type="submit" value="<?php echo $edit ? 'Update' : 'Add' ; ?> Post" />
</form></td>
</td>
</tr>
</table>
</form>
<?php
}
?>
Functions.php ;
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
while($row = mysqli_fetch_assoc($result)) {
printf("\n %s %s |\n",$row["catname"],$row["catid"]);
}
mysqli_close($conn);
}
I am able to call in the 'get_cattegories()' function which generates a flat data of categories and their respective id's. I then combined this with the Select Option Field in the Output.php file and it doesn't generate anything.
Can anyone give some useful tips or advice? Many thanks :)
You are not returning the array but printing a string to the output. Change printf to return:
function get_categories($catid, $catname) {
$conn = db_connect();
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL " .mysqli_connect_error();
}
$sql = "SELECT catname, catid FROM categories";
$result = mysqli_query($conn, $sql) or die(" Could not query database");
$categories = array();
while($row = mysqli_fetch_assoc($result)) {
$categories[] = $row;
}
mysqli_close($conn);
return $categories;
}
Also I agree for the comments to your question. The arguments are useless.
You also may refactor the code, actually... alot. Move the mysql_connect() to the other place, probably at the beginning of your script.
I suggest to use some frameworks. I think KohanaPHP will be a good start. You will learn about architecture and some design patterns. Keep the good work and improve your skills ;-)
I have a loop of checkboxes from a MySql table "exercise" in a form as shown below:
<form id="form1" name="form1" method="POST" action="insertDrills.php">
<table width="100%" border="1" cellspacing="0" cellpadding="0">
<?php do { ?>
<tr>
<td>
<input type="checkbox" name="drillSelect[]" value="<?php echo $row_Recordset1['drillID']; ?>" id="drillSelect" />
<?php echo $row_Recordset1['rubrik']; ?>
</td>
</tr>
<?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
<tr>
<td colspan="2">
<input name="spelarID" type="hidden" id="spelarID" value="<?php echo $row_rsSpelare['id']; ?>" />
<input name="date" type="hidden" id="date" value="<? print date("Y-m-d h:i:s"); ?>" />
<input type="submit" name="submit" id="submit" value="Välj övningar" />
<input type="button" value="Avbryt" onclick="window.close();"></button>
</td>
</tr>
</table>
</form>
The value from the hidden fied "spelarID" along with the value from the checkbox array are inserted to a look-up table "exercise_spelare_ref" with this:
<?php
$id = $_POST['spelarID'];
$drills = $_POST['drillSelect'];
$date = $_POST['date'];
$inserts = array();
foreach ($drills as $drills)
$inserts[] = "('$id','$drills','','$date')";
$query = "REPLACE INTO exercise_spelare_ref VALUES ". implode(", ", $inserts);
//echo "query = $query"; // for debugging purposes, remove this once it is working
mysql_query($query) or die(mysql_error());
?>
How can I make values that are in the look-up table marked as "checked" in the form?
There are a solution here https://stackoverflow.com/a/4069477 written by Martin Bean but I cant get it to work?
I have been stuck here for ever, hope anyone can help me out here!
I tried Martin Beans script like:
$uid = $row_rsSpelare['id']; // your logged in user's ID
$exercise = array();
// get an array of exercise
$sql = "SELECT drillID FROM exercise";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$exercise[$row->id] = $row->drillID;
}
// get an array of exercise user has checked
$sql = "SELECT DISTINCT drillID FROM exercise_spelare_ref WHERE id = '$uid'";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$checked[] = $row->drillID;
}
// this would be templated in a real world situation
foreach ($exercise as $id => $drillID) {
$checked = "";
// check box if user has selected this exercise
if (in_array($checked, $id)) {
$checked = 'checked="checked" ';
}
echo '<input type="checkbox" name="drillSelect[]" value="'.$id.'" '.$checked.'/>';
}
But getting a warning:
Warning: in_array() expects parameter 2 to be array, string given in /customers/b/d/e/teeview.se/httpd.www/analys_kund/selectDrills.php on line 158
Line 158 is:
if (in_array($checked, $id)) {
Well, you will need to SELECT the items from the table, store them into an array, and if the current checkbox's ID matches something in the array, add the checked attribute to it in the HTML.