I've tried to create list of users. In front of every user i have tried to place check box to check attendance.
Unfortunately i don't succeed to create a "dynamic" one. Can somebody explain to me how to achive that type of list ? (to print checkbox infront of every registred user and print results)
Here is my code :
<?php
echo '<h2>Students:</h2>';
$sql = "SELECT username FROM users WHERE user_type = 'user' ";
$result = mysqli_query($db, $sql);
if ($result){
while($user = mysqli_fetch_array($result)) {
echo $user['username'], '</br>';
}
}
?>
</div>
Replace the line echo $user['username'], '</br>'; with:
$username = $user['username'] ;
echo "<input type=checkbox name='user' value='$username'>$username<br>" ;
The first line saves the username to a variable which can be more easily accessed from within the echo on the next line. The second line will print an html checkbox for each username, with a common name of 'user' and a value of the username for each one.
Related
I am developing a platform that allows me to enter presences at an event and I am stuck in one place. How can I load a series of checkboxes in order to change the user ID for each item?
A practical example, I have a table containing the name of all the people and next to it a checkbox once pressed submit php must upload the data for each user to the db.
Below the html form and the php script that manages the upload to the db.
'''php
<?php
$query = "SELECT * FROM utenti";
$ris = mysqli_query($conn, $query);
//$dati = mysqli_fetch_array($ris);
while($row = mysqli_fetch_assoc($ris)){
echo "<tr><td>".$row['nome']."</td>";
echo "<td>".$row['cognome']."</td>";
echo "<td>".$row['squadra']."</td>";
echo "<td>
<input type='checkbox' name='presenza' data-toggle='toggle' data-onstyle='success' data-offstyle='danger' data-on='Presente' data-off='Assente' value='1'>
</td></tr>";
}
'''
if (isset($_POST['submit'])){
if(!empty($_POST['presenza'])){
// Loop to store and display values of individual checked checkbox.
foreach($_POST['presenza'] as $selected){
echo $selected."</br>";
$sql="INSERT INTO presenze(id_utente,settimana,presenza) VALUES ('1','1','$selected')";
if(mysqli_query($conn, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}
}
}
'''
One of the way to get relationship between a user and a checkbox is to use user ID (or whatever unique identifier you have in your tables structure) in checkbox name e.g.:
"<input type='checkbox' name='presenza_" . $row['user_id'] . "'>"
Then on the backend you can iterate over all post params with presenza_ prefix and get user ID from it.
So your code will be a bit more sophisticated:
foreach($_POST as $param_key) {
// working only with params started with presenza_
if (0 !== strpos($param_key, "presenza_")) {
continue;
}
$presenza_parts = explode("_", $param_key);
$user_id = (int)$presenza_parts[1];
}
Keep in mind that checkbox field sends only value if it's switched on and sends nothing if it's switched off.
First of all this is my first question on here, and altohugh I have searched the site none of the answers I've seen resolve my current problem.
I am a PHP novice and am currently working on an end project for a course. The object is to make a rudimentary blog where users can post, delete and edit their news, admins can edit or delete everything etc. I am mostly doing fine, but am having a bit of trouble with the editing feature.
The following code displays all blog posts, their authors and dates of posting. If the currently logged in person is the author of a post or a admin, they have the option of deleting or editing each individual post. A small form appears that contains the title and post text. When the user types something else in clicking on the edit button should change the values in the database to the new values the user specified. The problem is that whenever i click on the edit button in the current setup, nothing happens. If i move the if statement outside of the other if statement, the posts do update, but become blank in the database.
Running print_r($_POST) after the fact shows that the array it builds has correct names and updated values, but still they aren't updated in the database. Here is the code, the pertinent part starts at the last if statement( I know, it isn't injection proof, will get to that as soon as it works):
$query = "SELECT id, title, body, pub_date, user_id FROM posts ORDER BY id desc";
$query_fetch = mysql_query($query);
while ($blog_post = mysql_fetch_assoc($query_fetch)) {
$author_id = $blog_post["user_id"];
$post_id = $blog_post["id"];
$post_id2 = $blog_post["id"] . 2;
$title = $blog_post['title'];
$body = $blog_post['body'];
$query = "SELECT username FROM users WHERE id = '$author_id'";
$query_run = mysql_query($query);
$author = mysql_fetch_assoc($query_run);
echo "<h2>" . censor($blog_post["title"]) . "</h2>" . "<br> <p> Autor: " . $author["username"] . "</p><br><p>Objavljeno: " . $blog_post["pub_date"];
if ($_SESSION['admin'] == 1 or $_SESSION['username'] == $author["username"]) {
echo "<form action='' method='POST'><input type='submit' name= '$post_id' value= 'Obriši objavu'></form>";
echo "<form action='' method='POST'><input type='submit' name= '$post_id2' value= 'Uredi objavu'></form>";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
if (isset($_POST["$post_id"])) {
$del_post = "DELETE FROM posts WHERE id = '$post_id'";
mysql_query($del_post);
}
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
}
Any help would be appreciated.
This last piece of code
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
}
gets activated when post_id2 is sent, but generates a form where post_id2 is not contained anymore. So when you submit that form, the IF is not entered.
You can modify it like this:
if (isset($_POST["$post_id2"])) {
echo "<form action='' method= 'POST'>New title<input type='text' value = '$title' name='title'>New text<textarea name='body' id='' cols='30' rows='10'>$body</textarea><input type='submit' name='edit' value='edit'></form>";
}
if (isset($_POST['edit'])) {
$edit_title = $_POST['title'];
$edit_body = $_POST['body'];
$query = "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
mysql_query($query);
}
In general I think you would find it easier to use forms differently, specifically by using some sort of action tag:
input type="hidden" name="command" value="edit"
input type="hidden" name="post" value="{$post_id}"
This way you could run one single query immediately, without the need for browsing all the posts in a cycle.
One other useful possibility is to split your code between different PHP files, and keeping common code in one include:
<?php // this is delete.php
include "common.php";
$post_id = my_get_var('post_id');
my_sql_command("DELETE FROM posts WHERE...");
used from
<form action="delete.php" method="post" ...>
As you can see this allows for different ways of retrieving post_id (centrally defined in a single function my_get_var in common.php) and the central definition of SQL functions. How this function interfaces to MySQL can then be updated, specifically passing from mysql_ functions (which are deprecated, and soon will no longer be available) to e.g. PDO.
It also allows you to test a single command independently, by directly entering delete.php in the browser (you need for my_get_var to accept both POST and GET variables to do this).
Details
You want to inspect and/or modify a collection of posts. You then require initially at least the following operations: list, edit, and delete.
Only the first works against all posts.
So you could have a list.php file running the SELECT. Also, it is only in this SELECT that you need information about the user, so your query could become:
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) ORDER BY posts.id desc";
In the display cycle we would display this information:
$query_fetch = mysql_query($query);
// This file will receive requests to edit or delete
// We can use a single form.
echo '<form action="manage.php">';
while ($post = mysql_fetch_assoc($query_fetch)) {
echo "<h2>" . censor($post["title"]) . "</h2>" . "<br> <p> Autor: " . $post["username"] . "</p><br><p>Objavljeno: " . $post["pub_date"];
if ((1 == $_SESSION['admin']) or ($_SESSION['username'] == $post["username"]) {
echo "<input type=\"submit\" name=\"Obriši objavu\" value=\"{$post['id']}\" />";
echo "<input type=\"submit\" name=\"Uredi objavu\" value=\"{$post['id']}\" />";
}
echo "<p>" . censor($blog_post["body"]) . "</p>";
}
echo "</form>";
This way you need only one form, and it will submit one field with a name describing the action to be taken, and the post on which to do it.
The file manage.php will then receive this information -- and can also be used to update it:
foreach(array(
"delete" => "Obriši objavu", // from list.php
"edit" => "Uredi objavu", // " "
"update" => "update" // from this file itself (see below)
)
as $test_todo => $var) {
if (array_key_exists($var, $_POST)) {
$id = $_POST[$var];
$todo = $test_todo;
}
}
if (isset($id)) {
switch($todo) {
case "delete":
mysql_query("DELETE FROM posts WHERE id = '{$id}'");
break;
case "edit":
// Get this post.
$query = "SELECT posts.id, title, body, pub_date, user_id, username FROM posts JOIN users ON (posts.user_id = users.id) WHERE posts.id = '{$id}';";
echo '<form action="manage.php" method= "POST">';
// This is how we tell this file what to do, and to what.
echo "<input type=\"hidden\" name=\"update\" value=\"{$id}\">";
// run query, fetch the one record, display info...
echo "</form>";
break;
case "update":
// Build the update query from $_POST.
mysql_query("UPDATE posts SET ...");
}
At first check that your query is correct. Then try to hard-code your query. Also test your query in phpMyAdmin Also you can try to remove the '' from your number variables on every query.
Please, can you give us your error?
There is a possibility also that your database has already been updated. So double check it.
This is how I usually debug. echo the query. Run it in PHPmyadmin, and see the error.
so, in your case.
echo "UPDATE posts SET title= '$edit_title', body= '$edit_body' WHERE id= '$post_id'";
echo that and you will have the query that the script will be trying to run.
Try running it in phpmyadmin and check what the error is.
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 ?
http://i.stack.imgur.com/Gy3o0.png
That is what the site looks like now. What I want to do is when you click on the approve registration on the table, it will extract the value of the id no and the name of that particular record. I thought i was on the right track. I knew how to get the id no. But it doesn't get the value of the name at the same time.
This is how the code looks like:
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><form method=post action=approvedmayor.php><input type='radio' name=id value='$id'></td>";
}
approvedmayor.php
$query = mysql_query("insert into tbcandidates VALUES ($id, '$name', 'mayor')");
if ($query)
{
echo "You appproved ";
echo $name;
}
else
echo "error";
you can try like this...
<?php
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr><td><a href='approvedmayor.php?id=$id&name=$name'>Approve</a></td></tr>";
}
?>
in this type don't use the form, and Approve button... try this alone
Actually it is bad practice to insert that kind of data directly from POST data.
If you have all these candidates already stored in the database, you should run a SELECT query in your approvedmayor.php first, and if the candidate still exists, insert it's data to another table.
$query = mysql_query('SELECT * FROM `candidates` WHERE `id` = '.$id.' LIMIT 1');
if(mysql_num_rows($query)) {
$candidate = mysql_fetch_assoc($query);
$insertQuery = mysql_query("insert into tbcandidates VALUES ($candidate['id'], $candidate['name'], $candidate['mayor'])");
if ($insertQuery) {
echo "You appproved ";
echo $name;
} else echo "error";
} else echo 'This candidate is no longer available';
I understand your question,
But thats not the best way go ahead, Before we move let us understand some little elements functions
Radio Button : Its an input type element, that allows the user to choose only one [ 1 ] of option given list.
Check Boxes : Its an input type element, that allows the user to select n number of options or selections from give list.
Fore info - http://www.w3schools.com/html/html_forms.asp
Now comming to your question..
You need to modify your code to check boxes as below
<input type='checkbox' name=id[] value='$id'>
Notice : elements name is in Array mode.. ie whenever a user one or more than one, the values are stored in array.
Once the values are stored in array, call it / use if however you want.
For your mentioned code
echo "<form method=post action=approvedmayor.php>';
while($row = mysql_fetch_array($mayor))
{
$id = $row['identification_no'];
$name = $row['lastname'].", ".$row['firstname'];
echo "<tr>";
echo "<td><input type='radio' name=id[] value='$id'></td>";
}
echo "</form>";
approvedmayor.php
$temp_app_arr = $_POST['id'];
foreach ($temp_app_arr as $pos => $val) {
$query = mysql_query("insert into tbcandidates VALUES ('$val', '$name', 'mayor')");
if ($query) {
echo "You appproved ";
echo $name;
} else {
echo "error";
}
}
And i believe this should gonna be good code / algorithm for your project.