I have retrieve data from lvl2itquepaper and display it with textarea and save the user input to another table call lvl2itresult but when I press save, it save the last user input only.
For example, got 2 question with 2 text area, 1st text area are 'A' and 2nd text area are 'B', it save both user input as 'B'
<?php
include('../dbconnect.php');
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<title>Online Examination System</title>
</head>
<body>
<div id="container">
<h1>Level 2 IT Question Paper</h1>
<h2>Please read the question carefully and answer it confidently. Good Luck All!</h2>
<?php
if(isset($_POST['Submit']))
{
$sql="SELECT * from lvl1itquepaper";
$run_que = mysqli_query($mysqli, $sql);
$check_que = mysqli_num_rows($run_que);
while ($row=$run_que->fetch_assoc())
{
$questionno = $row['questionno'];
$question = $row['question'];
$student_ans = $_POST['studentans'];
$sql="insert into lvl2itresult (questionno, question, studentans, username) values ('.$questionno.', '$question', '$student_ans', '".$_SESSION['login_user']."')";
$submit = $mysqli->query($sql);
}
}
?>
<form method= "post">
<?php
echo "Welcome, ";
$sql="SELECT * from lvl2itstudent WHERE username= '".$_SESSION['login_user']."'";
$find_student = mysqli_query($mysqli, $sql);
$check_student = mysqli_num_rows($find_student);
if ($check_student>0){
while($row = $find_student->fetch_assoc())
{
echo $row['username'];
}
}
echo "<br><br><br><br>";
$sql="SELECT * from lvl2itquepaper";
$run_que = mysqli_query($mysqli, $sql);
$check_que = mysqli_num_rows($run_que);
if($check_que>0){
while ($row=$run_que->fetch_assoc())
{
$questionno = $row['questionno'];
$question = $row['question'];
echo "".$questionno. "." .$question."<br>";
echo "<textarea name='studentans' rows='5' cols='50'></textarea><br><br>";
}
}
else {
echo "there is no data in database";
}
?>
<input type="submit" value = "Submit" name= "Submit" style= "width:60px; height:30px";>
</form>
</div>
</body>
This is pretty easy, but hard to explain in a few words. What's pretty much going on is that only one parameter is being sent in the POST data since no array has been set; furthermore PHP is not treating the information as arrays either, so there's only one value to be interpreted. In any case, if the data was sent correctly, PHP would identify the POST value as an array of 2 dimensions, outputting a SQL error for not being able to parse the data as a string.
To solve this, first change your <textarea> tag as follows:
<textarea name='studentans[]' rows='5' cols='50'></textarea>
The brackets will tell HTML that there will be many elements with the name studentans.
Now breaking into your insert logic, you need to treat the arrays getting the values using indexes. Usually these will start on 0, so we will work with that:
$i = 0; // $i stands for index.
while ($row=$run_que->fetch_assoc()){
$questionno = $row['questionno'];
$question = $row['question'];
$student_ans = $_POST['studentans'][$i]; // this is where the magic happens
$sql="insert into lvl2itresult (questionno, question, studentans, username) values ('$questionno', '$question', '$student_ans', '".$_SESSION['login_user']."')";
// please also notice I deleted 2 concatenating dots near "values ('$questionno',"
$submit = $mysqli->query($sql);
$i++; // increment by 1 so we can access the next value on the next loop
}
And that should do it. I hope I didn't forget any detail.
Related
I am currently running into an issue, where I have this form consisting of checkboxes. I get the values of user preferences for the checkboxes from a database. Everything works great, and does what is supposed to do, however after I change and check some boxes and then hit the submit button, it will still show the old values to the form again. If I click again in the page again it will show the new values.
The code is shown below with comments.
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk
FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name
FROM categories
INNER JOIN portals on categories.portal_id=portals.portal_id
ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
<?php
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
if(isset($_POST['submit'])){
if(!empty($_POST['categories'])){
$cats= $_POST['categories'];
$result = mysqli_query($conn,$qry_del_usrcats); //delete all
for ($x = 0; $x < count($cats); $x++) {
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`)
VALUES ('".$_SESSION['user_id']."', '".$cats[$x]."');";
$result = mysqli_query($conn,$qry_add_usrcats);
}
echo "success";
}
elseif(empty($_POST['categories'])){ //if nothing is selected delete all
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
I am not sure what is causing to do that. Something is causing not to update the form after the submission. However, as i said everything works great meaning after i submit the values are stored and saved in the DB, but not shown/updated on the form. Let me know if you need any clarifications.
Thank you
Your procedural logic is backwards and you're doing a bunch of INSERT queries you don't need. As #sean said, change the order.
<?php
if(isset($_POST['submit'])){
if(isset($_POST['categories'])){
$cats= $_POST['categories'];
// don't do an INSERT for each category, build the values and do only one INSERT query with multiple values
$values = '';
for($x = 0; $x < count($cats); $x++) {
// add each value...
$values .= "('".$_SESSION['user_id']."', '".$cats[$x]."'),";
}
// trim the trailing apostrophe and add the values to the query
$qry_add_usrcats="INSERT INTO `user_categories` (`user_id_fk`, `category_id_fk`) VALUES ". rtrim($values,',');
$result = mysqli_query($conn,$qry_add_usrcats);
echo "success";
}
elseif(!isset($_POST['categories'])){ //if nothing is selected delete all
// you may want to put this query first, so if something is checked you delete all, so the db is clean and ready for the new data.
// and if nothing is checked, you're still deleting....
$qry_del_usrcats="DELETE FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';"; //delete all query
$result = mysqli_query($conn,$qry_del_usrcats);
}
unset($usr_cats);
unset($cats);
}
?>
<form action="myprofile.php" method="post">
<?php $usr_cats=array();
$qry_usrcat="SELECT category_id_fk FROM user_categories WHERE user_id_fk='".$_SESSION['user_id']."';";
$result = mysqli_query($conn,$qry_usrcat);
while($row = mysqli_fetch_array($result)){
$usr_cats[] = $row[0]; // getting user categories from db stored in array
}
$query_allcats="SELECT category_id,category_name, portal_name FROM categories INNER JOIN portals on categories.portal_id=portals.portal_id ORDER BY category_id;"; // select all category queries
$result = mysqli_query($conn,$query_allcats);
while($row = mysqli_fetch_array($result)){
echo $row['portal_name'] . "<input "; //print categories
if(in_array($row['category_id'], $usr_cats)){ // if in array from db, check the checkbox
echo "checked ";
}
echo "type='checkbox' name='categories[]' value='";
echo $row['category_id']."'> ". $row['category_name']."</br>\n\t\t\t\t\t\t";
}
?>
<input type="submit" name="submit" value="Submit"/>
Typically this occurs due to the order of your queries within the script.
If you want to show your updated results after submission, you should make your update or insert queries to be conditional, and have the script call itself. The order of your scripts is fine, but you just need to do the following:
Take this query:
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
and put it inside the if statement so it looks like this:
if (isset($_POST['submit'] {
$qry_del_usrcats="DELETE FROM user_categories
WHERE user_id_fk='".$_SESSION['user_id']."';"
$result = mysqli_query($conn,$qry_del_usrcats);
[along with the other updates you have]
}
Also, you will need to move this entire conditional above the form itself; typically any updates, inserts, or deletes should appear year the top of the form, and then call the selects afterward (outside of the conditional)
This is my first php project. I have created a website where users can upload their picture and then view the pictures of other users, one person at a time (similar to the old hotornot.com). The code below works as follows:
I create an array (called $allusers) containing all members except for the user who is currently logged in ($user).
I create an array (called $usersiviewed) of all members who $user has previously either liked (stored in the likeprofile table) or disliked (stored in the dislikeprofile table). The first column of likeprofile and dislikeprofile has the name of users who did the liking/disliking, second column contains the name of the member they liked/disliked.
I use the array_diff to strip out $usersiviewed from $allusers. This is the list of users who $user can view (ie, people they have not already liked or disliked in the past).
Now the problem is when I click the like button, it updates the likeprofile table with the name of the NEXT person in the array (i.e., not the person who's picture I am currently looking at but person who's picture appears next). Additionally, if I refresh the current page, the person who's profile appears on the current page automatically gets 'liked' by me. I would really appreciate any advice on this.
<?php
// viewprofiles.php
include_once("header.php");
echo $user.' is currently logged in<br><br>';
echo <<<_END
<form method="post" action="viewprofiles.php"><pre>
<input type="submit" name ="choice" value="LIKE" />
<input type="submit" name ="choice" value="NEXT PROFILE" />
</pre></form>
_END;
$allusers = array();
//Create the $allusers array, comprised of all users except me
$result = queryMysql("SELECT * FROM members");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
if ($row[0] == $user) continue;
$allusers[$j] = $row[0];
}
//Create the $i_like_these_users array, comprised of all users i liked
$result = queryMysql("SELECT * FROM likeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_like_these_users[$j] = $row[1];
}
//Create the $i_dislike_these_users array, comprised of all users i disliked
$result = queryMysql("SELECT * FROM dislikeprofile WHERE user='$user'");
$num = mysql_num_rows($result);
for ($j = 0 ; $j < $num ; ++$j)
{
$row = mysql_fetch_row($result);
$i_dislike_these_users[$j] = $row[1];
}
//Create the $usersiviewed array, comprised of all users i have either liked or disliked
if (is_array($i_like_these_users) && is_array($i_dislike_these_users))
{
$usersiviewed = array_merge($i_like_these_users,$i_dislike_these_users);
}
elseif(is_array($i_like_these_users))
{
$usersiviewed = $i_like_these_users;
}
else
{
$usersiviewed = $i_dislike_these_users;
}
// this removes from the array $allusers (i.e., profiles i can view) all $usersviewed (i.e., all the profiles i have already either liked/disliked)
if (is_array($usersiviewed))
{
$peopleicanview = array_diff($allusers, $usersiviewed);
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
else {
$peopleicanview = $allusers;
$peopleicanview = array_values($peopleicanview); // this re-indexes the array
}
$current_user_profile = $peopleicanview[0];
echo 'check out '.$current_user_profile.'s picture <br />';
if (file_exists("$current_user_profile.jpg"))
{echo "<img src='$current_user_profile.jpg' align='left' />";}
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['choice']) && $_POST['choice'] == 'LIKE')
{
$ilike = $current_user_profile;
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$ilike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['choice']) && $_POST['choice'] == 'NEXT PROFILE')
{
$idontlike = $current_user_profile;
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$idontlike')";
if (!queryMysql($query)) echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
?>
Because when you refresh page it sends previus value of
Form again...and problem when u like a user it being liked next user.. There there is something in yor for loop while fetching row ...insted of for loop try once while loop ...i hope it will solve ur problem
You are calculating the $iLike variable with the currently loaded user and then updating the database with that user.
You should probably change your application logic a bit:
pass the user ID of the user you liked or did not like as a POST parameter in addition to the like/didn't like variable
move the form processing logic to the top of your page (or better yet separate out your form processing from HTML display)
Also, it's best not to use the mysql_* extensions in PHP. Use mysqli or PDO.
Try to make two different forms. One with "LIKE", another with "NEXT" to avoid liking from the same form
When you submit your form - your page refreshes, so in string $current_user_profile = $peopleicanview[0]; array $peopleicanview doesn't have user from previuos page (before submitting) you have to attach it, e.g. in hidden field
<form method="post" action="viewprofiles.php">
<input type="hidden" name="current_user" value="$current_user_profile" />
<input type="submit" name ="choice" value="like" />
</form>
<form method="post" action="viewprofiles.php">
<input type="submit" name ="go" value="next" />
</form>
and INSERT it later
"INSERT INTO likeprofile VALUES" . "('$user', '".$_POST['current_user']."')"
ps remove <pre> from your form
Lets start by simplifying and organizing the code.
<?php
// viewprofiles.php
include_once("header.php");
//if form is sent, process the vote.
//Do this first so that the user voted on wont be in results later(view same user again)
//use the user from hidden form field, see below
$userToVoteOn = isset($_POST['user-to-vote-on']) ? $_POST['user-to-vote-on'] : '';
// if i like or dislike this person, the likeprofile or dislikeprofile table is updated with my name and the name of the person who liked or disliked
if (isset($_POST['like']))
{
$query = "INSERT INTO likeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
if (isset($_POST['dislike']))
{
$query = "INSERT INTO dislikeprofile VALUES" . "('$user', '$userToVoteOn ')";
if (!queryMysql($query))
echo "INSERT failed: $query<br />" . mysql_error() . "<br /><br />";
}
//now we can create array of available users.
$currentProfileUser = array();
//Create the $currentProfileUser array,contains data for next user.
//join the 2 other tables here to save php processing later.
$result = queryMysql("SELECT `user` FROM `members`
WHERE `user` NOT IN(SELECT * FROM `likeprofile` WHERE user='$user')
AND `user` NOT IN(SELECT * FROM `dislikeprofile` WHERE user='$user')
and `user` <> '$user'
LIMIT 1");
//no need for a counter or loop, you only need the first result.
if(mysql_num_rows > 0)
{
$row = mysql_fetch_assoc($result);
$current_user_profile = $row['user'];
}
else
$current_user_profile = false;
echo $user.' is currently logged in<br><br>';
//make sure you have a user
if($current_user_profile !== false): ?>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="like" value="LIKE" />
</form>
<form method="post" action="viewprofiles.php">
<input type="hidden" name="user-to-vote-on" value="<?=$current_user_profile?>" />
<input type="submit" name ="dislike" value="NEXT PROFILE" />
</form>
check out <?=$current_user_profile?>'s picture <br />
<?php if (file_exists("$current_user_profile.jpg")): ?>
<img src='<?=$current_user_profile.jpg?>' align='left' />
<?php endif; //end check if image exists ?>
<?php else: //no users found ?>
Sorry, there are no new users to view
<?php endif; //end check if users exists. ?>
You'll notice I changed the code a lot. The order you were checking the vote was the main reason for the issue. But over complicating the code makes it very difficult to see what's happening and why. Make an effort to organize your code in the order you expect them to run rather a vote is cast or not, I also made an effort to separate the markup from the logic. This makes for less of a mess of code to dig through when looking for the bug.
I also used sub queries in the original query to avoid a bunch of unnecessary php code. You could easily have used JOIN with the same outcome, but I think this is a clearer representation of what's happening. Also please use mysqli instead of the deprecaded mysql in the future, and be aware of SQL injection attacks and makes use of real_escape_string at the very least.
Hope it works out for you. Also I didn't test this code. Might be a few errors.
I have a site where an admin can enter exam marks for papers which are part of an exam.
I am on the final part of actually giving a user their mark. But I just can't seem to do it.
So far what I have done is:
Allow the admin to view all of the exams, click on a specific exam and view the papers for that exam, then click on a paper and view all of the people who took that paper.
Then, click on a user and enter their marks and feedback. This is the part which I cannot do. I have pasted my code below along with what I am trying to do but it just is not working, any help would be great!
So, along with their mark and feedback I am also inserting into the marks table the, paperID and the examID.
CODE:
<?php
$epsID = $_GET['epsID'];
$sql = "SELECT * FROM ExamPaperStudent WHERE epsID = '$epsID'";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result))
{
$epID = $row ['epID'];
$sID = $row ['sID'];
echo "<p><form>";
echo "<b>Mark: <input type=text name=mark></b><br>";
echo "<b>Feedback: <input type=text name=feedback></b><br>";
echo $epID;
echo $sID;
echo "</form>";
echo "<a href='insertmark.php?epsID=". $row['epsID']."'>Add Data</a>";
}
?>
INSERTMARK.php code: (At this form I already know the exam/paper ID, which I also am trying to insert (along with marks/feedback).
CODE:
$mark = $_POST["mark"];
$feedback = $_POST["feedback"];
if(isset($_REQUEST['submit']))
{
$sql = mysql_query("insert INTO exammarks (mark, feedback, epID, atID) values ('$mark', '$feedback', '$epID', '$sID')");
$result = mysql_query($result);
}
epsID = exampaperstudent
epID = exampaper
sID = student
your form is wrong .
change this
echo "<p><form>";
to
echo "<p><form action='INSERTMARK.php' method='POST' name='myform'>";
OMG everything is wrong inside your inputs. i just give one and you correct the others
echo "<b>Mark: <input type='text' name='mark'></b><br>";
^----^------^----^---//use single quotes around here
didnt you miss submit button ?
I am having a problem.
I am creating a script that allows a person to select a record by it's primary ID and then delete the row by clicking a confirmation button.
This is the code with the form:
"confirmdelete.php"
<?php
include("dbinfo.php");
$sel_record = $_POST[sel_record];
//SQL statement to select info where the ID is the same as what was just passed in
$sql = "SELECT * FROM contacts WHERE id = '$sel_record'";
//execute SELECT statement to get the result
$result = mysql_query($sql, $db) or die (mysql_error());//search dat db
if (!$result){// if a problem
echo 'something has gone wrong!';
}
else{
//loop through and get dem records
while($record = mysql_fetch_array($result)){
//assign values of fields to var names
$id = $record['ID'];
$email = $record['email'];
$first = $record['first'];
$last = $record['last'];
$status = $record['status'];
$image = $record['image'];
$filename = "images/$image";
}
$pageTitle = "Delete a Monkey";
include('header.php');
echo <<<HERE
Are you sure you want to delete this record?<br/>
It will be permanently removed:</br>
<img src="$filename" />
<ul>
<li>ID: $id</li>
<li>Name: $first $last</li>
<li>E-mail: $email</li>
<li>Status: $status</li>
</ul>
<p><br/>
<form method="post" action="reallydelete.php">
<input type="hidden" name="id" value="$id">
<input type="submit" name="reallydelete" value="really truly delete"/>
<input type="button" name="cancel" value="cancel" onClick="location.href='index.php'" /></a>
</p></form>
HERE;
}//close else
//when button is clicked takes user back to index
?>
and here is the reallydelete.php code it calls upon
<?php
include ("dbinfo.php");
$id = $_POST[id];//get value from confirmdelete.php and assign to ID
$sql = "SELECT * FROM contacts WHERE id = '$id'";//where primary key is equal to $id (or what was passed in)
$result=mysql_query($sql) or die (mysql_error());
//get values from DB and display from db before deleting it
while ($row=mysql_fetch_array($result)){
$id = $row["id"];
$email = $row["email"];
$first= $row["first"];
$last = $row["last"];
$status = $row["status"];
include ("header.php");
//displays here
echo "<p>$id, $first, $last, $email, $status has been deleted permanently</p>";
}
$sql="DELETE FROM contacts WHERE id = '$id'";
//actually deletes
$result = mysql_query($sql) or die (mysql_error());
?>
The problem is that it never actually ends up going into the "while" loop
The connection is absolutely fine.
Any help would be much appreciated.
1: It should not be $_POST[id]; it should be $_POST['id'];
Try after changing this.
if it does not still work try a var_dump() to your results to see if it is returning any rows.
if it is empty or no rows than it is absolutely normal that it is not working.
and make sure id is reaching to your php page properly.
Ok as you are just starting, take care of these syntax, and later try switching to PDO or mysqli_* instead of mysql..
Two major syntax error in your code:
Parameters must be written in ''
E.g:
$_POST['id'] and not $_POST[id]
Secondly you must use the connecting dots for echoing variables:
E.g:
echo "Nane:".$nane; or echo $name; but not echo "Name: $name";
Similarly in mysql_query
E.g:
$sql = "SELECT * FROM table_name WHERE id="'.$id.'";
I hope you get it..take care of these stuff..
I am doing an exercise from the book PHP & MYSQL in easy steps. It involves an HTML form to update a row in a database then various PHP scripts to check the the input data for HTML code and make it into a secure format. However, the code just does not work the way the book says. I went to the publisher's website and downloaded the code example, but no joy.
Instead of a form with the name of the row below it, instead I get the form, then below that "No valid new name submitted". Then below that the current name of row in the table which I want to change. When I try to enter and submit data into the form it makes no difference. It displays exactly the same page. The code is below.
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Ensuring security
</title>
</head>
<body>
<form action="secure.php" method="POST">
<p>New Name : <input type="text" name="name">
<input type="submit"></p></form>
<?php
require('../connect_db.php');
if (!empty($POST['name']) && !is_numeric($_POST['name'])) {
$name = $POST['name'];
$name = mysqli_real_escape_string($dbc, $name);
$name = strip_tags($name);
$q = 'UPDATE towels SET name "' . $name . '" WHERE id= 1';
mysqli_query($dbc, $q);
} else {
echo 'No valid new name submitted';
}
$q = 'SELECT * FROM towels WHERE id = 1 ';
$r = mysqli_query($dbc, $q);
while ($row = mysqli_fetch_array($r, MYSQLI_NUM)) {
echo "<p>Name : $row[1] </p>";
}
mysqli_close($dbc);
I'd appreciate any ideas on this. I have spent about 3 hours and been on the publishers website, but I am still at square one.
There is no superglobal array $POST so you have to change $POST['name'] to $_POST['name'].
PHP can't see that array so it evaluates !empty($POST['name']) as false and never executes code with update query.
And, like #BartFriederichs said, buy better book. I don't think you'll learn something valuable from current one.