Using input checkboxes with a database--part 2 - php

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.

Related

Data cross matching with mysql two tables, value display in table using PHP mySql

I am having some trouble with php and mysql, I am even not sure how to properly ask the question, it seems very complex. Still if anyone can help me, i will be very thankful.
i have two tables
(allunit.sql)
id - unit_name
12 - MIS
14 - MIT
15 - ENG
when someone click enroll button from browser (unit_id) will store in enrollment table. if some one enroll into the unit, button will show (Already Enrolled), not not it will show "Enroll"
enrollment.sql
enroll_id - unit_id
1 - 12
2 - 14
I am using this query
$unit = SELECT * FROM allunit;
$enroll = SELECT * FROM enrollment;
$row_enroll = mysqli_fetch_assoc($enroll);
while($row = mysqli_fetch_assoc($unit)) {
if($row['id']==$row_enroll['unit_id']){
$button = 'Already enrolled';
}else{
$button = 'Enroll';
}
?>
<tr>
<td><?php echo $row['id']; ?></td>
<td><?php echo $row['unit_name']; ?></td>
<td><?php echo $button; ?></td>
</tr>
<?php } ?>
if i add one unit button changes to "already Enrolled" for that unit, but if i add more than one, still only one button changes. other stays same "enroll".
I know my question is reallty messy, hope you will understand. Badly need help. Thank you
First, you have to tell the database to run your query, it is not enough to place a query in a text string. This is done, in this case using the query() method.
Second, as you want to process the Enrolments once for each of the Units, it would be useful to unload at least the Enrolment into an array so it is easily reusable
// assuming you have a connection and its in $con
$sql = 'SELECT * FROM allunit';
$units = $con->query($sql);
$sql = 'SELECT unit_id FROM enrollment';
$res2 = $con->query($sql);
// make an array of just the enrolment id's as that all you need
// so we can use in_array() later to do the test for are you already enrolled
$enrols = [];
while ($row = $res2->fetch_assoc()){
$enrols[] = $row['unit_id'];
}
while ($unit = $units->fetch_assoc() ) {
if ( in_array($unit['id'], $enrols) ) {
$button = 'Already enrolled';
}else{
$button = 'Enroll';
}
?>
<tr>
<td><?php echo $unit['id']; ?></td>
<td><?php echo $unit['unit_name']; ?></td>
<td><?php echo $button; ?></td>
</tr>
<?php
} // endwhile
?>
There are two problems I see in your code:
mysqli_fetch_assoc() is called on a MySQL result, not a query. You need to call mysqli_query() first. You can see an example in the docs: https://www.php.net/manual/en/mysqli-result.fetch-assoc.php
When you get a result, such as $row_enroll, it's a collection of rows, so you can't use it with a column directly, i.e. $row_enroll['unit_id'] won't give you anything.
Finally, it doesn't appear that a comparison between two separate datasets like this is going to work well for you, at least with the current code. Consider using JOINs to return just one dataset.

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!

Loop through database record to generate table

I want to construct an html table based on the returned results from the database. Assuming I have a table called constraints in my database and a column called riskName and it has these values: Security, Financial, Legal and Technical as shown in the image below. How do i loop through my database and come up with this table. I have tried different approach but no has worked. Here is my code so far:
<?php
error_reporting(0);
$optioner = 12;
$getObs = $db->prepare("SELECT * FROM constraints WHERE constraintsID = ?");
$riski->bindParam(1, $optioner);
$riski->execute();
$result = $riski->fetch(PDO::FETCH_ASSOC);
while($getObs->fetch(PDO::FETCH_ASSOC)){
echo "<tr><td>".($result['riskName'])."<td><tr>";
//...other code
}
?>
</tbody>
<?php };
?>
I'm not sure if this will give you the exact table you're looking for, but it should at least put you on the right lines. Also, you weren't keeping your variables the same and notice how $result is set in the while loop
$optioner = 12;
$riski = $db->prepare("SELECT * FROM constraints WHERE constraintsID = ?");
$riski->bindParam(1, $optioner);
$riski->execute();
?>
<form>
<table>
<tr> <th>i</th> <th>Importance</th> <th>How Much More?</th> <tr>
<?php
while($result = $riski->fetch(PDO::FETCH_ASSOC)){
echo '<tr>';
echo '<td>'. $result['riskName']).'<td>';
echo '<td>';
for ($i=1;$i<10;$i++){
//radio buttons go here
}
echo'<tr>';
//...other code
}
?>
Sorry I couldn't help more.
Hope this works for you.

Retrieving mysql table data that is stored within a php variable array

My connection to my database was successful. I now have all of the data from a table stored as an array in a php variable named $data. I am trying to extract three rows from this variable and display them with html.
Here is what my code looks like (with the exception of the connection info being removed):
<?php
$data = mysql_query("SELECT * FROM specs")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data)) {
$rows[] = $row;
?>
I know that I can pull individual data from this variable and insert it into html successfully by entering code like this (for example):
<table cellpadding="0" cellspacing="0" border="0">
<tr>
<td>Model: <?php echo $row['name'];?></td>
</tr>
</table>
But my problem is that I want to display three separate rows of data from the database as three individual columns in a html table. (Hope that makes sense)
I've looked into how to do this with foreach and while but am not quite sure where I'm going wrong.
I'm hoping someone might be able to shed some light on this as I have read about foreach loops, while, and am still stuck! I'm also hearing that mysql_query is deprecated but ruled out not using this since our webserver is still using an old version of php and mysql and is not planning to update anytime soon.
Sorry if I'm not all here in my post - it's late and I'm tired. Thanks for your help in advance! I'll keep an eye on this in case anyone has questions.
This will print the array in a table with each row being 3 elements of the array.
echo "<table>";
for ($i = 0; $i < count($rows); $i += 3) {
echo "<tr>";
for ($j = 0; $j < 3; $j++) {
if (isset($rows[$i+$j]) {
echo "<td>Model: {$rows[$i+$j]['name']}</td>";
}
}
echo "</tr>";
}
echo "</table>";
It's simpler to limit the SQL to three rows, and then echo all incoming rows directly, without first adding to an array. That would waste resources.
<?php
echo "<table>";
$data = mysql_query("SELECT * FROM specs LIMIT 3")
or die(mysql_error());
while ($row = mysql_fetch_assoc($data))
echo '<tr></td>', $row['name'], '</td></tr>';
echo "</table>";
?>
Ah, but now I see it's a year old question. I hope you learned a lot in the meantime.

Using input checkboxes with a database

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
}

Categories