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
}
}
Related
i have a form in php in which i am trying to add multiple fields on button click, i did the following code:
function add_fields() {
var objTo = document.getElementById('room_fileds')
var divtest = document.createElement("div");
divtest.innerHTML = '
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
';
objTo.appendChild(divtest)
}
<div id="room_fileds">
<div class="form-group col-md-6">
<label for="inputPassword4">Item</label>
<?php
$sqlcodes = "SELECT * FROM inventory ORDER BY categoryname ASC";
$resultcodes = mysqli_query($con, $sqlcodes);
echo "<td><select class='form-control' name='item'>";
echo "<option>Select Item</option>";
if ($resultcodes->num_rows > 0) {
while($row = $resultcodes->fetch_assoc()) {
$group[$row['categoryname']][] = $row;
}
foreach ($group as $key => $values){
echo '<optgroup label="'.$key.'">';
foreach ($values as $value)
{
echo '<option value="'.$value['name'].'">'.$value['name'].'</option>';
}
echo '</optgroup>';
}
} else {}
echo "</select></td>";
?>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Weight</label>
<input name="weight" type="text" class="form-control" id="inputEmail4" placeholder="Weight">
</div>
</div>
<input type="button" id="more_fields" onclick="add_fields()" value="Add More" />
however this is not working, i am getting the following error:
** Uncaught ReferenceError: add_fields is not defined
at HTMLInputElement.onclick **
can anyone please tell me what is wrong in here, thanks in advance
As per the comment previously about cloning content and appending that the following goes a step further and uses a content Template to store the content that you wish to add with each button click. This template could hold the generated select menu and would be invisible until added to the DOM. This means you do not have a huge, bloated function that gets called - only some quite simple code to find the template, create a clone and append to the designated parent node.
The below example has the PHP commented out so that the display here looks OK but would need the PHP code re-enabled to produce the actual results you need. None of the code within the template has an ID attribute so there is no need to worry about duplicating IDs.
const clonetemplate=(e)=>{
let parent=document.getElementById('room_fields');
let tmpl=document.querySelector('template#rfc').content.cloneNode( true );
parent.append( tmpl )
}
// Button click handler
document.querySelector('input#add').addEventListener('click',clonetemplate );
// pageload... display initial menu
clonetemplate();
#room_fields > div{margin:1rem;padding:1rem;border:1px solid grey;font-family:monospace;}
#room_fields > div label{display:block;width:80%;padding:0.25rem;margin:0.1rem auto;float:none;}
#room_fields > div select,
#room_fields > div input{float:right}
<div id="room_fields">
<!-- add content here -->
</div>
<input type="button" id='add' value="Add More" />
<!--
Generate the content once that will be repeated
and keep it within a content template until
needed.
-->
<template id='rfc'>
<div>
<div class='form-group col-md-6'>
<label>Item
<select class='form-control' name='item'>
<option>Select Item
<!-- Uncomment this PHP for live version
<?php
$sql = 'select * from `inventory` order by `categoryname` asc';
$res = $con->query( $sql );
$group=array();
while( $rs=$res->fetch_object() ){
$group[ $rs->categoryname ]=$rs;
}
foreach( $group as $key => $values ){
printf('<optgroup label="%s">',$key);
foreach( $values as $obj )printf( '<option>%s',$obj->name );
print('</optgroup>');
}
?>
-->
<option>Hello
<option>World
<option>No IDs
<option>Simples...
</select>
</label>
</div>
<div class='form-group col-md-6'>
<label>Weight
<input name='weight' type='text' class='form-control' placeholder='Weight' />
</label>
</div>
</div>
</template>
In the string that you define in the function add_fields and assign to divtest.innerHTML you have line breaks. You probably also get an error when loading the script saying that you have a syntax error. You should try to avoid line breaks in strings. An alternative solution could be to use backticks for your string. YOu can read about it here: Template literals (Template strings).
Here are two examples. The first fails with both syntax and reference error, the next works fine (but does not do anything).
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = '
test
';
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
function add_fields(){
var divtest = document.createElement("div");
divtest.innerHTML = `
test
`;
}
<input type="button" id="more_fields1" onclick="add_fields()" value="Add More" />
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.
I have next form :
<?php
echo "<form action=\"test.php\" method=\"post\">";
$rez = mysqli_query($kon, "SELECT * FROM shops");
while($red = mysqli_fetch_assoc($rez)){
$niz = array(
array($red["id"],$red["naam"])
);
echo "<div class=\"col-xs-12 col-sm-12\">
<input class=\"hidd\" type=\"hidden\" name=\"txtHidd[". $red["id"] ."][kolicina]\" id=\"txtHidd\" value=\"\"/>
<div class=\"col-sm-2 col-xs-4\">
<div class=\"form-group\">
<input id=\"quan\" class=\"form-control\" type=\"number\" value=\"0\" min=\"0\" max=\"10\" onChange=\"proces();\"/>
</div>
</div>
<div class=\"col-sm-10 col-xs-8\">
Informacije
</div>
</div>
<div class=\"footer\" style=\"position: fixed;bottom: 0;width: 100%;left:0;\">
<span class=\"glyphicon glyphicon-chevron-left\"></span> Niets toevoegen
<button class=\"col-xs-6 col-sm-6 btn btn-danger\" type=\"submit\" name=\"btnNaruci\" id=\"btnNaruci\">
Leg in winkelmand <span class=\"glyphicon glyphicon-chevron-right\"></span><span class=\"glyphicon glyphicon-chevron-right\"></span><span class=\"glyphicon glyphicon-chevron-right\"></span>
</button>
</div>";
}
echo "</form>";
?>
I want to update this hidden field for every result. I have now 5 results but if i increase quantity, the hidden field get value only if i increase quantity of first result.
I have onChange by the quantity input field and then in javascript i get the value of that field and add it to the value of the hidden field, but the value of the hidden field is changed only for the first result in while loop..
Thanks in advance...
I would need the body of your proces() function to say for sure, but I think you reference your input field by id, all 5 input fields have the same id. Only first gets updated and that's the problem. Either give different ids (by adding count) or reference by class. That would work, however having same id for multiple fields is not a good idea.
Post the body of the function and I can give more detailed help.
Ok, so they do have the same id. You could go by class to update them like this:
var quan = document.getElementById("quan").value;
var hiddenfields = document.getElementsByClassName('hidd');
for (var i = 0; i < hiddenfields.length; ++i) {
var item = hiddenfields[i];
item.value = quan;
}
Or if it's ok tu use JQuery:
var quan = $("#quan").val();
$( ".hidd" ).val(quan);
Based on your comment:
I see. I think simplest would be to do the following:
In your php code add id (concat as string), and add it to the call of your updating function
This might not compile, but gives you the idea:
$i = 1;
while($red = mysqli_fetch_assoc($rez)){
// ...
echo "<div class=\"col-xs-12 col-sm-12\">
// ...
<input class=\"hidd\" type=\"hidden\" name=\"txtHidd[". $red["id"] ."][kolicina]\" id=\"txtHidd".$i."\" value=\"\"/>
<div class=\"col-sm-2 col-xs-4\">
<div class=\"form-group\">
<input id=\"quan".$i."\" class=\"form-control\" type=\"number\" value=\"0\" min=\"0\" max=\"10\" onChange=\"proces('quan".$i."', 'txtHidd".$i."');\"/>
</div>
</div>
// ...
</div>";
$i++;
In javascript the updating function would use the parameter
function proces(quanID, hiddenID) {
var quan = document.getElementById(quanID).value;
document.getElementById(hiddenID).value = quan;
}
EDIT AGAIN
I found that the /" at the id fields were in wrong position.
Updated sample code. Basically your html output is supposed to look like this (I didn't include name, as it doesn't matter, now we are only looking at id-s):
...
<input class="hidd" type="hidden" name="xxxxx" id="txtHidd1" value=""/>
<div class="col-sm-2 col-xs-4">
<div class="form-group">
<input id="quan1" class="form-control" type="number" value="0" min="0" max="10" onChange="proces('quan1', 'txtHidd1');"/>
</div>
</div>
...
...
<input class="hidd" type="hidden" name="xxxxxx" id="txtHidd2" value=""/>
<div class="col-sm-2 col-xs-4">
<div class="form-group">
<input id="quan2" class="form-control" type="number" value="0" min="0" max="10" onChange="proces('quan2', 'txtHidd2');"/>
</div>
</div>
...
Looking at the id-s and the call of the function. If it's like that, the javascript update part will work perfectly.
That is my test.php page
<?php
session_start();
include("config.php");
global $kon;
ob_start();
print_r($_POST["txtHidd"]);
foreach ($_POST["txtHidd"] as $id => $id_prod) {
foreach ($id_prod as $kolicina) {
echo "<br />Id : {$id} and quantity : {$kolicina}<br />";
}
}
ob_flush();
?>
And result tha i get when i hit a post is next :
Array ( [17] => Array ( [kolicina] => ) [18] => Array ( [kolicina] => ) [19] => Array ( [kolicina] => ) [20] => Array ( [kolicina] => ) )
Id : 17 and quantity :
Id : 18 and quantity :
Id : 19 and quantity :
Id : 20 and quantity :
Okay so I've searched multiple questions that are similar to mine, but aren't quite the same problem. All I'm trying to do is check each textbox in a table to see if it is a numerical value or not. This textbox has a quantity value, so it should only take numbers. Most of my code's in HTML and PHP.
The hidden input is a numerical value that creates the number of rows in the table that comes from the previous page.
I feel like I'm so close but yet so far away....
function validate() {
var submitOK = true;
var alertstring = "";
var x1 = document.getElementsByClassName('validate-it');
for(var i=0; i
" />
<?
$userinput = $_POST['productnumber'];
$count = 0;
do {
echo '<tr>'; ?>
<td>
<select name="product<?=$count?>" rel="cost<?=$count?>">
<option value="0"></option> <?
$sql1 = "select product_id, product_name from product";
$rs=mysqli_query($db,$sql1);
while($row=mysqli_fetch_array($rs)){ ?>
<option selected="selected" value="<?=$row[0] ?>"><?= $row[1] ?></option>
<?}?></select>
<? echo '<td> <input type="text" class="validate-it" name="quantity' .$count. '" value="" /> </td>';
echo '<td> <input type="text" id="cost'.$count.'" name="unitprice' .$count. '" value="" /> </td>';
echo '<td id="totalprice".$count> </td>';
echo '</tr>';
$count = $count + 1;
}
while($count < $userinput);
?>
I might be wrong, but I believe you should "register" new dynamic HTML elements you add on your page in order for jQuery to be aware of them.
Here are few useful links, in case everything else is working for you - then you just need to bind your new elements to these events and you'll be good to go:
Event binding on dynamically created elements?
Jquery how to bind click event on dynamically created elements?
Hope it helps! :)
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.