Using input checkboxes with a database - php

So I'm trying to help a friend out by writing his guild an attendance tracker for raiding and whatnot. Right now my concept is to do a select * from the user column, and make a checkbox for each user, assuming that person showed up to raid, it would pass a "1" through the form, and their raid attendance would be incremented by 1. On the users page the overall attendance would be calculated as (raidAtt / raidsTotal)*100 (since joining).
My issue right now is that I don't really know how to get all this information passed using a single loop...
Right now my code is something like this:
<form action="raidattend.php" method="post">
<?php
mysql_connect("$database",$username,$password);
#mysql_select_db($database) or die( "Unable to select database");
$query="SELECT * FROM attend WHERE UserName = $v_member ORDER BY date desc";
$result=mysql_query($query);
$num=mysql_numrows($result);
mysql_close();
?>
<table>
<tr>
<th>Member</th>
<th>Attended?</th>
</tr>
<?php
$i=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"UserName");
}
<tr>
<td><?php echo $f1; ?></td><td input type="checkbox" checked value="1">
And that's where I ran into issues. I'm not sure how to pass each user and the result of the checkbox back to the database. Once I understand how to do that it's just as simple as incrementing, but I'm pretty lost.
Thanks for any help!
Edit: To clarify, what I'm unsure of is how to break it up so each member gets updated, I understand that I need to use a submit and all that.
Edit 2: Stray }

You should change your checkbox so that they all have the same name (ie name="member[]"). This way, when you submit your form, all of the checked members will be in $_POST['member']. Then, just loop through $_POST['member'] and update your table.
<td><?php echo $f1; ?><td> <input type="checkbox" name="member[]" value=<?php echo "'$f1'"; ?> /></td>
This should give you the list of checkboxes with the names of the members that attended.
Here is a quick overview of how to do the update:
1.Loop through $_POST['member'] and increment the amount that person has attended :
foreach($_POST['member'] as $member)
{
mysql_query("update table_name set attended=(attended+1) where username='$member'");
}
2.After you update each member that attended, do an update on the entire table to increment the total number of raids that have happened:
mssql_query("update table_name set total=(total+1)");

on form:
<input type=checkbox name=selected[] value='" . $f1 . "'>
on raidattend.php:
$selected=$_POST['selected'];
while (list ($key,$val) = #each ($selected)) {
//$val will hold the username
}

Related

mysqli php problems showing orders in groups / SELECT DISTINCT shows only one result

I'm having some trouble with my php / mysqli code, hopefully you can help me.
I'm currently working on an online shop for a school project. Customers are able to buy things, they get an order number and I'm writing their user_id, the order number, the different products and some other things in a relation.
now the administrator should be able to see all orders.
right now it looks like this (I copied my table into a word table, so it's easier to see the structure):
part of the table
So the problem is that I have two different order numbers (80425 and 14808) and I want to show each number (and the name and adress of the custumer, too) only one time, but for each order number all different ordered products.
I imagine it like this:
part of the table (more organised)
(it's german, I hope you still get what I mean)
So this is the code right now for getting all the information and show them in a table:
$selection = "SELECT * FROM kundenbestellungen, zahlart, produkte, user, status_bestellung, wohnsitz, kontodaten
WHERE b_zahlung_id = z_id
AND b_produkte_id = p_id
AND b_user_id = u_id
AND b_status_id = sb_id
AND w_user_id = u_id
AND d_user_id = u_id";
$sql = mysqli_query ($dblink, $selection) OR die (mysqli_error($dblink));
if (mysqli_num_rows ($sql) > 0) {
while ($row = mysqli_fetch_assoc($sql)) {
?>
<tr>
<td>
<?php /*Change the status to sent*/
if ($row['b_status_id'] == '0') {
echo $row['sb_status'];
?>
<form action="admin-bestellungen.php" method="POST">
<input type="hidden" name="id" value="<?php echo $row['b_id']?>">
<input type="submit" name="versenden" value="versenden">
</form>
<?php
} else {
echo $row['sb_status'];
}
?>
</td>
<td> <?php echo $row['b_nummer'];?></td>
<td><?php echo $row['u_vorname']." ".$row['u_nachname'];?></td>
<td><?php echo $row['p_produktname'];?></td>
<td><?php echo $row['b_menge_produkt'];?></td>
<td><?php echo $row['b_einzelpreis'];?></td>
<td><?php echo $row['z_art'];?></td>
<td><?php echo $row['b_zeitpunkt'];?></td>
</tr>
<?php
}
}
I'm really confused. I tried this below the $selection part, just to start with something:
$anzahl_bestellungen = "SELECT COUNT(DISTINCT b_nummer) AS nr FROM kundenbestellungen";
$anzahl_bestellungen = mysqli_query ($dblink, $anzahl_bestellungen) OR die (mysqli_error($dblink));
$bestell = mysqli_fetch_array($anzahl_bestellungen);
print_r($bestell['nr']);
and the code counts the amount of the different order numbers (8). But if I use it without COUNT, it shows only the first order number (80425) and also counts only 1 result and doesn't get the other 7 numbers.
$anzahl_bestellungen = "SELECT DISTINCT b_nummer FROM kundenbestellungen";
$anzahl_bestellungen = mysqli_query ($dblink, $anzahl_bestellungen) OR die (mysqli_error($dblink));
$bestell = mysqli_fetch_array($anzahl_bestellungen);
print_r($bestell['b_nummer']);
$b = count($bestell['b_nummer']);
echo "<br>".$b;
I also tried to work something out with GROUP, but then the code shows only one item for each order number.
I tried to work with a for-loop as well, but that didn't work out either.
I thought about a multidimensional array, but I wasn't able to think through that whole thing, I'm not very good at php / mysqli.
So I have no idea how to go on. Maybe you can help me. This is my first question, so please let me know if I need to be more specific or you need more code or anything.
thanks a lot!

Retrieving and inserting multiple entries in MySQL/PHP

I'm trying to create a form that retrieves data from a database and then allows me to add data to one column for multiple entries.
Every entry has an ID, a lot of other fields, and a category. I am trying to add these categories for every ID in the database using one form.
I came up with the solution below, but (of course)this only inserts the LAST entry in the form, because the variable ID is changed with every new row.
The form I have now shows me what I want to see, but it does not save it the way I need it to.
The question is, (how) can I make a form that has all entries in the database with a dropdown menu next to it,
lets me select the right category from the dropdown, and save it to the database?
The form:
$result = mysqli_query($con,"SELECT * FROM aw");
while($row = mysqli_fetch_array($result))
{
echo '<tr><td><input type="hidden" name="ID" value="'.$row[ID].'."> '.$row[ID].'</td><td>';
echo '
<select name="cat" onchange="this.form.submit()">
<option value="C1">category1</option>
<option value="C2"">category2</option>
</select></td></tr>
';
}
?>
<tr><td><input type="submit" title="SAVE" ></td></tr>
</form>
The insert.php
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$_POST[ID]','$_POST[cat]')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
mysqli_close($con);
?>
I changed my code according to Tom's answer and I now have the following:
This does print the values like they should be, but it still saves only the last entry into the database. I'm sure I must be missing something here..
$name = $_POST['ID'];
$category = $_POST['cat'];
foreach( $name as $key => $n ) {
$sql="REPLACE INTO aw (ID,cat)
VALUES
('$n','$category[$key]')";
print "The id is ".$n.", category is ".$category[$key]."<br>";
}
First of all, use PDO::Mysql, the SQL functions you are using are a bit deprecated and do not focus much on security. At the moment your code is vulnerable to SQL injections and your output is sensitive to XSS attacks (always sanitize output).
I was wrong, MySQL is deprecated but MySQLi is not! I do prefer using PDO::Mysql because of the range of databases it supports (MySQLi only supports a MySQL database, PDO::Mysql supports many more)
Now to your original question, you can create a sort of array. By making name="ID" to name="ID[]" and name="cat" to name="cat[]".
Now you can do
$name = $_POST['ID'];
$category = $_POST['cat'];
foreach( $name as $key => $n ) {
print "The id is ".$n.", category is ".$category[$key];
}
The problem is your using the name elements regardless of how many rows..
So name="ID" & name="cat" needs to change on each row or have an array type
you could use something like name="ID[]" as this would append/ create an array to $_POST['ID']... but you still would want to change your SQL query to handle each of these.
EDIT
If i understand, you want to be able to identify a row from the table so you can use that in the database?? One way todo this is when creating the table.. Give the TR a id/name attribute that is the row id from the database.
Then can simply know by checking that if your using the select menu from row #4, you check the id/name attribute of the current row and you have your database id.
<tr id='my_row_1'>
<td class='colName'>John</td>
<td class='colPhone'>1111</td>
<td class='colOther'>....</td>
</tr>
<tr id='my_row_2'>
<td class='colName'>Bill</td>
<td class='colPhone'>2222</td>
<td class='colOther'>....</td>
</tr>
<tr id='my_row_3'>
<td class='colName'>Roger</td>
<td class='colPhone'>3333</td>
<td class='colOther'>....</td>
</tr>
With something like the above, Say i had a button in on of the columns... When i click on that button.. all i have todo is find the parent TR and get its id value.... Then explode it by "_" and get the last piece to have the id..
So your PHP would generate the id easily... Also, using a form would not be the best case here.. Using multiple forms within a table is... wasteful... sort of ..
I would suggest more so, having a button that simple calls a js function which will then post/ajax/jquery what you need from that row.
--- Trying to understand exactly what you need??

PHP Updating row in record to yes instead of no but it still shows even though code is for where X = no only

The page is set to show all rows where isthisapproved equals no. This is working how I want by updating isthisapproved to yes. However, after updating isthisapproved from no to yes I don't want it to show anymore... but it is. I'm guessing I have some code in the wrong spot so it isn't "refreshing" the isthisapproved=no query.
<form method='post'>";
$query="SELECT * FROM table WHERE isthisapproved='no'";
$result = mysql_query($query) or die(mysql_error());
$count = mysql_num_rows($result);
echo "<p>$count need approval</p>";
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$id=$row['id'];
echo "
<table>
<tr>
<td>ID:</td>
<td>$id <input type='hidden' name='id[]' value='$id'></td>
</tr>
<tr>
<td>
<center><input name='submit' type='submit' value='Change To Yes'></form></center>
</td>
</tr>
</table><br>
";}
if($_POST['submit']) {
$update = "UPDATE table SET isthisapproved='yes' WHERE id='$id' LIMIT 1";
if(mysql_query($update)) $count++;
else die("Error in query:<br>$sql<br>");
echo "<p><b>$name approval changed to yes</b></p>";
}
?>
I'd also like to put the notice that the approval worked to be at the top of the page after an update is made instead of at the bottom. I'm not sure how to go about that.
The select query and the update query are using different column names.
$query="SELECT * FROM table WHERE approved='no'";
^^^^^^^^
$update = "UPDATE table SET isthisapproved='yes' WHERE id='$id' LIMIT 1";
^^^^^^^^^^^^^^
Your code is very vulnerable to SQL injection consider using PDO..
Your id is an array so upon submit all of the ids will be sent to your script as it is all contained in one form.
You could wrap it in individual forms and there would also be no need for id to be an array... OR you could place a check box for each user and have the name as id[] then upon submit. you can do this...
foreach($_POST['id'] as $v){
//query goes here. $v is the ID
}
This could however be more efficient and generate a string to be sent as one query to update all users in one go.
First of all you are using "approved" column for select query and "isthisapproved" for update query. So anyway I am assuming it as a typo error. (If not then fix it).
Now pointing out some issue :
Correct your form starting tag and closing tag. Even though it is closing properly. So here form closing tag should be after finishing the table.
After submitting the form you are not receiving the id through $_POST. You are using direct $id which is wrong.
So here you should recieve the id like this and then pass it to update query :
$id = $_POST['id'];

mysql query not working in php?

My mysql table has 6 fields bkid bkname bkauth bkpub bkedn bkstock.
This program is just for testing you may see some extra lines which I have commented out because I am not using the commented lines for now.
Just for now I am trying to get bkid from the html form and then use it in a query to find out the last column of the retrieved result in $row as $row[5] which is books in stock bkstock. So,I need to find out the no of books in stock from the bkid provided by the user in the form and clicking the button to submit the form.
The query given below does not work.
Notice: Undefined offset: 5 in C:\xampp\htdocs\projects\library\incstockbook.php on line 41
<HTML>
<HEAD>
<h1 align="center">THIS PAGE ADDS STOCK OF BOOKS TO THE LIBRARY</h1>
</HEAD>
TO INCREASE THE STOCK OF BOOKS TO INCLUDE TO THE LIBRARY
<FORM action="incstockbook.php" method="POST">
<table>
<tr>
<td>ENTER THE BOOK ID :</td>
<td><input type=text name="bkid">
</TR>
<TR>
<td>ENTER THE NO. OF BOOKS TO INCLUDE TO THE LIBRARY:</td>
<td><input type=text name="bkstock">
</tr>
</table>
<BR>
CLICK HERE STOCK MORE BOOK :<input type="submit" value="ADD STOCK" name="submit"></br></br>
</FORM>
<?php
$server="localhost";
$username="root";
$password="pramit";
$db="test";
$mysqli = new mysqli($server,$username,$password);
if ($mysqli->errno)
{
printf("Unable to connect to the database:<br /> %s",
$mysqli->error);
exit();
}
$mysqli->select_db($db);
$query1 = "select bkstock from books where bkid=";
if(isset($_POST['submit']))
{
$bkid=$_POST['bkid'];
// $bkstock=$_POST['bkstock'];
$query1.="'$bkid'";
$result=$mysqli->query($query1,MYSQLI_STORE_RESULT);
$row = $result->fetch_array(MYSQLI_NUM);
echo "$row[5]";
}
$mysqli_close;
?>
First thing to do in such cases is to use var_dump(). It'll tell you what is in $row variable and allow you to fix that problem. And problem is the fact that you're trying to get sixth item from row when there is only one, so it should be $row[0].
But there are some more to fix here.
Check $mysqli_close; statement, maybe you wanted to use $mysqli->close()? Because like that it doesn't make any sense.
Next, never use raw user input data in queries. It's dangerous! You have to filter it, or better use prepared statements.
$row[5] tries to retrieve the 6th element from your array. Since this row maps to 1 row (the first) of your query result, the number of elements contained in the row is exactly the number of selected columns from your table. select bkstock from... indicates there will only be one element in your array, so only $row[0] will work.
And as an extra: there is no need to wrap it in a quote when you echo it. just echo $row[0]; should be fine.

Using input checkboxes with a database--part 2

Warning: This question might be a bit long, my apologies in advance.
So in my last question seen here:
Using input checkboxes with a database
I asked the question: "How do I manage multiple users raid attendance with checkboxes and a database loop" and I got a solution that worked in the shortrun, but failed in the longer-run.
Here's the code that runs the loop / allows the user to select who raided:
checked />
When I add this to the database, I actually use 3 queries, shown here:
foreach($_POST['member'] as $member)
{
mysql_query("UPDATE attend set rAttend=(rAttend+1) WHERE UserName='$member'");
mysql_query("INSERT INTO attend set rDate =(CURDATE()) WHERE UserName='$member'");
mysql_query("UPDATE attend set rTotal=(rTotal+1) WHERE UserName='$member'");
}
The reason why I can't use a single 'total' is because each user needs to have the total be based off the amount of raids they attended. Right now the page is displaying like this:
http://i.imgur.com/dwxLf.png
Despite the fact that I entered a date (with CURDATE()) and had selected the checkbox to be checked.
Here's the full code for the query that displays the above: (warning long)
$query="SELECT rTotal FROM rAttend WHERE Username=('$v_member')";
$total=mysql_query($query) or die(mysql_error());
$query="SELECT * FROM rAttend WHERE UserName =('$v_member') order by UserName";
$result=mysql_query($query);
$num=mysql_num_rows($result);
?>
<center><h3><?php echo ($v_member)?>'s attendence record</h3></center>
<?php
$i=0;
$j=0;
while ($i < $num) {
$f1=mysql_result($result,$i,"rDate");
$f2=mysql_result($result,$i,"UserName");
$f3=mysql_result($result,$i,"rAttend");
?>
<tr>
<td><?php echo $f1; ?></td>
<td><?php echo ''.$f2.''; ?></td>
<?php if ($f3 == 1){
echo "<td>yes"; $j++;
}else{ echo "<td>no" ;} ?></td>
</tr>
<?php
$i++;
}
?>
<center>"Raid Attendence: "<?php echo ($j/$total)*100; ?> %</center><br />
</table>
If anyone could help me debug this, I would be most grateful, as php / mysql has never been my favorite language.
Thanks a TON!!!
Edit 1: Shortened posted code by about 30%.
On the second line of your display code:
$total=mysql_query($query) or die(mysql_error());
It seems you're expecting $total to be a number, but it's actually a resource (that's what mysql_query does, it returns a resource to the resultset). You need something like this:
$total_query = mysql_query($query) or die(mysql_error());
$total_row = mysql_fetch_array($total_query);
$total = $total_row['rTotal'];
After working for this on the past few hours, HunderThooves and I finally got the solution. Haha.

Categories