In my HTML code I have a table but with no data rows initially loaded, only a header and column labels. Upon clicking a button, a number of rows are loaded into this table depending how many rows are selected from the database in a SQL statement. In this situation, if my team has seven registered players in the database, my table will display seven rows (via PHP echo statements). In each row I have a checkbox with the players name and text input boxes.
This is the jQuery that adds rows once the post-result button is clicked:
$("#post-result").click(function(){
$("#post-result").hide();
$("#confirm-result").show();
$("#cancel").show();
$("#home-player-count").show();
$("#home-score").html("<input class='form-input f-score' id='home-score-input' type=number name=home_score maxlength=2>");
$("#away-score").html("<input class='form-input f-score' id='away-score-input' type=number name=away_score maxlength=2>");
$("#stats-home").after(<?php
echo "\"";
$i = 0;
$sql2 = mysqli_query($link, "SELECT * FROM user_accounts WHERE ps4_club= '" . $myclub . "'");
while ($row = mysqli_fetch_array($sql2, MYSQLI_ASSOC))
{
$i++;
echo "<tr id='player-".$i."'><td class='match-stats-name'><input type='checkbox' class='f-player' checked='true' value='" . $row['username'] . "' name='home_player_".$i."'>". $row['username'] ."";
echo "<td><input class='form-input f-stats single' maxlength=1 name='home_player_".$i."_rating_1'> . <input class='form-input f-stats single' maxlength=1 name='home_player_".$i."_rating_2'></td>";
echo "<td><input class='form-input f-stats single' maxlength=1 name='home_player_".$i."_goals'></td>";
echo "<td><input class='form-input f-stats single' maxlength=1 name='home_player_".$i."_assists'></td>";
echo "<td><input class='form-input f-stats' maxlength=2 name='home_player_".$i."_tackles_won'> / <input class='form-input f-stats' maxlength=2 name='home_player_".$i."_tackles_made'></td></tr>";
}
echo "\"";
?>)
<?php
$_SESSION["match_id"] = $id;
$_SESSION["player_count"] = $i;
$_SESSION["team"] = $team;
?>
$("#stats-home").after is where the rows get added.
The problem I'm coming across is when I'm trying to input this data from the table into my database. This is the bit of PHP code that is loaded once I click the confirm-result button of my form:
<?php
include "../config.php";
if (isset($_POST["confirm_result"]))
{
session_start();
for ($i = 1; $i <= $_SESSION["player_count"]; $i++)
{
$sql = $link->prepare("INSERT INTO ps4_apl_1_stats (match_id, team, name, rating, goals, assists, tackles_won, tackles_made)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
$sql->bind_param("issiiiii", $match_id, $team, $name, $rating, $goals, $assists, $tackles_won, $tackles_made);
$match_id = $_SESSION["match_id"];
$team = mysqli_real_escape_string($link, $_SESSION["team"]);
$name = "test_".$i."_player";
$rating = $_POST["home_player_".$i."_rating_1"];
$goals = $_POST["home_player_".$i."_goals"];
$assists = $_POST["home_player_".$i."_assists"];
$tackles_won = $_POST["home_player_".$i."_tackles_won"];
$tackles_made = $_POST["home_player_".$i."_tackles_made"];
$sql->execute();
$sql->free_result();
}
header("Location: ../match.php?id=".$_SESSION['match_id']);
}
else
{
header("Location: ../match.php?id=".$_SESSION['match_id']);
}
?>
What this code does is it loops through each row in the table by incrementing the $i variable. In each iteration it'll put the data from the input boxes into variables, which are then placed into the prepared SQL statement. Each row's input boxes have names that are numbered by what row number they are, for example:
ROW 1: home_player_1_goals, home_player_1_assists
ROW 2: home_player_2_goals, home_player_2_assists
ROW 3: home_player_3_goals, home_player_3_assists
When I try to submit this form, I get a lot of "Unidentified index" notices, like this:
Notice: Undefined index: home_player_1_goals in C:\Apache24\htdocs\script\match_post.php on line 20
For some reason it's not finding the POST variables of any of the input boxes that were inserted dynamically into the page via echo statements. It has no trouble finding $_POST["confirm_result"] since that input box is loaded into the page right at the beginning.
How do I get around this? It's pretty much not recognizing any of the input boxes that have been loaded in via echo statements.
I also dumped the $SESSION and $POST variables using print_r:
print_r($_SESSION): Array ( [email] => my_email#hotmail.com [userid] => 43 [xbox_club] => [ps4_club] => Wrecking Crew [match_id] => 3 [player_count] => 7 [team] => home )
print_r($_POST): Array ( [confirm_result] => Confirm Result )
It only shows the confirm_result button which is loaded onto the page initially.
I also have another question:
How would I go about skipping the insertion of a row depending on if it's checked or not? In each row I have a checkbox. When this checkbox is disabled, that rows input boxes will all be disabled. What would be the best way to skip this row? At the moment my code goes through every single row and enters the data, regardless of whether the input boxes are disabled or not.
Thanks in advance!
UPDATE - here is a single row that gets generated after the "post-results" button is clicked:
<tr id="player-1">
<td class="match-stats-name"><input type="checkbox" name="home_player_1" value="Syrian2nv" checked="true" class="f-player">Syrian2nv</td>
<td><input name="home_player_1_rating_1" maxlength="1" class="form-input f-stats single"> . <input name="home_player_1_rating_2" maxlength="1" class="form-input f-stats single"></td>
<td><input name="home_player_1_goals" maxlength="1" class="form-input f-stats single"></td>
<td><input name="home_player_1_assists" maxlength="1" class="form-input f-stats single"></td>
<td><input name="home_player_1_tackles_won" maxlength="2" class="form-input f-stats"> / <input name="home_player_1_tackles_made" maxlength="2" class="form-input f-stats"></td>
</tr>
Where is your form in relation to #stats-home? You're telling jQuery to add those form inputs after it, so if your form is inside it, they will miss the form.
If I were you, I would simplify the whole jQuery call you've got up there by outputting your fields when you load your page normally, but applying a class to the table row which you will tell to be invisible:
echo "<tr class='player-information' id='player-".$i."'><td class='match-stats-name'><input type='checkbox' class='f-player' checked='true' value='" . $row['username'] . "' name='home_player_".$i."'>". $row['username'] ."";
<style type="text/css">
.player-information {
display: none;
}
</style>
Then in your jQuery you replace $("#stats-home").after() with:
$('tr.player-information').show();
Not sure if this will fix your problem or not, but at least you'll know that your form elements are there, in the DOM and being output in the correct place (p.s. if this doesn't help, post the resulting HTML output on your page after you click your button so we can see what's happening)
--edit-- also, post the javascript produced when you load the page i.e. after PHP's done its thing
I'll answer the second question. As far as the first one I'm betting that the html isn't quite right after the jQuery insert based on the fact that the var_dump on the $_POST is empty.
The second question, skip a row if the checkbox isn't checked. So if your html is like this:
<tr>
<td><input type="checkbox" name="checkme[]"></td>
<td><input type="text" name = "homePlayerRating[]"></td>
<td><input type="text" name="homePlayerGoals[]"></td>
</tr>
<tr>
<td><input type="checkbox" name="checkme[]"></td>
<td><input type="text" name = "homePlayerRating[]"></td>
<td><input type="text" name="homePlayerGoals[]"></td>
</tr>
Then in the php when you process it do:
foreach($_POST['homePlayerRating'] as $key=>$homePlayerRating){
if(isset($_POST['checkme'][$key])){
//now you know that row was checked
$playerRating = $_POST['homePlayerRating'][$key];
$goals = $_POST['homePlayerGoals'][$key];
}
}
EDIT: This is dead wrong. I'm not sure what I was thinking. The $_POST['checkme'] array won't match the rest of the line. It isn't added to the $_POST array if it's not checked. For example if you check the checkbox in the third line down the
$_POST['homePlayerTating']
key will 2 but the
$_POST['checkme']
key will be zero because it isn't added to that array unless it's checked so it will be the first item in the $_POST['checkme'] array.
Related
I am trying to displaying the input fields depending upon the what outputs are coming from the database. Please share any idea or logic in this. I have more than 25 fields.
Page1.php
I have Name(Text type), Email(Email type), gender(Radio), country(Select dropdown), Address( Textarea) in the form. The user will click on check box whatever he needs from the form and click on submit then the value of the fields which he selects will store in the database.
Form page
Page2.php
Here I am displaying the fields which are selected from Page1.php but also I need input type related to which fields come from the database.
For example: In the page1 I choose Name, Email, Country and submitted the form then In page2 I have to display the output <input type="text" name="Name">,<input type="text" name="Name">,<select></select>.
I need to know what logic I have to use it. Can any one help me with the script?
Form code
<form action="" method="post">
<input type="checkbox" name="check-fields[]" value="Name">
<label>Name(Text type)</label>
<input type="checkbox" name="check-fields[]" value="Email">
<label>Email(Email type)</label>
<input type="checkbox" name="check-fields[]" value="Gender">
<label>Gender(Radio type)</label>
<input type="checkbox" name="check-fields[]" value="Select">
<label>Country(Drop down)</label>
<input type="checkbox" name="check-fields[]" value="textarea">
<label>Address(Textare)</label>
<input type="submit" name="submit" value="submit">
</form>
Storing the value in the database
if (isset($_POST['submit'])) {
// prepare and bind
$a=$_POST['check-fields'];
$elements= implode(',',$a);
$sql_elements="INSERT INTO test (elements) VALUES (?)";
$stmt = $conn->prepare($sql_elements);
$stmt->bind_param("s", $elements);
$stmt->execute();
echo "New records created successfully";
$stmt->close();
$conn->close();
}
Page 2
I am getting output but how can I set the input fields?
$sql_fields="SELECT elements FROM test WHERE id=3";
if ($stmt = $conn->prepare($sql_fields)) {
$stmt->execute();
$stmt->bind_result($elements);
while ($stmt->fetch()) {
$arr=explode(",", $elements);
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}
$stmt->close();
$conn->close();
?>
You're trying to create a personalized form for different users if I'm correct, meaning that you will allow a user to generate a form based on a selection of fields the user can choose from.
What you need to do is create a table called "forminputtypes" where you create a row for each different input field you can think of, and want to give the user as a choice to select from. Your table would looke like this:
Id | FieldName | Type | etc ->
-------------------------------
1 | Name | text | ...
2 | Email | email | ...
3 | Gender | radio | ...
You can add more columns in the table to store more information (think of possible values in a radio input or a dropdown).
Now at in Page1.php you select all input types from this table, and display them like you already are. However, the value of these checkboxes will be the corresponding Id value of the record in the database like so:
<input type="checkbox" name="check-fields[]" value="3">
Now when someone chooses the Gender field, you can see in your Page2.php that the user did so by matching his choice '3' to the record in the database. If you want to save this information, you can create another table called UserFormInputFields which will function as a couple table between your user table and the FormInputTypes table.
When you want to display the form in Page2.php, you simply get all the input fields the user chose by selecting on Id from the FormInputTypes table. Since you know the type of each input field (because it's a column in the table) you can display them all correctly.
If you want to do it in core PHP only.Just put if else around the html tags.If value is coming from Database then you show particular tag else nothing. You can modify your page 2 code like.
<?php
$sql_fields="SELECT elements FROM test WHERE id=3";
if ($stmt = $conn->prepare($sql_fields)) {
$stmt->execute();
$stmt->bind_result($elements);
while ($stmt->fetch()) {
$arr=explode(",", $elements);
echo "<pre>";
print_r($arr);
echo "</pre>";
}
}
$stmt->close();
$conn->close();
?>
<form action="" method="post">
<?php if(in_array("Name",$arr)) { ?>
<input type="text" name="name" >
<label>Name</label>
<?php } ?>
<?php if(in_array("Email",$arr)) { ?>
<input type="email" name="email">
<label>Email</label>
<?php } ?>
<?php if(in_array("Gender",$arr)) { ?>
<input type="radio" name="gender" value="Male">
<input type="radio" name="geneer" value="Female">
<label>Gender(Radio type)</label>
<?php } ?>
//.............write other fiels like this.
<input type="submit" name="submit" value="submit">
</form>
I hope this helped.
I am complete beginner
I want to display comma separated values from database in tabular form
From the below image link we can see how the data is getting added separated by commas:
I want to display in tabular form in html/php page just like below:
This is my html page below:-
<form action="insert.php" method="POST">
<div id="items">
<input type="text" placeholder="name" name="user_name[]" />
<input type="text" placeholder="email" name="user_email[]" />
</div>
<input type="button" value="add entry" id="add"/>
<input type="submit" value="submit"/>
Javascript file for adding additional input:-
$(document).ready(function(){
$("#add").click(function (e){
event.preventDefault()
$('#items').append('<div><input type="text" placeholder="Name" name="user_name[]" ><input type="text" placeholder="email" name="user_email[]">'
+'<input type="button" value="delete" id="delete"/></div>');
});
$('body').on('click','#delete',function(e){
$(this).parent('div').remove();
});
});
And below is the PHP code for inserting to database:-
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("dynamic", $con);
$user_name = $_POST["user_name"];
$value = implode(',', $user_name);
$user_email = $_POST["user_email"];
$valueone = implode(',', $user_email);
$sql="INSERT INTO dynamicdata (user_name, user_email)
VALUES
('$value','$valueone')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
echo "1 record added";
mysql_close($con)
?>
Just fetch the data from the table and explode both username and useremail to make array and just loop it and diplay the values.
Below pasted code may help you.
<?php
$ArrUserName=explode($username,','); //exploding the coma separated username to make array of user names
$ArrUserEmail=explode($username,',');//exploding the coma separated user email to make array of user email
echo '<table><tr><td>Name</td><td>EMAIL</td></tr>';
for($i=0;$i<count($ArrUserName);$i++){
echo "<tr>";
echo"<td>".$ArrUserName[$i]."</td>"; //display user name
echo"<td>".$ArrUserEmail[$i]."</td>"; // diaplay user email
echo"</tr>";
}
?>
Please understand this nd try to implement in your code.
Ideally, you would want the username and email stored in a new row for each user. This would make it a lot simpler for yourself.
However, try something like:
<?php
$query = mysql_query('SELECT * FROM dynamicdata LIMIT 1', $con);
$results = mysql_fetch_assoc($query);
$usernames = explode(',', $results['user_name']);
$emails = explode(',', $results['user_email']);
//Now we should be able to loop over them.
for($row = 0; $row <= count($usernames); $row++) {
echo $usernames[$row] . ' : ' . $emails[$row];
}
I haven't had chance to test this, but hopefully it works.
here is what i have so far :sql that gets data from the database, the data is passed through a loop and then displayed with the html code
$sql = "SELECT items_available.title,
items_available.item_number,
items_available.subtitle,
items_available.image_name,
users.username
FROM items_available
INNER JOIN users ON items_available.owner_id = users.user_id
WHERE items_available.status ='pending'
LIMIT $query_limit ;";
$query = mysql_query($sql);
while ($dbData = mysql_fetch_assoc($query)) {
$item_id = $dbData['item_number'];
$sel_title = $dbData ['title'];
$sel_Image = $dbData['image_name'];
$sel_subtitle = $dbData['subtitle'];
$sel_owner = $dbData['username'];
echo "<span style='display:inline-block;width:185px;margin:4px;'>
<a href='#'>
<img src='upload/$sel_Image' style='width:180px; height:160px;' />
<h5 style='display:inline;'>$sel_title </h5><br>
<h7 style='display:inline;'> $sel_subtitle</h7><br>
<h6 style='display:inline;'>Posted by $sel_owner</h6>
</a>|
<div style= \"display:inline-block;\">
<input type=\"checkbox\" id=\"check\" name='item_ids[]' value='1' />
</div>
</span>";
}/
the checkbox below the block of codes should grab the ids of each element so an update to the database is possible.Hope my description is clear enough to be aided
you did nt give any specfic so it is like a guide for what u asking
you need to create a form here with a hidden field
like
<div style= \"display:inline-block;\">
<form method=\"post\">
<input type=\"hidden\" name=\"value\" =". $item_id.">
<input type=\"checkbox\" name=\"update\" value = '1' />
</form>
</div>
php for that ll look like
if (isset($_REQUEST['value']))
{
//update after validation
}
P.S $_REQUEST Deals with both for GET or POST method
it actually depends what you want
You can make the VALUE of the checkbox into the id you want to get back in the $_POST['item_ids'] array.
<div style= \"display:inline-block;\"> ";
echo '<input type="checkbox" id="check" name="item_ids[]" value="' . $item_id . '" />';
echo "</div>
Now in your PHP code you can process them like this, remember checkboxes are only returned in the $_POST/$_GET array if they are actually checked.
I am assuming $_POST.
if ( isset($_POST['item_ids']) ) {
foreach ( $_POST['item_ids'] as $item_id ) {
// do whatever you want to with this information
}
}
So I tried Google before I posted this and didn't find anything that suited my needs. I was hoping you guys could help.
I have a form simple just a drop down box and a checkbox. The drop down box shows a list of names pulled from a database. The checkbox is initially unchecked. What I want to happen is that when the user clicks on the box the page will refresh and update the drop down box to include more names in the list depending up on the sql query that I have set up.
so form looks like this :
<form name="search" method="post" action="myaction.php">
<table width="100%">
<tr>
<td><label>Select a name to search for:</label></td>
<td><select name='mynames'><?php
echo "<option value='0'>-- Select a Name --</option>";
mysql_data_seek($request_staff, 0);
while ($row_mynames = mysql_fetch_assoc($mynames)) {
echo "<option value='".$row_mynames['myID']."'>".$row_mynames['firstName'] . " " . $row_mynames['lastName'] ."</option>" ; }?></select></td>
<td><input type="checkbox" name="checkActive" value="1">Include additional Names</td>
<td><button id="submit" type="submit" ><span>Search</span></button></td>
</tr>
</table>
</form>
I think I may need some javascript but I wasn't sure I found several things that suggested just checking when the submit button is checked, but I need it to check before the form is submitted.
the sql statement is pretty simple just
$sql = "Select myID, fName, lName, extraNames from myTable $mysearch;
I want a where clause like this : (I know this isn't correct code but this is what I want it to do)
if checkbox is checked {
$mysearch = "";
}else {
$mysearch = "Where extraNames = 1";
}
I have some javascript that checks a checkbox on another page, but I couldn't figure out how to change the sql query (written in php) with the javascript. Thanks for any help you may provide.
HTML
<form name="search" method="post" action="myaction.php" id="myForm">
<table width="100%">
<tr>
<td><label>Select a name to search for:</label></td>
<td><select name='mynames'><?php
echo "<option value='0'>-- Select a Name --</option>";
mysql_data_seek($request_staff, 0);
while ($row_mynames = mysql_fetch_assoc($mynames)) {
echo "<option value='".$row_mynames['myID']."'>".$row_mynames['firstName'] . " " . $row_mynames['lastName'] ."</option>" ; }?></select></td>
<td><input type="checkbox" name="checkActive" value="1" onclick="$('#myForm').submit();">Include additional Names</td>
<td><button id="submit" type="submit" ><span>Search</span></button></td>
</tr>
</table>
</form>
PHP
$sql = "Select myID, fName, lName, extraNames from myTable";
if (!empty($_POST['checkActive'])) {
$sql .= "WHERE `extraNames` = 1";
}
Since the web page is running in a browser on the client side (the HTML) and the SQL query is running on the server (the PHP), you'll need to add a parameter to the page (the HTML) that indicates if the check box was clicked. When the form is submitted to the myaction.php URL on the server, you can then feed the value of that parameter into the if checkbox is checked statement.
I have a PHP script that generates table rows with hidden input tags that have names like title1, title2 etc and price1, price2 etc. The user has the ability to remove and add rows as they see fit. My question is when I submit the rows how can I read those hidden inputs in order, either through PHP or Javascript?
EDIT: Sorry about the lack of detail. Here's some code:
The PHP that generates the rows
$result = mysql_query("SELECT * FROM `table`");
$i=0;
while ($list = mysql_fetch_array($result))
{
$i++;
$title = $list['title'];
$price = $list['price'];
$plu = $list['plu'];
?>
<tr id="row<?php echo $i; ?>"><td><input type="hidden" name="title<?php echo $i; ?>" value="<?php echo $title; ?>"></td></tr>
<tr><td><input type="hidden" name="price<?php echo $i; ?>" value="<?php echo $price; ?>"></td></tr>
<tr><td><input type="hidden" name="plu<?php echo $i; ?>" value="<?php echo $plu; ?>"> </td></tr>
<?php
}
?>
Now if users can remove rows, I know I can tell exactly how many rows there are, but when it comes time to read them and save them in order I'm lost.
I'm not sure you're guaranteed to get them in order based on location on the page, but since you can name the elements yourself, you could name them title[1], title[2], ...
For example:
<input type="hidden" name="title[1]" value="foo">
...
<input type="hidden" name="title[2]" value="bar">
This will allow you to access the submitted elements in PHP by, for example:
$_POST['title'][1], $_POST['title'][2], etc.
You can use only one or two (for title and price) hidden input rather separate inputs for each values...all you need to do is use some special characters like ';','#' as a delemeter to seperate each values.. and when user delete the row just remove that value from the entire string....you can do it easily using javascript..
so ultimately you will have to submit only one (or two) hidden values...