Grouping values of table elements by id - php

I'm making a webpage where one can modify points of players.
Table structure is like this
Contestant (text), Points(input text field with default value current player's points), submit
now, in mysql db every contestant has an id, what i want to do is when someone changes a player's points and clicks submit to be able to relate by id which player got submited.
This is organized in an html table and i have no clue how to group the data. Anyone can help?
Okay not sure if this is correct, cause i wrote it really fast, but I hope you'll get the idea.
$query = "SELECT `con`.`id`, `av`.`name` as `contestant`, `con`.`points` as `points`
FROM `contestants` as `con`
JOIN `mydb`.`avatars` as `av`
WHERE `con`.`boardId`=$id";
$result = mysql_query($query) or die("ERROR:QUERY_FAILED " . mysql_error()); echo "<h4>Boards List</h4><br/>";
$numFields = mysql_num_fields($result);
echo "<table>";
echo "<tr>";
for($i = 0; $i < $numFields; $i++)
{
if(mysql_field_name($result,$i) != 'id')
{
echo "<th>";
echo mysql_field_name($result,$i);
echo "</th>";
}
}
echo "</tr>";
while($row = mysql_fetch_row($result))
{
echo "<tr>";
for($i = 0; $i < $numFields; $i++)
{
if(mysql_field_name($result, $i) == 'points')
{
echo "<td><input name='points' type='number' min='0' max='45' value='$row[$i]'></td>";
}
else
{
echo "<td>$row[$i]</td>";
}
}
echo "<td>
<input type='button' value='Save' onclick='SavePlayersData(this)'>
</td>";
echo "</tr>";
}
echo "</table>";
What I need is a way to tell to javascript which input field it should process as the players points being saved. hope it makes sense. (btw, there will be more fields than just points. This is just an example.

Name your form fields with values like "player1_points", "player2_points", etc. On the server, loop through all values received, looking for these fields. Welcome to 1993.
EDIT: get thyself a toolkit, like extjs, which handles all this nonsense (and much more) automatically. ext4js is a huge improvement over previous versions.

Related

Updating data in MySQL database based on checked dynamic checkboxes in the table

I'm sorry about my question, but I'm starting with PHP and I want to ask you for a help with my problem.
In my web application I work with a table, which has a dynamic count of rows based on the number of rows in a source table in MySQL database. In the application should be a checkbox in each row of the table. After clicking on the submitt button there should be update of records in the source table and it should be update just of these records where the checkboxes were checked.
The table in the application looks simillar like in the picture.
The primary key in the source table is in the column NUMBER. As a first try I simulated that after clicking on submitt button there will be shown the msgbox with the values from the column NUMBER for the rows, where the checkboxes were checked.
<html>
<head>
<title>APLICATIONa</title>
<script type="text/javascript">
function GetSelected() {
//Reference the Table.
var grid = document.getElementById("Table");
//Reference the CheckBoxes in Table.
var checkBoxes = grid.getElementsByTagName("INPUT");
var message = "\n";
//Loop through the CheckBoxes.
for (var i = 0; i < checkBoxes.length; i++) {
if (checkBoxes[i].checked) {
var row = checkBoxes[i].parentNode.parentNode;
message += " " + row.cells[1].innerHTML;
message += "\n";
}
}
//Display selected Row data in Alert Box.
alert(message);
}
</script>
</head>
<body>
<?php
$values = mysql_query("SELECT * FROM table_03_2020");
echo "<br><form action='main.php' method='POST'>";
echo "<input type='submit' name='button' value='Get Selected' class='btn btn-primary' onclick='GetSelected()' />";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
echo "<td><input type='checkbox' name='cbox[]' ></td>";
echo "<td><font color='red'>".$zaznam["number"]."</font></td>";
echo "<td>".$zaznam["name"]."</td>";
echo "</tr>";
endwhile;
echo "</table><br>";
echo "</form>";
?>
</body>
</html>
The msgbox is just an illustration. Instead of msgbox, I need that after clicking on the submit button, there should be an update for these records in the source table, where the checkboxes were selected (so of these records, which are now shown in the msgbox). So I need something like:
"UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
There'll be also a second submit button and after clicking on it, there should be another different update. So after clicking on the second button, I need something like:
"UPDATE table_03_2020 SET column1 = 'ab' where NUMBER in ('values of NUMBER from rows, where the checkbox was checked)"
I'm sorry if my question is not so clear, but I'd really appreciate any help.
Thank you very much.
Add key values with the number to the cbox form variable:
echo "<td><input type='checkbox' name='cbox[" .$zaznam["number"]. "]' ></td>";
Then use the following PHP to get the number list.
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
The addslashes function is for SQL Injection protection.
This will create a list with comma separated numbers.
Than, you can insert it in the the SQL query.
UPDATE table_03_2020 SET column1 = 'xy' where NUMBER in ('. $checked_list .')
If you assign a value to the checkboxes, like this:
<input type='checkbox' name='cbox[]' value='{$zaznam["number"]}' >
When the form is submitted the cbox variable will contain an array of these numbers, which means that you can process them like this:
<?php
include 'db.php'; #your database connection!!!
$sql='update table_03_2020 set `column1`="XY" where `column2` in ( ? )';
$stmt=$db->prepare( $sql );
$ids=implode(',',$_POST['cbox']);
$stmt->bind_param('s',$ids);
$stmt->execute();
?>
Note that the above has not been tested so there might be errors but I hope it'll give the idea.
Thank you, I tried to improve the part of the code to:
echo "<input type='submit' name='buttonupdate' value='Get Selected' >";
echo "<table id = 'Table' border='0px' bordercolor='silver' cellpadding='1' cellspacing='2' width='100%'>";
echo "<tr bgcolor='#EEEEEE' height='45px'><th></th><th><b>NUMBER</b></th><th><b>NAME</b></th></tr>";
while ($zaznam=MySQL_Fetch_Array($values)):
echo "<tr onmouseover=\"highlight_row(this, 1, '#F2F2F2');\" onmouseout=\"highlight_row(this, 0, '#F2F2F2');\">";
if ($_POST["buttonupdate"]) {
if (isset($_POST["cbox"])) {
$checked = array();
foreach($_POST["cbox"] as $number => $val) {
$checked[] = addslashes($number);
}
$checked_list = implode(",", $checked);
}
}
echo "<td><input type='checkbox' name='cbox[" .$zaznam["cflot"]. "]' ></td>";
It didn't work, there was no update. Did I edited the code incorrectly?
Actually I forgot to mention the second button, so I edited my first post. Would it be possible to distinguish between the first and the second button? Thank you very much for any help.

Organise seats into tablerows in html output with PHP

I'm putting together something that's mean to allow for a user to book seats for a cinema showing. The row and seat numbers for every showing are stored in the database. I'm currently extracting them in the following method so that users can click on a seat button to select that seat for their booking:
echo "<form>";
echo "<table>";
while($row = mysqli_fetch_assoc($result)){
$rownum = $row['row'];
$seat = $row['seat'];
echo "<tr><td><button type=\"submit\" name=\"seatsel\" value=\"$rownum$seat\">$rownum$seat</button></td></tr>";
}
echo "</table>";
Right now this just outputs html showing all of the buttons as a single row in the table. I'd like the output to show seating across a single table row for every one of the table rows in the cinema screen. I'm not sure how to do this exactly given that each row is of differing lengths. E.g row A has twelve seats while row C has eight.
What would be the best way of accomplishing this?
You could easily update your code so that you will get a new table row every time the mysql row has another value. One thing to note is that you might want to add (depending on whether you're already sorting your results) the following ORDER BY row,seat.
echo "<form>";
echo "<table>";
echo "<tr>";
while($row = mysqli_fetch_assoc($result)){
if (!isset($oldrownumber)) $oldrownumber = $row['row'];
else if ($oldrownumber != $row['row']) {
echo "</tr><tr>";
$oldrownumber = $row['row'];
}
$rownum = $row['row'];
$seat = $row['seat'];
echo "<td><button type=\"submit\" name=\"seatsel\" value=\"$rownum$seat\">$rownum$seat</button></td>";
}
echo "</tr>";
echo "</table>";

PHP MySQL save a row id to a database based on user checkbox

I am attempting to get the sql row that a user checks with a checkbox and post the id to a script that will save the users selected rows to a db so they can pull "saved" rows at a later data.
Below is my code -- the issue is when I post the checkbox value it is appearing as "1" and I am not sure why this is happening. All checkbox values are appearing as "1".
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$connection = mysql_connect('198.71.225.63:3306', 'newmslsuper', '');
mysql_select_db('msl_data');
$query = "INSERT INTO searches (ID, school, type) VALUES('$current_user->ID', '$school', '1')";
mysql_query($query);
$search = mysql_query("SELECT * FROM `data` WHERE `school` LIKE '%$school%'");
$count=mysql_num_rows($search);
if ($count==0) {
echo 'Sorry your search for'; echo " $school "; echo 'returned no results. Please try again.';
}
else {
$fields_num1 = mysql_num_fields($search);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// printing table headers
for($i=0; $i<$fields_num1; $i++)
{
$field1 = mysql_fetch_field($search);
echo "<th>{$field1->name}</th>";
}
echo "</tr>\n";
// printing table rows
while($row = mysql_fetch_array($search)){
foreach($row as $rowarray)
while($row1 = mysql_fetch_row($search)){
echo "<tr>";
echo "<td><input type='checkbox' value='$rowarray' name='cell'></td>";
// $row is array... foreach( .. ) puts every element
// of $row1 to $cell1 variable
foreach($row1 as $cell1)
echo "<td>$cell1</td>";
echo "</tr>\n";
}
}
}
echo "<input type='submit' value='SAVE'>";
mysql_close(); //Make sure to close out the database connection
Your checkboxes should be as array as they are multiple. The reason why you get them all as 1 as they override each other.
<form method='post' id='form' action='page.php'>
<input type='checkbox' name='checkboxvar[]' value='Option One'>1
<input type='checkbox' name='checkboxvar[]' value='Option Two'>2
<input type='checkbox' name='checkboxvar[]' value='Option Three'>3
<input type='submit'>
</form>
<?php
if(isset($_POST['submit']){
$v = $_POST['checkboxvar'];
foreach ($v as $key=>$value) {
echo "Checkbox: ".$value."<br />";
}
}
?>
TBH, this thing was a mess. The base of your problem was a) only having a single named element (as the other answer pointed out) and b) trying to give it an array as a value. But even after fixing that this was never going to work.
You had your database results inside four separate loops, I don't know what the thinking was there. As well, if you presented me with this web page, I could easily erase your entire database with a single click.
Here's what it looks like after 5 minutes of work. I'd still not call this a reasonable script, but hopefully it will give you something to learn from. You need to make a priority to learn about preventing SQL injection, and the first way to do this is to stop using a database engine that's been unsupported for 5 years. PDO is the easiest alternative as it's built into PHP for nearly a decade now. It provides convenient methods for dumping a result set into an array easily.
<html>
<head>
<link rel="stylesheet" type="text/css" href="results.css">
</head>
</html>
<?php
require('./wp-blog-header.php');
$current_user = wp_get_current_user();
$school = $_POST['school'];
$db = new PDO("mysql:host=198.71.225.63;dbname=msl_data", "newmslsuper", "");
$stmt = $db->prepare("INSERT INTO searches (ID, school, type) VALUES(?,?,?)";
$stmt->execute(array($current_user->ID, $school, 1));
$stmt = $db->prepare("SELECT * FROM `data` WHERE `school` LIKE ?");
$stmt->execute(array("%$school%"));
// put it in an array. presto!
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($result) === 0) {
echo "Sorry your search for '$school' returned no results. Please try again.";
}
else {
$fields = array_keys($result[0]);
echo "<form action='save.php' method='post'>";
echo "<p>Check the box next to a Scholarship you would like to save and hit the SAVE button.<p/><table><tr><th>Save Search</th>";
// assume "id" field is first
unset($fields[0]);
// printing table headers
foreach($fields as $field) {
echo "<th>$key</th>";
}
echo "</tr>\n";
// printing table rows
// just one loop
foreach($result as $row) {
echo "<tr>";
// assume the column is named "id"
echo "<td><input type='checkbox' value='$row[id]' name='cell[]'></td>";
unset($row["id"]);
foreach($row as $cell) {
echo "<td>$cell</td>";
}
echo "</tr>\n";
}
echo "<input type='submit' value='SAVE'>";
echo "</form>";
}
?>

PHP Delete Button

I recently started learning PHP on my own and started to use MySQL and Apache as well. I made a basic table in MySQL, and using some PHP code, I displayed the table in a HTML table in a browser. Now I'd like to add a delete button beside each row, and when clicked, it would delete that row. I am very new to this, and I'm just practicing. Could anyone please help me? This is the code I have so far:
From: phpcode on Pastebin
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
mysql_connect('localhost', 'root', '');
mysql_select_db('testdb');
$result = mysql_query('select * from products');
$numrows = mysql_numrows($result);
//****************************************************************
print "<table border = 3 style = width:400px>";
for($i = 0; $i < $numrows; $i++)
{
$row = mysql_fetch_row($result);
print "<tr>";
foreach($row as $cell)
{
print "<td>";
print $cell;
print "</td>";
}
print "</tr>";
}
print "</table>";
mysql_close();
?>
I also have a delete.php page, but I really don't know where to start. I've looked for online tutorials, and many say different ways.
Just add another "" inside the loop with delete text and pass the id for that
for($i = 0; $i < $numrows; $i++)
{
$row = mysql_fetch_row($result);
print "<tr>";
foreach($row as $cell)
{
print "<td>";
print $cell;
print "</td>";
print "<td>";
print "DELETE";
print "</td>";
}
print "</tr>";
}
Let say your table like below;
$result = mysql_query('select * from products');
print "<table>";
while ($row = mysql_fetch_assoc($result)) {
print "<tr><td>" . $row["name"] . "</td><td>" . $row["surname"] . "</td><td>Delete</td></tr>";
}
print "</table>";
Here, while iterating your row, you need to put $row["id"] in delete link id.
And in your delete.php
$id = $_GET["id"];
// Delete sql here. Do not forget to validate id here.
header("Location: index.php"); // I assume, table page is this
In your table products you need a field with different value for each register, name it id or whatever you want.
If you have table but doesn't have that field, good option would be and auto_increment field.
Code for add an auto_increment field:
ALTER TABLE `products` ADD COLUMN `id` INT AUTO_INCREMENT UNIQUE FIRST;
Then id would be unique for each register and you don't need to worried about it because you don't need to insert it, it is generated automatically.
print "<table border = 3 style = width:400px>";
for($i = 0; $i < $numrows; $i++)
{
$row = mysql_fetch_row($result);
print "<tr>";
foreach($row as $cell)
{
print "<td>";
print $cell;
print "</td>";
}
print "<td><a href='delete.php?id=".$row["id"] ."' > delete </a> " ;
print "</tr>";
}
$row["id"] is the id of register you want to delete.
in delete.php
$id = $_GET["id"];
$delete = " DELETE from yourTable where id = ". $id ;
mysq_query ( $delete ) ;
PD: Use mysqli_

PHP syntax help on if statement

I'm trying to determine the right syntax from what I'm trying to do with MySQL. I'm basically saying that if a value in a certain column of a row of a table is equal to some session variables, I want to echo out info.
I have a table with subject, description and user. User is set by taking the current user's first name and last name and inserting it into the table under user. This is done by the following code:
$sql="INSERT INTO tbl_name (subject, description, user)
VALUES
('$_POST[subject]','$_POST[description]','$_SESSION[firstname] $_SESSION[lastname]')";
Then once I'm calling this data back out, I want to basically allow the user to delete content that they submitted themselves. The first step for me is to be able to display it in the table. I believe this is just syntax error, but I've confused myself now with how things are set up:
$sql = "SELECT * FROM tbl_name ORDER BY subject, description
LIMIT {$startpoint},{$limit}";
$result = $mysqli->query($sql);
$num_rows = mysqli_num_rows($result);
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME EXAMPLES:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if('$field->user' == '$_SESSION[firstname] $_SESSION[lastname]'){
echo '<td>You can delete this</td>';
}
}
I figured the $field->user would equal $_SESSION[firstname] $_SESSION[lastname] because that's how it was initially submitted to the table (without the '.' for concatenation).
Any help would be appreciated. Thanks!
EDIT
Here's the result of my table output code. The results are actually being display with $cell instead of from within the for loop I believe. I've added the if statement in after the but it doesn't seem to recognize echo "<td>".$field->user."</td>"; which makes me think that that is where the problem lies. What I would like to do is be able to add the if statement in a immediately after `echo {$field->user}"; to keep the code clean. I think I've confused myself thoroughly:
if($num_rows>0){
$field_num = $mysqli->field_count;
echo "<h1>HERE ARE SOME JOBS:</h1>";
echo "<table border='0'><tr>";
for($i=0; $i<$fields_num; $i++)
{
$field = mysql_fetch_field($result);
echo "<td>{$field->subject}</td>";
echo "<td>{$field->description}</td>";
echo "<td>{$field->user}</td>";
if($field->user == $_SESSION[firstname]." ".$_SESSION[lastname]){
echo '<td>You can delete this</td>';
}
else{
echo "<td>".$field->user."</td>";
echo "<td>".$_SESSION[firstname]." ".$_SESSION[lastname]."</td>";
}
}
echo "</tr>\n";
while($row = mysqli_fetch_row($result))
{
echo"<tr>";
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>\n";
}
mysqli_free_result($result);
}
else{
echo 'There are no jobs!';
}
I re-wrote the code in a way that was a little bit easier for me to understand (though maybe not the shortest way to do it):
while($row = mysqli_fetch_array($result))
{
echo"<tr>";
echo"<td>".$row['subject']."</td>";
echo"<td>".$row['description']."</td>";
echo"<td>".$row['user']."</td>";
if($row['user'] == $_SESSION['firstname']." ".$_SESSION['lastname']){
echo"<td>You can delete this</td>";
}
else{
echo"<td>Code didn't work</td>";
}
echo "</tr>\n";
}
It ended up working this way. If there's way to do this shorter then feel free to post it here otherwise thanks for the help!

Categories