update ID automatically - javascript

i need a help here. i want to automatically update my iD whenever i submit my data. let me explain a bit more.
Here is the scenario when i submit a form the id of my page needs to update automatically. for example if i enter id 3 and submit the html form, when i open the form again it must check the Id from database and show the next id.
This means if the last data i entered has id 3 it then show me id 4 automatically when i refresh the page and want to submit new data
how can i add ID validation query in that code
need your expert advises.. thanks alot!!!
Html
<form action="survey-data-entry.php" name="1st-form" id="form-control" method="post" >
<label>Id.</label>
<input type="text" class="form-control" placeholder=" 0451211315" name="ID" id="id" required>
php
if(isset($_POST['ID'])){
$ID = $_POST['ID'];
$sql= "INSERT INTO phpstartup (ID, )
VALUES('$ID') ";
if(!mysql_query($sql))
{
die('caution' . mysql_error());
}
echo"1 record added";
}

You need to get the maximum of id + 1 from the query to use it for your next submission.
$rslt = mysql_query('SELECT MAX(ID) + 1 as nextId FROM phpstartup');
$row = mysql_fetch_assoc($rslt);
$nextId = $row['nextId'];
Now you can use the variable $nextId in your forms for re submission.

Related

SQL lag with jquery variables

I have this strange issue, which is hard for me to describe to be honest.
For testing purposes I have set up a SQL db containing id (autoincrement), first name, last name.
I have 2 entries there.
I call the db and list the entries in inputs like this:
while($row = $result->fetch_assoc()) {
$id = $row['id'];
$fname = $row['fname'];
$lname = $row['lname'];
echo "<div id='$id'>
<form method='post'>
<p>ID: <input type='text' name='id' id='id".$id."' value='$id' /></p>
<p>New first name: <input type='text' name='fname' id='fname".$id."' placeholder='$fname' /></p>
<p>New last name: <input type='text' name='lname' id='lname".$id."' placeholder='$lname' /></p>
<input type='submit' name='update' class='update' value='ID = $id' />
</form>
</div>";
}
Works perfectly fine and I get a page with both entries and a button to update them.
I am updating them with this function
$('.update').click(function(){
var row = $(this).parent().parent().attr('id'); // I've stored the SQL id in the parent div
// construct the input ids so i know where I am getting the data from
var idSource = '#id'+row;
var fnameSource = '#fname'+row;
var lnameSource = '#lname'+row;
// store the input values in variables
var id = $(idSource).val();
var fname = $(fnameSource).val();
var lname = $(lnameSource).val();
// use ajax to update sql table
$.ajax({
url : 'aiai.php',
method : 'post',
data : {id: id, fname: fname, lname: lname},
success: function(response){
console.log(response);
}
});
});
I am doing this so that every entry can be edited & updated on it's own.
An while this basically working I am getting a strange lag.
Example:
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am
getting the old value again
When I refresh the page I get the name update I just saved
Lag continues until I refresh the page
I load the page, update the first name, click the update button --> Works
Then I edit the same entry again, click the update button --> i am getting the old value again
When I refresh the page I get the name update I just saved.
Lag continues until I refresh the page.
It's like that info gets cached in the browser.
BUT, and this confuses me:
When I hardcode the inputs where I am calling the values from, everything works perfect.
So when I use
var id = $('#id2').val();
... instead of
var id = $(idSource).val();
... I am not experiencing this lag.
Anyone got an idea what I am doing wrong?

How to display mysql data through javascript in dynamic form field

I have a dynamically added HTML form field which takes a list of company names to store in MySql database. Since I have only 1 column in database, I am using serialize function to save & unserialize function to display again (on the edit page). The saving part works fine.
The issue is, I am unable to figure out how to display the various companies in the dynamic fields. I have hard coded $internname[0] at the first field (which is a static field) & added $internname[1] to the dynamic field (in script). This displays the first company name in the first field & the second company name in all the remaining fields.
I know, I need to pass an incremental number into the dynamic field, but how do i write this function? Tried using the already available xint variable which is incrementing anyway, didn't work.
<?php
$query = "SELECT * FROM user WHERE mail = '$mail' LIMIT 1";
$result=mysqli_query($db,$query);
while($row = mysqli_fetch_array($result))
{
?>
<div class="field_wrapperint">
<div class="inlineinput2b">
<div align="left">Internships:</div>
<?php $internshipname = unserialize($row['internshipname']);
foreach ((array) $internshipname as $internname[])
?>
<input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[0]);?>"/>
</div>
<div class="inlineinputb">
<img src="add-icon.png"/>
</div>
</div>
<input type="submit" name="update_profile" class="action-button" value="Update Profile" />
<?php
}
mysqli_close($db);
?>
<!-- Script for dynamic button adding -->
<script type="text/javascript">
$(document).ready(function(){
var maxField = 4; //Input fields increment limitation
var xint = 0; //Initial field counter is 1
var addButtonint = $('.add_buttonint'); //Add button selector
var wrapperint = $('.field_wrapperint');
var fieldHTMLint = '<div><div class="inlineinput2b"><input type="text" name="internshipname[]" placeholder="Company Name" value="<?php echo htmlspecialchars($internname[1]);?>"/></div><div class="inlineinputb"><img src="remove-icon.png"/></div></div>' ; //New input field html
//Once add button is clicked
$(addButtonint).click(function(){
//Check maximum number of input fields
if(xint < maxField){
xint++; //Increment field counter
$(wrapperint).append(fieldHTMLint); //Add field html
}
});
//Once remove button is clicked
$(wrapperint).on('click', '.remove_buttonint', function(e){
e.preventDefault();
$(this).parent('div').parent('div').remove(); //Remove field html
xint--; //Decrement field counter
});
});
</script>

How to handle inputs with the same name in php to add/update them in the database?

I have an HTML input form which is have an unknown number of inputs in some stages, like when the user wants to enter more than one document he click on an add button so a new field appears to him (using JavaScript for sure).
I make the names of the inputs just the same but in an array like <input name="something[]"/> .. the problem is I don't know if what I am doing gonna work or not ..
HTML PART
<input name="uat[]" type="date"/>
</td>
<td>
<input name="uatedate[]" type="date"/>
</td>
<td>
<input name="pgldate[]" type="date"/>
PHP PART
$j=0;
while(j<100){
$sql[j]= "insert into project scope values ('$uat[j]','$uatedate[j]' , '$pgldate[j]' ;)";
$j++;
}
^^ Just before the "try"
Replace your PHP PART code with this code:
$j = 0;
while ($j < count($_POST['uat'])) {
$sql[$j] = "insert into project scope values (" . $_POST['uat'][$j] . "," . $_POST['uatedate'][$j] . "," . $_POST['pgldate'][$j] . ")";
$j++;
}

PHP sending selected variables in a email to user

I would like to send the selected objects to a email address.
here is a demo:
http://jsfiddle.net/62g3s8sz/
I know a email can be send with PHP and i have tried many ways but all unsuccessful.
The email needs to correspond with the items selected.
So if Cooler Master K-380 is selected with AMD FM2 A6-6400K Dual Core 3,9GHz i need it to list these items
Case : Cooler Master K-380 : price
Processor: AMD FM2 A6-6400K Dual Core 3,9GHz : price
And then send it to the email address that the person is logged in with.
i know that $loggedInUser->email will display the email address.
If anyone knows how to send all this information within a email to the logged in person that would be great.
HTML:
<script type="text/javascript" src="js/formcalc.js"></script>
<form method="POST" name="contactform" action="contact-form.php" id="computerform">
<div>
<div class="cont_order">
<fieldset>
<legend></legend>
<label>Case</label>
<br>
<label class='radiolabel'>
<input checked="checked" type="radio" name="selectedcase" value="2001" onclick="calculateTotal()" />Cooler Master K-350 - ($10)</label>
<br/>
<label class='radiolabel'>
<input type="radio" name="selectedcase" value="2002" onclick="calculateTotal()" />Cooler Master K-380 - ($20)</label>
<br/>
<br/>
<label>Processor</label>
<br>
<label class='radiolabel'>
<input checked="checked" type="radio" name="selectedprocessor" value="3001" onclick="calculateTotal()" />AMD FM2 A4-5300 Dual Core 3,4GHz - ($10)</label>
<br/>
<label class='radiolabel'>
<input type="radio" name="selectedprocessor" value="3002" onclick="calculateTotal()" />AMD FM2 A6-6400K Dual Core 3,9GHz - ($20)</label>
<br/>
<br/>
<label>Totale price</label>
<div class="total">
<div id="case"></div>
<div id="totalPrice"></div>
</div>
<br>
</fieldset>
</div>
<input type='submit' id='submit' value='Bestel' onclick="calculateTotal()" />
</div>
</form>
JavaScript code
var case_prices = new Array();
case_prices["2001"]=10;
case_prices["2002"]=20;
var processor_prices = new Array();
processor_prices["3001"]=10;
processor_prices["3002"]=20;
window.onload = function()
{
calculateTotal();
}
// getCasePrice() finds the price based on the selected case
// Here, we need to take user's the selection from radio button selection
function getCasePrice()
{
var casePrice=0;
//Get a reference to the form id="computerform"
var theForm = document.forms["computerform"];
//Get a reference to the case the user Chooses name=selectedcase":
var selectedCase = theForm.elements["selectedcase"];
//We loop through each radio buttons
for(var i = 0; i < selectedCase.length; i++)
{
//if the radio button is checked
if(selectedCase[i].checked)
{
//we set cakeSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" cake we set it to 25
//by using the cake_prices array
//We get the selected Items value
//For example cake_prices["Round8".value]"
casePrice = case_prices[selectedCase[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cakeSizePrice
return casePrice;
}
// getCasePrice() finds the price based on the selected case
// Here, we need to take user's the selection from radio button selection
function getProcessorPrice()
{
var processorPrice=0;
//Get a reference to the form id="computerform"
var theForm = document.forms["computerform"];
//Get a reference to the cake the user Chooses name=selectedprocessor":
var selectedProcessor = theForm.elements["selectedprocessor"];
//We loop through each radio buttons
for(var i = 0; i < selectedProcessor.length; i++)
{
//if the radio button is checked
if(selectedProcessor[i].checked)
{
//we set cakeSizePrice to the value of the selected radio button
//i.e. if the user choose the 8" cake we set it to 25
//by using the cake_prices array
//We get the selected Items value
//For example cake_prices["Round8".value]"
processorPrice = processor_prices[selectedProcessor[i].value];
//If we get a match then we break out of this loop
//No reason to continue if we get a match
break;
}
}
//We return the cakeSizePrice
return processorPrice;
}
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var computerPrice = getCasePrice() + getProcessorPrice() + getCoolerPrice() + getMotherboardPrice();
//display the result
var divobj = document.getElementById('totalPrice');
divobj.style.display='block';
divobj.innerHTML = "Totale prijs: €"+computerPrice ;
}
Thanks :)
I don't like just pasting a link to the answer but ...
http://php.net/manual/en/function.mail.php
So all you need is something like this
$content = "..write it here yadda yadda whatever is your mail content ..";
$ok = mail($mailTo,"Hello, this is the mail subject",$content);
Note this will send plain mail, there are a few extra steps to make HTML mail, all covered on the link above. Good luck
Few reminders: it will probably not work on your local machine unless you have a mail daemon installed and working with PHP, and also you might need to tweak the last parameters on that mail() function depending on how PHP is installed.
In php, you send mails through the mail() function (or you could use an external mailer plugin), which requires a few basic concepts. Example:
$to = "email-from-user#some-email-client.com";
$subject = "You just made an order";
$body = $message;
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: noreply#somewebsite.com";
if (mail ($to, $subject, $body, $headers)) {
echo "1";
}
Quickly explained, you need a few parameters for the function to work. I just moved over some items from my own mail function, but i ll explain. You need a target (the $to variable) a subject (the $subject variable and the content, which i defined here as $body ... now i added headers too, which is additional, but for you, it might be important. The first two lines allows you to use HTML in the email, which you can use to markup your mail, such as using tables. Also you can specify where the email came from.
I use an echo there to check if it got through the mail function, if so, i use that parameter in an ajax call return to put up an appending div.
Remember, calling an external stylesheet isnt working in this so preferly, you have to do inline styling on your elements.
edit
I see you re trying to get the totals from your fieldset up in the email. Since you use a div to show the end content, sending a form will not allow you to transfer the variable from the total. (btw, if you submit this form, you actually go with 3002 and 2001 for example as variables, instead of the names in the email, thus you got to do some query work to push out the right names) Since I asume these prices are also in a database, you can calculate from there on the price as fixed and push it out in a query as well, which you then have to use in the $body variable.
Trying to point you in the right direction
The PHP code must be in contact-form.php, or you must change that name in the HTML.
Use the mail() function of PHP.
In PHP, the form data is available in the superglobal variable $_REQUEST.
Try print_r($_REQUEST); to see what is in there.

how to update mysql database

I want to update an int. in my MySQL Database with php. The int. comes from some Javascript. Here is my code where I get the int.:
<form action="SCD.php" method="POST">
<span name="Int_1" id="Int_`1">0</span><br>
<button type="button" onclick="UpdateData()">Update</button>
Name: <input type="Text" name="Name"></input>
<input type="submit" name="submit" value="Send Data">
</form>
The javascript pasts the int. in the span element when you click on the Updat button. That works perfectly.
Now I want to update this in the database. Here is my code:
<?php
$Int_1= $_POST['Int_1'];
$Name = $_POST['Name'];
if($Name) {
include_once("Includes/Database_conx.php");
$query_name = mysql_query("SELECT * FROM Users WHERE Username='$Name'")
or die(mysql_error());
$numrows = mysql_num_rows($query_name);
if($numrows != 0) {
//User exists
$query_int("UPDATE Users SET Int='$Int_1' WHERE Username='$Name'")
or die(mysql_error());
echo "Data updated";
} else {
echo "THat user does not exist";
}
} else {
echo "Please fill in a name";
}
?>
I get a error on line 15 in the php document. Line 15:
$query_int("UPDATE Users SET Int='$Int_1' WHERE Username='$Name'")
what is wrong with it? (Sorry if I missed anything, this is my first question on Stack Overflow)
$query_int is undefined variable, not function name so you can use it like that.
You probably wanted to use mysql_query() here, but it's also not good. Use PDO.
INT is a reserved word in MySQL, so you should use backticks if you have a column with such name. Your query to the server should be
UPDATE Users SET `Int`='$Int_1' WHERE Username='$Name'
<span name="Int_1" id="Int_1">0</span>
span cannot be send to the server.
you can try input element instead.

Categories