new value overwriting the previous values - php

Ok so i have this javascript
function getpreconfigproducts(str1,str2)
{
var url="ajax_preconfig_products.php?";
url=url+"id="+str1+"&cid="+str2;
xmlHttp = GetXmlHttpObject(stateChangeHandler);
xmlHttp_Get(xmlHttp, url);
return false;
}
and it calls this php
<?php
if($_GET['id']!='')
{
$sql="SELECT * FROM productinfo WHERE ProductID=".$_GET['id']." AND Status=1";
$pro=ExecuteGetRows($sql);
?>
<p>Qty: <input type="input" name="qty[]" id="fpro[]" value="1" style="width:15px; margin-top:-3px;" /> <label><?php echo $pro[0]['ProductName'];?></label> </p>
<?php
echo "^_^";
echo ",".$pro[0]['ProductID'];
} ?>
which generates this
<div class="fields">
<h2>Final Products</h2>
<p id="finalproductsid">
<p>Qty: <input name="qty[]" id="fpro[]" value="1" style="width: 15px; margin-top: -3px;" type="input"> <label>FIREBOX S5510 15</label> </p>
<p>Qty: <input name="qty[]" id="fpro[]" value="1" style="width: 15px; margin-top: -3px;" type="input"> <label>FIREBOX S5510 15</label> </p>
</p>
</div>
The problem is that if a user changes the input qty[] to say 5 and adds another product it reverts back to 1 ...any ideas how i can address this

Aside from all the SQL injection stuff, mentioned already, I think I might know what your problem is. Tell me if I understand your script:
User clicks an 'add product' button
Button fires an AJAX request to the PHP script above
The PHP script generates some HTML
Somehow (?) the generated HTML gets displayed
The values of all of the other product fields in the form revert back to one
I'm assuming #4 is where the problem (#5) is occurring. Depending on how you append the HTML to the form, the input fields will sometimes revert. For instance:
//Reverts all form inputs to default-
myForm.innerHTML += "<input name='new_input'/>";
//Keeps current input values-
var newNode = document.createElement('input');
myForm.appendChild(newNode);
May I suggest, that instead of appending a string of HTML, you create the HTML with JavaScript, getting the product name/id through an AJAX request.
I don't quite understand how your script is working though. As far as my limited knowledge goes, the PHP isn't displaying onto the current page, but echoing to the AJAX's response text. Is there something more, or is it just me?

Re: Where is the sql injection?
This answer is in response to the OP's comment asking about the sql injection error.
Note the line:
$sql="SELECT * FROM productinfo WHERE ProductID=".$_GET['id']." AND Status=1";
The error is that the incoming HTML value for "id" is not properly escaped. You're expecting that it will contain an integer or nothing. But if a hacker sent something like
1;truncate users;select * from users where id=1 as the value of id, you'd end up with the sql statement:
$sql="SELECT * FROM productinfo WHERE ProductID=1;truncate users;select * from users where id=1 AND Status=1";
The right way is to ALWAYS ALWAYS ALWAYS properly escape or untaint any data coming in to the program. For Php MySQL dbms queries (manual):
$sql= sprintf("SELECT * FROM productinfo WHERE ProductID=%s AND Status=1",
mysql_real_escape_string($_GET['id']));
Notes:
For databases other than MySQL, there are other Php techniques. See the docs.

Related

PHP update form that updates database information only if there is an input in that particular field using PDO

I am currently working on a form that uses PHP and SQL to update information in a database. It is functioning properly and updating the information but the issue is... is that it updates everything, including fields that I didn't even put any input in which means it will only update a particular row in the database and leave the others blanks... I need it to just change information from a field with an actual input and leave it if there is no input.
Here is the PHP and SQL code:
try {
$deleteRecId = $_GET['id'];
$update_event_name = $_POST['updateName'];
$update_event_location = $_POST['updateLocation'];
$update_event_date = $_POST['updateDate'];
include 'connect.php';
if(isset($_POST["submit"])) {
// new data
$sql = "UPDATE events SET event_name='$update_event_name',
event_location='$update_event_location', event_date='$update_event_date'
WHERE event_id=$deleteRecId";
// Prepare statement
$stmt = $conn->prepare($sql);
// execute the query
$stmt->execute();
// echo a message to say the UPDATE succeeded
echo $stmt->rowCount() . " records UPDATED successfully";
}
}
catch(PDOException $e)
{
echo $sql . "<br>" . $e->getMessage();
}
and here if the form:
<form class="update-form" action="<?php echo $_PHP_SELF ?>" method="post">
<p id="input-headers">Event Name</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateName" value="">
</p>
<p id="input-headers">Event Location</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateLocation" value="">
</p>
<p id="input-headers">Event Date</p>
<p id="update-input-field-wrapper">
<input type="text" name="updateDate" value="" placeholder="01/01/2000">
</p>
<input type="submit" name="submit" value="Submit" id="updateBtn">
</form>
So to sum up I need this application to only update information of a field with an actual input and if the form field has no input I need that database info to remain the same. I appreciate any help with this as I am pretty new to these concepts... thanks!
I found a really handy solution to this! Here is how I implemented it into my code.
$sql = "UPDATE events SET event_name=IF(LENGTH('$update_event_name')=0, event_name, '$update_event_name'), event_location=IF(LENGTH('$update_event_location')=0, event_location, '$update_event_location'), event_date=IF(LENGTH('$update_event_date')=0, event_date, '$update_event_date') WHERE event_id=$deleteRecId";
It basically just checks whether the string is empty or not. If it's empty it won't be updated. If it isn't empty it'll go through with the update! Very simple way to achieve this effect when creating an update form.
Using your current code structure, you can do this.
Use SQL to select * from event ID. Populate your update_event_xxx with the parameters.
If $_POST[xx] is blank, ignore. Else, update_event_xx = $_POST[xx]

Form Not Submitting Correctly

So I am trying to make a select element update a MYSQL record every time the selection is changed. But the only way I was successfully able to trigger the PHP code is through an input button and not what is shown below. I need to be able to trigger the PHP code with the invisible input submit.
The whole point is to update PHP records through the select element and no button.
<form id="signin-form_id" class="panel" method="POST" style="margin-bottom: 0px;">
<div class="input-group">
<span class="input-group-addon">
Coin
</span>
<select class="form-control" name="cointype" onchange="this.form.submit()">
<option value="0" selected>Bitcoin</option>
<option value="1">Litecoin</option>
</select>
</div>
<noscript><input type="submit" name="ReferralCoin"></noscript>
</form>
And the submit button is suppose to trigger a POST event in PHP seen here:
Do not comment about MYSQL injection vulnerabilities.
<?php
if (isset($_POST['ReferralCoin']))
{
$cointype = $_POST['cointype'];
if($cointype == "0")
{
$odb->exec("UPDATE users SET `coin` = '$cointype' WHERE `ID` = '$userid'");
}
elseif($cointype == "1")
{
$odb->exec("UPDATE users SET `coin` = '$cointype' WHERE `ID` = '$userid'");
}
}
?>
The problem is if I was to use an input button it works fine and triggers the php POST code, but when using the invisible input submit it does not trigger the PHP POST code. If anyone can help me find my mistake, much is appreciated!
You're checking for the submit button here:
if (isset($_POST['ReferralCoin']))
But if the submit button isn't being clicked (since you're submitting the form via JavaScript code instead) then it isn't included in the POST values. So $_POST['ReferralCoin'] isn't set.
You'd need to remove the check entirely, or check some other condition. (Such as whether $_POST['cointype'] is set.)

Show DIV Text based on Multiple Selections jQuery and PHP

I have tried to search google and here about my question but havent found the exact answer which I could use. So I am asking here. Hope to find help.
I have some input fields in a form and want to show a DIV using jQuery. The details (pseudo-logic) are as follows.
V1: <input type="radio" name="rad" value="v1" />
V2: <input type="radio" name="rad" value="v2" />
<select name="sel">
<option value="o1">o1</option>
<option value="o2">o2</option>
</select>
Now, based on selection, the jQuery will generate the text in an initially empty hidden div based on data filled in form fields.
For example, as it may be shown
<div id="d1">
The calculated value for rad(o1) & o2 & t1 is "value1"
</div>
If it was only for PHP, the simple code I could use, to be processed in another php file, would be (using mysql query, and I am aware of real escape strings, just not mentioning here),
$radioBtn = $_POST['rad'];
$selDrpDn = $_POST['sel'];
$textData = $_POST['t1'];
//Using this query,
$queryString = mysql_query("SELECT * FROM mobiles WHERE jobType = '$radioBTN' AND modelName = '$selDrpDn' AND compName = '$textData'");
Not sure if this answers your question...
$(function() {
$("select[name='sel'], input[name='rad']").on("change",function() {
$('#d1').html("You selected : " + this.value).show();
}
});
that's using the form code and div sample you gave above.

Calculating values with formulae from user input in PHP

I want to do an equation using the values I get from the input boxes called ampMin, voltMin and hastMin...
I'm not sure if it's a syntax problem or my method of approach is plain wrong.. Here's is an example of how the equation should look and work like with Excel.
What am I doing wrong? Thank you for your time!
EDIT: worth mentioning is that the whole block of code is within "strckenergi.php".
<html>
<title>Sträckenergi</title>
<body>
<h3>Svetsmetod: 111</h3>
<h4><i>Med K=0.8</i></h4>
<pre>
<form method="post" action="strckenergi.php">
Amp. Min <input type="text" name="ampMin"> Volt. Min <input type ="text" name="voltMin"> Hast. Min <input type="text" name="hastMin"> </pre>
<?php
echo "kJ/mm (minimum) = " . $qMin
$qMin = ( $ampMin * $voltMin ) / (( $hastMin * 1000 ) / $hastMin * 0.8));
?>
</body>
</html>
This works.
<html>
<title>Sträckenergi</title>
<body>
<h3>Svetsmetod: 111</h3>
<h4><i>Med K=0.8</i></h4>
<pre>
<form method="post" action="form.php">
Amp. Min <input type="text" name="ampMin"> Volt. Min <input type ="text" name="voltMin"> Hast. Min <input type="text" name="hastMin">
<input type="submit" value="submit"> </pre>
</form>
<?php
if($_POST){
$voltMin = $_POST['voltMin'];
$ampMin = $_POST['ampMin'];
$hastMin = $_POST['hastMin'];
$qMin = ( $ampMin * $voltMin ) / ( $hastMin * 1000 ) / $hastMin * 0.8;
echo "kJ/mm (minimum) = " . $qMin;
}
?>
You don't appear to be using forms correctly. If you want the browser do be able to display it right away, you should use JavaScript instead. PHP will require an additional pageload, or an AJAX request.
And in order to post the form, you need a submit button. Otherwise, the browser won't know what to do with it.
Further, your first PHP line needs a semi-colon, and your second one needs to be above the first - otherwise, the interpreter won't know what your value is when printing it, because it hasn't been calculated yet.
To be honest, I think you need to start by googling for how to construct an HTML form, then you can look up simple JavaScripts. Lycka till!
First off, as Joel Hinz says above, you need a submit button so the page knows when the user is done inputting and wants to send the form to the server for processing.
Second, you need to close the form with a tag.
Third, you're probably better off sticking with php at this stage; JavaScript can be a bit tricky and mighty frustrating for beginners.
This is a rough approximation of how your form should look.
<form method="post" action="strckenergi.php">
Amp. Min <input type="text" name="ampMin">
Volt. Min <input type ="text" name="voltMin">
Hast. Min <input type="text" name="hastMin">
<input type="submit" value="submit">
</form>
See http://www.tizag.com/phpT/forms.php for a clear explanation of forms.
OK first thing first. When the form is submitted, the values contained in the $_POST array aren't immediately available to the script on the server which processes the input.
For that you will need something like the following:
<?php
if($_POST){// this checks for the existence of the $_POST array, i.e. was something submitted
//now we're assuming a form was submitted
$voltMin = $_POST['voltMin'];
$ampMin = $_POST['ampMin'];
$hastMin = $_POST['hastMin'];
$qMin = ( ($ampMin*$voltMin)/($hastMin*1000)/($hastMin*0.8) );
echo "kJ/mm (minimum) = " . $qMin;
}// if($_POST)...
?>
Then you can process the elements, and print out the results of your calculations.
Oh, and drop the pre tags unless you really need them.

save multiple form in one button only

I want to create a project that save the fill up forms in previous form and insert into database using one button only. For example answer1.php and answer2.php the save button is in the answer2.php i want to fetch data from answer1.php and save to databse same as in answer2.php
this code below insert data in one form only
$query = mysql_query("INSERT into holiday (holiday_no,holiday_name, status,campaign_name,holiday_type, createdBy, holiday_date, createdDate)
VALUES('$holiday_no', '$id','$status','$campaign_name','$hol', 'System','$date','$createdDate')") or die(mysql_error());
echo "Data has been saved with holiday name";
Not quite sure what you're asking for ...but giving it a try ;-) :
You can put the key-value pairs the first script receives into the next form so they get transmitted once again to the second script. E.g. if in the first step something like category=foo and country=bar gets transmitted write out a form that looks like
<form method="POST" action="answer2.php">
<p>
<input type="hidden" name="category" value="foo" />
<input type="text" readonly="readonly" name="country" value="bar" />
<!-- all the other things you want to add to the form -->
<input type="submit" />
</p>
</form>
But keep in mind that a) you need to encode the values properly for html output, otherwise your scripts are vulnerable for injection attacks, see http://docs.php.net/htmlspecialchars
and b) your second script can't "be sure" that the values haven't been altered or even transmitted to the first script at all; if you need that (e.g. for some transaction mechanism) you need something else like e.g. http://docs.php.net/features.sessions
Use hidden fields, a session, or a temporary table.
<?php
if (empty($_REQUEST)) {
echo '<form action="', $_SERVER['PHP_SELF'], '">
</form>';
} elseif (empty($_REQUEST['some_field_from_your_second_form']) {
// Do the second part of your form
} else {
// Do the final submission
// Sanitize the values
// Insert in the database
}

Categories