I checked for a possible solution in the site and found no solution. I have a form which has two text fields for the user to enter Name and Mobile Number. By default the page shows only two fields. If the user wants he can add more. The problem is, I am unable to insert these multiple data into DB. Please see below. I do no have 10 reputations to post images. Hence I am giving an external link.
1) The initial form
http://postimg.org/image/qiojxjrcx/
2) Clicking the plus symbol, user can add more fields
http://postimg.org/image/zaetpokbx/
3) The fields added dynamically using Jquery have unique id's and a class. The script below is for getting the values of Staff Name and Mobile Number
a) Script for Getting Staff Name
var addstaffname = new Array();
$('input[class="addstaff"]').each(function() {
addstaffname.push(this.value);
});
b) Script for Getting Mobile Number
var addstaffmob = new Array();
$('input[class="addstaffmob"]').each(function() {
addstaffmob.push(this.value);
});
I am getting the values by using the class for Staff Name and Mobile. And through ajax I am posting these values in PHP.
$.ajax({
type:"POST",
url:"../../ajax.php",
data:'addstaffname='+addstaffname+'&addstaffmob='+addstaffmob,
cache:false,
success: function(data)
{
alert(data);
}
})
In ajax.php, I am storing these values into variables.
if(isset($_POST['addstaffname']))
{
$addstaffname = $_POST['addstaffname'];
$addstaffmob = $_POST['addstaffmob'];
$addstaffnameexploded = explode(',',$addstaffname);
$addstaffmobexploded = explode(',',$addstaffmob);
}
I am using explode as I have multiple values and all the values I get are CSV's from Jquery. I have a table called staff with three columns, staff_id,staff_name,staff_mobile and staff_id is PK and Auto Increment. My question is how do I insert staff name and mobile in the same row. Lets say we got staff name as A,B,C and mobile numbers as 100,200,300 from the form, I need to insert into MySQL DB with these values. So A will have mobile 100, B will have 200 and so on... If I had only one explode, I could easily use foreach loop and iterate. Very simple. I am going mad on how to insert data with this scenario. Any help will be highly appreciated.
I think the best way would be to create a form and use an array in the input
<input type="text" name="addstaffname[]" value="" />
<input type="text" name="addstaffmob[]" value="" />
then send the entire form using ajax
$("#form").ajaxForm({url: 'server.php', type: 'post'});
(ajaxForm is a jquery plugin ajaxForm)
and when you collect the data in php, you'll just have to do a foreach one of its key variables, some like this.
$addstaffname = $_POST['addstaffname'];
$addstaffmob = $_POST['addstaffmob'];
foreach($addstaffname as $key=>$name){
echo "Your name is " . $name . " and your phone is " . $addstaffmob[$key];
}
obviously you need to make a cast to vars, for sql injection or etc
Related
I am developing a web application and i am stuck with a problem.
i have two drop-down list, one is dynamically populated from my db, while the the other is static html.
When a user selects an item form the dynamic drop-down and select an item from the static html drop-down, and clicks submit on the form, I would like the dynamic selected list item to print out the entire selected row in the db.
here is my code sample
if ($contactc =="Yes"){
$result = mysql_query("SELECT * FROM company_details where comid = '$selectsector'");
while ($row = mysql_fetch_array($result)){
echo $row["fname"]." ".$row["comname"]."<br/>";
}
}
maybe this is what you wanted, though you will have to use JQuery
HTML
<form id="when_user_clicks_submit_button">
<input class="data_to_send" type="text" value="MySQL Selection data"></input>
<input type="submit" value="Submit"></input>
</form>
JavaScript|JQuery for Ajax Request:
document.getElementById('when_user_clicks_submit_button').onsubmit = function() {
$.ajax({
type: "POST",
url: "php_code_script.php",//php script location
data: { "data_from_form": data_to_send }, //data to send in JSON format
success: function(data) { //callback if the script execution is successful
$('<p>' + data + '</p>').appendTo('body');//this returns the selected information from the MySQL database and inserts it somewhere, make sure to echo or print the selected data inside the php script.
}
)}
};
PHP
if($_POST['data_from_form']) {
if ($contactc =="Yes"){
$selectsector = $_POST['data_from_form']; //gets the sended data from the form page to use for selection in the MySQL database
$result = mysqli_query("SELECT * FROM company_details where comid = '$selectsector'");
while ($row = mysqli_fetch_array($result)){
echo $row["fname"]." ".$row["comname"]."<br/>";
}
}
}
Maybe this is sort of what you wanted, you basically send the information you want to use to select from the database, the php script then handles it and echoes the selected information from the database, that data then returns to the form page where it becomes the value pf an DOM Element(HTML tag). This is just to give an example of what you maybe want, I didn't think about security or anything(I don't know much about it yet). Note I also changed the mysql to mysqli to make it more compatible with newer versions of PHP because mysql is no longer supported in newer versions or for the future.
I have thought of two solutions to my problem and I would like to know all good viable solutions if you think there may be better.
I have a list in my MySQL database which is associated with a check-box in my html form. I want to add or delete the list items with the form and subsequently do the same in my database. I have an auto-increment ID column for the list. The problem is, how do I update the table as I perform my add and delete operations. The list must be ordered chronologically, which is usually done by the database automatically as we add new items to the table.
Solution 1:
The check-boxes will have name attribute 'items[]' so when I can read them in as a $_POST array and delete the matching list item in my database. This of course requires that my ID column always be ordered continuously from first to the last, ie. 1, 2, 3... So I'll have to update the ID column every time I delete an item. The solution is suggested here: Reorder / reset auto increment primary key
Solution 2:
I give the new item a checkbox value that equals the max ID+1, so that each time an item is entered, the ID is distinct. This way I don't have to update the ID column. I just need to find the largest ID in my table and add 1 to it for my checkbox value.
To summarize, the first way updates the list ID's each time an item is deleted, which seems to be a bigger hassle. The second way just gives a new distinct ID value and I'll just query the database for the largest ID at the time, which seems more efficient.
I'm open to other suggestions :) much obliged
This is a quick response and may not do everything the way you need, but hopefully there are some ideas you can use.
Here's a solution using one field, in one table.
Imagine a table named "scratchpad", with one field called "cb_list".
Store the checkboxes/IDs in the cb_list field as a JSON string:
{"cb1":1,"cb2":0,"cb3":0,"cb4":1}
When creating page, a PHP command reads the field and converts into an array:
$cb_json = mysql_result(mysql_query("SELECT `cb_list` FROM `scratchpad`"), 0);
$cb_arr = json_decode($cb_json);
Now, loop through that array and create HTML for the checkboxes:
$out = '<div id="chkboxDIV">';
foreach( $cb_arr AS $key =>$val ){
$chkd = ($val==1) ? 'checked="checked"' : '';
$out .= $key. " <input type='checkbox' id='" .$key. "' " .$chkd. " />";
}
$out .= "</div>";
echo $out;
To add a new checkbox, you can use jQuery (or js) code to append a new checkbox to the DIV:
var lbl = prompt('Label?');
$('#chkbox').append(lbl+ ': <input id="' +lbl+ '" type="checkbox" /> ');
When checkboxes are ready to be stored again, use this javascript to loop through the checkboxes and save their IDs and values:
var arrCB = {};
$("#chkbox>input[type='checkbox']").each(function(){
var el = $(this);
var id = el.attr('id');
arrCB[id] = (this.checked ? 1 : 0)
});
var json_cb = JSON.stringify(arrCB);
Now, you can use AJAX to send the string -- similar to what you got from the database at the beginning -- back to PHP for storage:
$.ajax({
type: 'POST',
url: 'your_php_file.php',
data: the_json=json_cb
});
On the PHP side, your AJAX processor file (in this example called your_php_file.php) will look something like this:
<?php
$j = $_POST['the_json'];
$result = mysql_query("UPDATE `scratchpad` SET `cb_list` = '$j' ");
Here is a jsFiddle with examples of the javascript/jQuery.
Resources:
You might find this helpful: $.ajax - dataType
I've found most of the pieces i've needed for this form (making the fields dynamic, etc.) however now the array part of this doesn't seem to work to be able to submit correctly.
what i'm trying to accomplish:
a form with a select field that can be duplicated dynamically and then be submitted as a part of the form to it's own table. so if we add and choose three people in the one form, it submits to it's own attending table with a foreign key back to the event the form is for. had to make it dynamic because we'll never know for sure how many people will be attending said event, but it has to happen all in one form. just because it does. my boss says so.
here's my javascript for the add another field button:
$(document).ready(function() {
$('#btnAdd').click(function() {
var num = $('.clonedInput').length; // how many "duplicatable" input fields we currently have
var newNum = new Number(num + 1); // the numeric ID of the new input field being added
// create the new element via clone(), and manipulate it's ID using newNum value
var newElem = $('#input' + num).clone().attr('id', 'input' + newNum);
// manipulate the id value of the input inside the new element
newElem.children(':first').attr('id', 'attendee' + newNum).attr('name', 'attendee[' + newNum + ']');
// insert the new element after the last "duplicatable" input field
$('#input' + num).after(newElem);
// enable the "remove" button
$('#btnDel').attr('disabled','');
// business rule: you can only add 5 names
if (newNum == 6)
$('#btnAdd').attr('disabled','disabled');
});
here's what the field starts out as in the form:
<div id="input1" style="margin-bottom:4px;" class="clonedInput">
<select name="attendee[1]" id="attendee1" style='float:right;margin-right:4.5%;'>
<option value=''>Please choose one...</option>
<?php
while($row_attendees = mysql_fetch_assoc($res_attendees)){
$attendee_id = $row_attendees['attendee_id'];
$attendee_name = $row_attendees['name'];
echo "<option value='".$attendee_id."'>".$attendee_name." </option>";
}
?>
</select><label style='width:100px;display:inline-block;line-height:28px;' for="attendee">Attendee</label>
</div>
I'm getting all the things to change correctly. all of the select inputs are being id'd and name'd correctly. the div is being updated the same. all of that works correctly. what doesn't is when i go to submit. here's my php:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."','".$attendee."')";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
all the tutorials i used to pull this together show this as correct. however it doesn't work. i'm only getting whatever the first dropdown is, and nothing else is populating into the array. at least that's all it shows/submits if i run the form or echo the attendee variable in the foreach statement. PLEASE HELP! :)
thanks a ton in advance.
UPDATE
I have tried a few ways discussed with another user to display the array for $_POST['attendee'], however it still just shows 1 id in the array, and not however many fields i've actually added. I've also tried removing the number from the array in the select's name attribute. so it would just be name='attendee[]' instead of name='attendee[1]' and so on. this also doesn't help any. can someone please help with why my dynamically added fields aren't being added to the array?
I put your code into a JSfiddle, here: http://jsfiddle.net/rv8Mv/1/
It looks like the selects are being added correctly. You can check by clicking the "Submit" button, which shows a data string of what will be submitted to the server.
One thing you might want to check, is to make sure you are enclosing all the select elements inside a <form> element, which you didn't include in your question.
I think your problem is in the PHP code on the server.
On the server, make sure you are receiving all the variables by using this code:
<?php
foreach($_POST as $key => $value){
error_log($key.' -> '.$value;
}
?>
Then check your error log to see the names and values for all the POST variables.
You are probably not referencing the POST variables correctly in your current PHP code.
You should change your sql to look like this:
foreach($_POST['attendee'] as $attendee){
$sql_attendees = "INSERT into marketing_calendar.attending (event_title, attendee_id) VALUES ('".$_POST['title']."',".$attendee.")";
$res_attendees = mysql_query($sql_attendees) or die(mysql_error());
}
Your attendee_id is an int column. You were wrapping the column content with single quotes, which denotes a string. This would result in your attendee_id being null if your column is defined as nullable.
I will make this as short and descriptive as possible (considering my case is way longer).
Lets say I have 2 database tables with the following structures:
User table:
id ---- username---- gold
Items table:
id----- item_name---- item_price
What I am trying to achieve is brainstorming, I tried this with over 20 script combinations. I need to be able to echo out all items in the table to a good layout (done)
Have a text box for the user to type in the value required to be bought.
an a href to submit the amount, deduct the price of the item from the amount of gold the user has, then add 1 to the inventory. I am not requiring php code, as it is easy. All I need is help with trying to update the value typed in "Live". The layout of the "shop" will look something like this:
while($_row = mysql_fetch_assoc($query)){
echo out name...
<input type = 'text' name = 'to_buy_value'/>
<a href = 'javascript:;' class = 'buy'>Buy</a>
}
I hope the above code gives you enough reference.
TL;DR (after db structure?)
1- A text box with an a href as the submit.
2- table update is done on-the-fly (no reloads). Ajax.
3- Be able to buy more than 1 item at a time without page reloads
4-no help with php code required unless necessary.
I'd appreciate any sort of help.
Here's a very rough solution for you. In your while loop you could attach the item's database id to the id of the element:
while($_row = mysql_fetch_assoc($query)){
echo out name...
<input id="purchaseAmount{$_row->id}" type="text" name="value_to_buy" />
<a id="purchaseButton{$_row->id}" href="#" class="buy">Buy</a>
}
Then bind a javascript function to your "Buy" link which will make an AJAX request:
$('.buy').bind('click', function() {
// Grab the item id and amount
var itemId = $(this).attr('id').substring(14);
var itemAmount = $('purchaseAmount' + itemId).val();
$.ajax({
url: 'someurl/purchaseItem.php',
data: { item: itemId, amount: itemAmount },
success: function(data) {
// Update the player's gold and inventory on screen
}
});
});
The "purchaseItem.php" file could return a simple JSON object that holds the player's current gold and item amount for the inventory. Or you could return HTML, depending on how your page is setup.
Some time ago, I had project in which I had to do sort of a CMS just for news management, add, edit, delete, etc. As Satya commented, the way is with AJAX if you want to do it nicely.
What I did was a loop, just like yours, for each row fetched with PHP mysql_fetch_assoc add a tr in a table (yeah, I know, tables...). I know that you didn't wanted PHP help, but I think this will help you.
$res=mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_assoc($res)) {
foreach ($row as $col => $val) {
if ($col != "column you dont display or isn't 'ID' column" && $col != "another column you dont display, and so on") {
if ($col == "ID") $id = $val;
//use this to echo values in table/tr/td/div/span or whatever you use to display values
if ($col == "gold") {
echo 'whatever you want to echo using the gold value';
}
if ($col == "name of last column you are displaying") {
echo 'whatever you display for that column';
echo '<input type="text" value="Introduce quantity">';
//If you are on HTML5 you could just use id="{$id}" as it will be easier
echo '<a href="#" class="buy" id="i_{$id}" value="Introduce quantity">';
}
}
}
One of the most important things here is to keep track of the ID of each item, this way you can relate them when sending the POST request to the server.
I recommend you to use jQuery for that matter, it's very easy to use
<script type="text/javascript">
$(document).ready(function () {
$(".buy").click(function(e) {
e.preventDefault();
// You get the id attribute of the button clicked, which contains the
// item ID. Then you substr the string to get just the id number. Example:
// The id of the clicked element is "i_2254" you use substr to get just the
// 2254 and send it to the php that process the buy
// If you choose the HTML5 id form I said above in the PHP, then var id=$(this).attr("id")
var id = $(this).attr("id").substr(2);
$.ajax({
type: "POST",
url: "buy_item.php",
async:false,
data: "itemID="+id,
success: function(data) {
// Here is where the magic occurs, this is what happens when you
// get the response, here is where you update the
// inventory, quantity, etc WITHOUT reloading.
// The variable data is the response of the server
// you just echo what you need on buy_item.php, and
// that will be data here
// A simple example is to change the value of an input
// with id="gold", you echo gold on php and...
$('#gold').val(data);
}
});
});
});
});
</script>
In the buy_item.php is where you UPDATE the gold values of the table, and add the item to the item table. Use $_SESSION variable to store user session name and update the gold and items of that user.
I suggest you to investigate about AJAX and jQuery(optional), it would help a lot!
I think basically this will solve your problem, and I hope for an invitation for the game :P
i have a multiple amount of text fields, the amount of text fields is due to how much data is in a database. The input for both are integers, all i want is when the values are inputted into the text fields it throws an error if the inputted data is larger than the value in the data base
for example
in a markscheme
the data inputted into the textbox is the mark given to the student and the data in the database is the maxmark for that particular question, so therefore it cannot exceed that value
so in effect i want to compare the values and if the text input value is larger than that of the one in the database it throws and error :)
If it's OK for you to rely on your users having javascript enabled, I would say the easiest is to verify the data on the client side.
You could do something like this:
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<input type="text" value="5" name="grade[123]" data-max="10" />
<script type="text/javascript">
$(function() {
$('input[type="text"]').blur(function(e) {
var $this = $(this);
var max = parseInt($this.data('max'), 10);
if (parseInt($this.val(), 10) > max) {
var name = $this.attr('name');
console.error('Value ' + $this.val() + ' in field "' + name + '" exceed its maximum value of ' + max);
$this.focus();
}
})
});
</script>
</body>
</html>
Or you could replace all this logic with simple HTML5 number fields:
<input type="number" value="5" name="grade[123]" min="0" max="10" />
Obviously, one should never trust their users. You should always double-check the data on the server side and notify users about the possible errors.
This is something you could do:
<?php
if (!empty($_POST)) {
// ...
// fetch max values from the database in the form of
// array(
// id => [max],
// );
$maxValues = array( /* ... */ );
// prepare some error array if you want to show errors next to individual fields
$errors = array();
// ...and then loop through the posted array
foreach ($_POST['grades'] as $id => $value) {
// make sure the submitted value is an integer
if (!ctype_digit($value) && !is_int($value)) {
$errors[$id] = 'Invalid value';
continue;
}
if ((int) $value > (int) $maxValues[$id]) {
$errors[$id] = 'Value cannot be more than ' . $maxValues[$id];
}
}
// assign errors to the view or do whatever is required in your script
// ...
}
It shouldn't be difficult to understand what I was doing there. Basically, have one reference array and the data array to verify against (note: your HMTL field names must have the square brackets in them to act as arrays). And then just loop through the submitted data and verify against the reference array.
Just like Ryan Kempt said, there are lots of ways you could do it and without a specific example of your data structure or how you want the errors/exceptions to be presented to the user, it's quite difficult to write you an exact code.
Nevertheless, have a look at our suggestions and start from there. And best of luck!
Lots of ways to tackle this but pretty much with everything you can use a javascript solution for client-side checking and PHP for server-side... for front-end you could query the DB and output the information in hidden inputs and then compare the value of the textbox to the value of the matching hidden div using a javascript solution.
When the textbox loses focus you could use AJAX and query what's in the textbox against your database.
When the user submits the form finally you should also then verify the numbers again against the daabase using PHP.
So... would need more information but the above steps are what you're going to want to do - how you do them is up to you and if you need specific help after trying the above methods and running into issues, we'd love to help you more.
Happy coding and best of luck!