POST values from multiple checkboxes to SQL - php

I've got two tables in mySQL.
Table: Player
-----------------------------------------------------------
| name | T1 | T2 | T3 | T4 | T5 | id | weeknumber |
|--------|----|-----|-----|-----|-----|-----|-------------|
| | | | | | | | |
| | | | | | | | |
-----------------------------------------------------------
Table: Teams
-------------------------------------------------------------------------
| id | team1name | team2name | team1score | team2score | weeknumber |
|------|-----------|-----------|-------------|------------|-------------|
| | | | | | |
| | | | | | |
-------------------------------------------------------------------------
The idea is, that table "Teams" is getting populated through another page that already works for me.
Every week there will be 13 new teams.
Table "Player" has to get populated from another page where the user gets the following options:
Name: Text-field
13 Checkboxes (those checkboxes need to store the value ID from table Teams)
The user is supposed to check 5 out of 13 teams (free choice) and the values of those checkboxes (the ID of the Teams ID) should be stored as T1, T2, T3, T4, T5 along with Name from text-field.
<form method="post" action="created.php" class="form-style-7">
<h2>Tilmeld en spiller </h2>
<ul>
<li>
<label for="name">Navn</label>
<input type="text" name="navn" value="<?php echo $navn;?>">
<span>Indtast spillerens navn</span>
</li>
<li>
<?php
$count = $rows = 0;
$sql = "SELECT * FROM Teams WHERE weeknumber='$WeekNumber' ORDER BY id";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo '
<table class=""><tr><th colspan="3">Igangværende - Uge ' . $WeekNumber . '</th></tr>
<tr class="underhead"><td>#</td><td>Kamp</td><td>Mål</td></tr>
';
// Output af data
while($row = $result->fetch_assoc()) {
if ($rows % 1 == 0) {
$count++;
}
$rows++;
echo '<tr>';
echo '<td>';
echo '';
echo '<input type="hidden" name="ID" value="' . $row['id'] . '" >';
echo '<input class="btn" type="checkbox" name="" > ';
echo ' </form>';
echo '</td>';
echo '<td>' . $count . '</td>';
echo '<td>' . $row["team1name"]. ' - ' . $row["team2name"] . '</td>
</form>';
}
echo '</table>';
}
mysqli_close($conn);
?>
</li>
<li id="buttontilmeld">
<input type="submit" name="submit" value="Tilmeld" >
</li>
</ul>
</form>
Edit:
My created.php contains the following:
if (isset($_POST['navn']) && $_POST['navn'] != "") {
if (isset($_POST['navn'])) {
if ($_POST['name'] == "" || $_POST['T1'] == "" || $_POST['T2'] == "" || $_POST['T3'] == "" || $_POST['T4'] == "" || $_POST['T5'] == "") {
echo 'XX';
}
} else {
require 'config.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['navn']);
$match1 = $conn->real_escape_string($_POST['kamp1']);
$match2 = $conn->real_escape_string($_POST['kamp2']);
$match3 = $conn->real_escape_string($_POST['kamp3']);
$match4 = $conn->real_escape_string($_POST['kamp4']);
$match5 = $conn->real_escape_string($_POST['kamp5']);
$WeekNumber = date('W');
$query = "INSERT into Spillere (navn,kamp1,kamp2,kamp3,kamp4,kamp5,ugenummer) VALUES('" . $name . "','" . $match1 . "','" . $match2 . "','" . $match3 . "','" . $match4 . "','" . $match5 . "','" . $WeekNumber . "')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
echo "Thanks";
}
}
}
Where I need $_POST['TX']=="" to populate table Player T1 to T5.

The name attribute of the checkboxes are not set. PHP can't get any info about the checked checkboxes (unless you should use Jquery en do some other stuff). It's important to know that only checked checkboxes will be visible in the POST data.
Give your checkboxes a name, for example:
echo '<input class="btn" type="checkbox" name="team_checkbox_'.$row['id'].'"> ';
Then in the script created.php were your data is posted to you can catch these values by running the same SQL-query and trying
if(isset($_POST['team_checkbox_'.$row['id']])){
// $row['id'] is checked
}
Or just check all POST data:
$t = array();
foreach($_POST as $post_param_name => $value){
if(substr($post_param_name, 0, 14) == 'team_checkbox_'){
// substr($post_param_name, 14) is the ID of one of the checked groups
$t[] = substr($post_param_name, 14);
}
}
Now $t is an array containing the team ID's of the checkboxes. So you can save in your SQL: T1 = $t[1], ...

This answer should be reviewed, but the solution is in another answer here:
https://stackoverflow.com/a/47162431/1589379
Follow good coding standards
There's a lot of little problems with the code you posted. Ultimately, you should always be very careful to keep everything properly indented, and always use brackets {}, even if they're not needed.
Your original code:
while (...) {
if ($rows % 1 == 0)
$count++;
Should be:
while (...) {
if ($rows % 1 == 0) {
$count++;
}
Those adjustments would have made it much more clear that your code had two closing </form> tags, and no opening tags, within your while loop.

Related

How to export to excel using php when table data and header are dynamic?

I want to export my code to excel however the header is also dynamic. Here is my code, i need assistance in exporting my data. This code below shows a dynamic table i showed in user view and needs to be exported. The view is:
"title: course/section"
"header: student id | student name | program | term | dynamic date 1 | Remarks (remarks why u are absent) including date 1 | date 2 | Remarks (remarks why u are absent) including date 2 | and so on.."
"table data: 20122222 |pinky webb |computer science | 3 | Absent | With medical certificate | present | no remark | present | no remark | late | no remark | and do on... "
"table data 2: 20122333 |Mane Sharpay|computer science | 3 | Absent | With medical certificate | present | no remark | Late | no remark | late | no remark | and so on... "
and so on...
basically, it shows the student and its attendance per date horizontally with a dynamic header of dates. sorry if im noob hehe but ill give a thumbs up i promise for ur effort
<?php
$query = "SELECT course_id, sections_id from current_att_view inner join professor_tbl on current_att_view.professor_id = professor_tbl.professor_id where professor_live_account = '".$_SESSION['username']."' group by course_id, sections_id";
$result1 = mysqli_query($link, $query);
while ($col1 = mysqli_fetch_array($result1))
{
$reslt;
echo '<h3 class="course-sect">'.$col1[0].'/'.$col1[1].'</h3>';
$qry = "Call Get_Attendance_Course_Section('".$_SESSION['username']."','".$col1[0]."','".$col1[1]."')";
$reslt = mysqli_query($link, $qry);
echo '<table class="table table-bordered">';
echo '<tr>';
if (!$reslt) {
printf("Error: %s\n", mysqli_error($link));
exit();
}
else{
while ($fieldinfo = mysqli_fetch_field($reslt)) {
if($fieldinfo->name != "Course" && $fieldinfo->name != "Section" && $fieldinfo->name != "Course Name" && $fieldinfo->name != "Schedule")
{
echo '<th>';
echo $fieldinfo->name;
echo '</th>';
}
}
echo '</tr>';
while ($rows = mysqli_fetch_array($reslt))
{
for ($i=0; $i < (count($rows)/2); $i++) {
if($i != 3 && $i != 4 && $i != 5 && $i != 6){
echo '<td>';
echo $rows[$i];
echo '</td>';
}
}
echo '</tr>';
}
echo '</table>';
mysqli_next_result($link);
}
}
// $reslt =mysqli_query($link, $qry);
?>
<input type=hidden name=date value='<?php echo date("F d, Y",strtotime($date));?>'>
<input type="hidden" name="outy" value="<?php echo $sql; ?>">
<input type="submit" name="export" value="Export" class="submit" />

SELECT SUM data rank and Resource id #9 error PHP

I have a website in which logged in members are stored under a table called ‘users’
‘users’ table
users_sales_guild_id | users_first_name | users_surname
555 | Jane | Smith
333 | John | Smith
111 | Mike | Myers
The users have sales data in a 'sales_points' field which is in a separate table called ‘sales_list’.
‘sales_list’ table
sales_id | users_sales_guild_id | sales_points | sales_entry_date
1 | 555 | 50 | 2013-02-31 00:00:00
2 | 333 | 30 | 2013-02-31 00:00:00
3 | 111 | 10 | 2013-02-31 00:00:00
4 | 555 | 50 | 2013-03-31 00:00:00
5 | 333 | 30 | 2013-03-31 00:00:00
6 | 111 | 10 | 2013-03-31 00:00:00
Essentially what I am trying to do is a query which:
A. Calculates the total amount of 'sales_points' for each user from 'sales_list'
B. Lists 100 users with the user having the most points at the top, then ranking the next highest below and so on...
C. Im not after a ranking number, just the order itself.
With the code below I am getting 100 users printing ok, however I am getting a ‘Resource id #9’ message in the ’Total Points’ column when it prints. Can anyone help?
What I am trying to print
Jane Smith | 100
John Smith | 60
Mike Myers | 20
Code:
<?php
require_once ('config.inc.php');
$page_title = '';
include ('header.html');
if (!isset($_SESSION['users_id'])) {
$url = 'http://' . $_SERVER['HTTP_HOST']
. dirname($_SERVER['PHP_SELF']);
// Check for a trailing slash.
if ((substr($url, -1) == '/') OR (substr($url, -1) == '\\') ) {
$url = substr ($url, 0, -1); // Chop off the slash.
}
// Add the page.
$url .= 'login.php';
ob_end_clean(); // Delete the buffer.
header("Location: $url");
exit(); // Quit the script.
}?>
<h1>Rankings</h1>
<?php require_once ('database.php'); // Connect to the database.
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$query = "SELECT us.users_id, us.dealership_id, us.users_sales_guild_id, us.users_first_name, us.users_surname, us.users_type,
de.dealership_id, de.users_dealer_name, de.class , de.region, de.state, de.users_dealer_code_id, de.users_dealer_code_new_id, de.users_model, de.pma
FROM users AS us, dealerships AS de
WHERE us.dealership_id = de.dealership_id
ORDER BY ’$total’ DESC
LIMIT 100";
$result = #mysql_query ($query);
// Table header.
echo '<table width="680"cellpadding="5" cellspacing="1" style="font-size:12px;">
<tr class="orangehead">
<td align="center"><b>Member</b></td>
<td align="center"><b>Title</b></td>
<td align="center"><b>Dealer</b></td>
<td align="center"><b>Category</a></b></td>
<td align="center"><b>Dealer Code</a></b></td>
<td align="center"><b>Total Points</a></b></td>
</tr>';
// Fetch and print all the records. echo '<td align="left"><strong>' . $row['sp_invoice_no'] . '</strong></td> ';
$bg = '#ffffff'; // Set the background color.
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$bg = ($bg=='#eaeced' ? '#ffffff' : '#eaeced'); // Switch the background color. New: ' . $row['users_sales_guild_new_id'] . '
// $entries = floor($row['sp_entry_amount']/200);
echo '<tr bgcolor="' . $bg . '">';
echo '<td align="left"><strong>' . $row['users_first_name'] . ' ' . $row['users_surname'] . '</strong></td> ';
echo '<td align="center">' . $row['users_type'] . ' </td>';
echo '<td align="center"> ' . $row['users_dealer_name'] . ' </td>';
echo '<td align="center"> ' . $row['class'] . ' </td>';
echo '<td align="center"> ' . $row['users_sales_guild_id'] . ' </td>';
echo '<td align="center"> ' . $total . '</td>';
echo '</tr>
';
}
echo '</table>';
mysql_free_result ($result); // Free up the resources.
mysql_close(); // Close the database connection.
include ('footer.html'); // Include the HTML footer.
?>
You don't fetch you first result. Fetch it as an array (mysql_fetch_array()) for example.
// Execute query
$total_query = mysql_query("SELECT SUM(sales_points)
FROM sales_list, users
WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'");
// Fetch result
$total = mysql_fetch_array($total_query);
You echo this:
$total = mysql_query("SELECT SUM(sales_points) FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
The variable $total contains the result of the query, which is a Resource. You should use mysql_fetch_assoc or a similar function to extract the result itself. It's best to give the SUM(sales_points) an alias, i.e. AS total_sales_points so you can fetch is easily.
By the way, the mysql_*-extension is soon-to-be deprecated. Good alternatives include MySQLi and PDO.
$query = mysql_query("SELECT SUM(sales_points) as points FROM sales_list,users WHERE sales_list.users_sales_guild_id = users.users_sales_guild_id
AND sales_entry_date
BETWEEN '2013-10-01 00:00:00' AND '2013-11-30 23:59:59'
" );
$row = mysql_fetch_object($query);
$total = $row->points;
You are echoing the mysql resource, you first need to fetch the results, then you can echo them.

PHP MySQL: Display all column names from a given table and the values for any single given row

I am trying to parse all the column fields and data of a single row of any selected mysql table.
The reason behind this is to make a 'universal'-like Table parser of any given single row.
For example I have this table 'tbl1':
+----+---------------------+---------+---------+--+
| id | date | amounta | amountb | |
+----+---------------------+---------+---------+--+
| 1 | 2014-02-28 05:58:41 | 148 | 220 | |
+----+---------------------+---------+---------+--+
| 2 | 2014-01-20 05:58:41 | 50 | 285 | |
+----+---------------------+---------+---------+--+
| 3 | 2014-03-30 05:58:41 | 501 | 582 | |
+----+---------------------+---------+---------+--+
and I want to be able to select table tbl1 and id = 1 to export into:
<label>id <input type="text" value="1"/></label>
<label>date <input type="text" value="2014-02-28 05:58:41"/></label>
<label>amounta <input type="text" value="148"/></label>
<label>amountb <input type="text" value="220"/></label>
This is what I have thus far:
if ($_GET['p'] && $_GET['table']) {
include ("con.php");
$query = "SELECT * FROM `" . $_GET['table'] . "` WHERE id = '" . $_GET['p'] . "'";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$fields[] = $row['0'];
$p = $row;
}
$fields = array();
$res = mysql_query("SHOW COLUMNS FROM `" . $_GET['table'] . "`");
while ($x = mysql_fetch_assoc($res)) {
$fields[] = $x['Field'];
}
foreach($fields as $f) {
foreach($p as $obj) {
echo '<label>' . $f . ' <input type="text" value="' . $p[$f] . '"></label>';
};
}
mysql_close();
}
The problem I'm sure is somewhere between the foreach looping. I know its totally wrong but im not quite sure how to solve this problem.
Basically the idea is to select all column names from $_GET['table'] and for each column name find its value where id = $_GET['p'];
if $p is a single-level array like
Array (
'field1' => 'value1',
'field2' => 'value2',
...
)
and $fields is an array like this
Array (
0 => 'field1',
1 => 'field2',
...
)
Then this should work
foreach($fields as $f) {
echo '<label>' . $f . ' <input type="text" value="' . $p[$f] . '"></label>';
}
Use mysql_fetch_field.
$fields = array();
while($f = mysql_fetch_field($query)) $fields[] = $f->name;
In this way you can get all field names, works for any kind of query rather than just SELECT *

How do I update a row in the database with the data from website?

I am trying to assigned each student with a company from a drop down list and have it updated in the database under the correct student.
So basically, this is how my website looks like.
___________________________________________________________________
| Student ID | Admin No | Student Name | Company List |
| 1 | 1234 | ABC | <drop down list> |
| 2 | 2345 | BCD | <drop down list> |
| 3 | 3456 | CDE | <drop down list> |
| 4 | 4567 | DEF | <drop down list> |
And this is the codes for the table above.
<form name="IT" action="getIT_now.php" method="post">
<table cellspacing="0">
<tr>
<th>Student ID</th>
<th>Admin Number</th>
<th>Student Name</th>
<th>GPA</th>
<th>Gender</th>
<th>Company List</th>
</tr>
<?php
$con=mysqli_connect("....","....","....",".....");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//create the query
$result = mysqli_query($con,"SELECT student_id, admin_no, name, GPA, gender FROM student_details WHERE jobscope1= 'Information Technology' ORDER BY `GPA` DESC; ");
$result2 = mysqli_query($con,"SELECT job_title FROM job_details WHERE jobscope='Information Technology' ORDER BY `job_title` ASC;");
/*options sections start*/
$options= '';
while ($row2 = mysqli_fetch_assoc($result2))
{
$options .='<option value="'. $row2['job_title'] .'"> '. $row2['job_title'] .'</option>';
}
/*options sections end*/
//return the array and loop through each row
while($row = mysqli_fetch_assoc($result))
{
$studentid = $row['student_id'];
$adminno = $row['admin_no'];
$name = $row['name'];
$gpa = $row['GPA'];
$gender = $row['gender'];
echo "<tr>";
echo "<td>" . $studentid . "</td>";
echo "<td>" . $adminno . "</td>";
echo "<td>" . $name . "</td>";
echo "<td>" . $gpa . "</td>";
echo "<td>" . $gender . "</td>";
echo "<td><select name='ddl' onclick='if(this.value != '') { myform.submit(); }'>".$options."</select></td>";
}
echo "</tr>";
?>
</table>
<input type='submit' value='Submit Pick' />
</form>
Now this form will actually go to another page since I have include a form action.
So the codes in this getIT_now.php page is
<?
$con=mysqli_connect("...","....","....","....");
if (!$con)
{
die('Could not connect: ' . mysqli_errno());
}
$ddlvalues = $_POST['ddl'];
$studentid = $_POST['student_id'];
$query = mysqli_query($con, "INSERT INTO student_details(company) VALUES('" . $ddlvalues . "');");
?>
However, when I check the database, only the first option in the drop down list is reflected in a new row. I have tried to use the UPDATE query statement, but it is wrong.
This is the query for the UPDATE statement.
UPDATE student_details SET company = '" . $ddlvalues . "' WHERE student_id = '" . $studentid . "';
The problem I'm having right now is actually:
How do I make Student ID on the website and in the database to match so that it can update correctly?
Why is it that only the first option in the drop down list is reflected when I use the INSERT query?
I am quite new to PHP so I am really struggling with this.
You don't have an input that holds the student_id, i.e $_POST['student_id'] is not set, also you would have to validate the user inputs before you pass them to query, You can use prepared statements,
Try with a hidden field like
echo '<input type="hidden" name="student_id" value="'.$studentid.'"/>';

I want to show data from one column of mysql table in a drop down list,But in drop down it show every entry two times.But i want it only one time

|===============================|
| customer_id | customer_name |
|===============================|
| 1 | vick |
| 2 | bawa |
| 3 | smith |
| 4 | goldy |
| 5 | jojo |
=================================
There are two columns in table. I have applied the following query.But it shows every name two times but i want every name one time in dropdown.
Please tell me how to show every name only one time in drop down....My second question is that..i want to take the selected value to next page....But first problem is that how to show every name from customer_name single time...But it shows every name two times....Thank you sir
<table>
<tr>
<td>customer name</td>
<td><select name="customer_name">
<?php
$query = 'SELECT customer_id, customer_name FROM customer_table';
$result = mysql_query($query, $db) or die(mysql_error($db));
while ($row = mysql_fetch_assoc($result))
{
foreach ($row as $value)
{
echo '<option value="' . $row['customer_id'] . '"> ' . $row['customer_name'] . '</option>';
}
}
?>
</select></td>
</tr>
</table>
your suolution :
no need of for each...
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['customer_id'] . '"> ' . $row['customer_name'] . '</option>';
}
You have 2 loops here which is making it to be repeated.Just remove foreach($row as $value) loop and you will get the result.
while ($row = mysql_fetch_assoc($result))
{
echo '<option value="' . $row['customer_id'] . '"> ' . $row['customer_name'] . '</option>';
}
This would work .

Categories