how to update mysql database - javascript

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.

Related

Passing input value via button click to php function in script

I need to use the value from an input field - without a POST - to do a lookup from an external source.
The input field has a button associated with it, which calls the script on button press. So I need to put the input field (id = 'lookup') into the function's parameter (the function is called within the script).
This is the code line in the script that needs the value from the input field (input field called 'lookup')
<?php $product_name = api_request(lookup);?>
My code is below.
(NB: I know about 'PHP is server side, JS is client site'. But the button click does call the PHP function, and the code does display the return value of the function if you do this instead:
<?php $product_name = api_request('1234');?>
which will return "My Product Name" via my api_request() function.)
What is needed to put a script variable in the api_request()'s parameter?
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
<p>Part Number = <input type="text" id="lookup" value= "12345"></p>
<button>Get product name for this part number</button>
<div id='product_name'>Product Name Goes Here </div>
<script>
$(document).ready(function(){
$("button").click(function(){
// returns value of input field
var lookup = document.getElementById('lookup');
// need to put the input field 'lookup' into the function's parameter
<?php $product_name = api_request(lookup);?>
var product_name = "<?php echo $product_name; ?>";
$('#product_name').text(product_name); // display it on the screen in that div ID
});
});
</script>
</body>
</html>
<?php
function api_request($partnumber) {
// code that returns the product name for that part number, hard coded here
$product_name = "My Product Name";
return $product_name;
}
As you already understand PHP is server and JS is client, you cannot directly use JS variables in PHP.
There are two ways by which you can.
$_POST which you already said you don't want to use. I assume the reason for not using $_POST is that browser prompts to continue refreshing page.
Use $_GET which will add a param in your url.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="get">
<p>Part Number = <input type="text" id="lookup" name="lookup" value= "12345"></p>
<button>Get product name for this part number</button>
</form>
Additionally add this small line in the beginning of your file to access is as a PHP variable.
$lookup = $_GET["lookup"];
ajax is possible.
try this
create file : api_request.php
<?php
function api_request($partnumber) {
// code that returns the product name for that part number, hard coded here
$product_name = "My Product Name";
return $product_name;
}
$number = $_GET["part"];
$product_name = api_request($number);
echo json_encode(array( "product_name" => $product_name ));
And Modify the javascript with this
$(document).ready(function(){
$("button").click(function(){
// returns value of input field
var lookup = document.getElementById('lookup');
// need to put the input field 'lookup' into the function's parameter
$.get(`api_request.php?part=${ lookup.value }`,(resp)=>{
$('#product_name').text(resp.product_name); // display it on the screen in that
},"json");
});
});

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++;
}

update ID automatically

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.

Simple HTML form input field with multiple values from barcode scanner

I know barcode scanner is just another keyboard that sends keycode 13 after every scan, I have a very simple form with just one input field, I want to be able to scan multiple barcodes and click submit to POST data. I think I would would need a javascript for this, but I am no good with javascripts.
The end result would look something like this. You can see multiple barcodes have been scanned and they appear at the bottom of the picture.
The goal is to scan desired number of barcodes without touching the keyboard, when done scanning press the submit button with the click of mouse. When I click submit they should be posted to another page.
I am sure this is a simple thing for someone who is good at javascript.
Here is the HTML form code.
<form action="myform5.php" method="post">
<p>First name: <input type="text" name="serial" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
My question is how I can make it do what I described above?
Thanks in advance.
This should work.
var codes = "";
var codes_el = document.getElementById('codes');
var output_el = document.getElementById('output');
function process_key(event){
var letter = event.key;
if (letter === 'Enter'){
event.preventDefault();
letter = "\n";
event.target.value = "";
}
// match numbers and letters for barcode
if (letter.match(/^[a-z0-9]$/gi)){
codes += letter;
}
codes_el.value = codes;
output_el.innerHTML = codes;
}
<form method="POST" action="myform5.php">
<input onkeydown="process_key(event)" />
<input type="submit" value="Send" />
<input type="hidden" name="codes" id="codes" />
</form>
<pre id="output">
</pre>
Then you can get in myform5.php like so:
<?php
// codes will be a string of barcodes seperated by "\n"
$codes = $_POST['codes'];
// get as array like so
$barcodes = explode("\n", $codes);
// build up string of barcodes
$barcode_str = "";
$prefix = '';
foreach ($barcodes as $barcode){
$barcode_str .= $prefix . "'" . $barcode . "'";
$prefix = ', ';
}
$query = "select * from hdds where serial IN (" . $barcode_str . ");";
/* do things with query here */
// once your done processing
// redirect the user back to the form page
header("Location: FormPage.html");
?>
I assume your barcodes are strings in the DB.
So you have to wrap each of the barcodes in the query.

Get the value of a hidden input in server side Php which was set by javascript

This wordpress stuff driving me mad again.
I have an output page which uses a short code to call a function (Stores)... the code of which in part is beneath.
It has a dropdown and a table of data, ..the data being dependant on the selected option of the drop down.
I use javascript to set the hidden input...successfully.
In fact I tried a normal, non hidden input as well...same result,..on server side, with$_POST["txtSelection"] or
$_POST["hdnSelect"]
But when I try get it's value on the php server side code, it is empty,..
How on earth do I retrieve it?
the hidden input is inside the form tag.
<?php
function Stores()
{
global $wpdb;
global $MyPage;
$MyPage = str_replace( '%7E', '~', $_SERVER['REQUEST_URI']);
?>
<form name="frmSB_stores" method="post" action="<?php echo $MyPage ?>">
<input type="hidden" name="hdnSelect" id="hdnSelect" value="">
<input type="text" name="txtSelection" size="19" id="txtSelection" value="">
<script type="text/javascript">
function SetDDLValueOnChange (objDropDown) {
var objHidden = document.getElementById("hdnSelect");
if ( objDropDown.value.length > '0')
{
objHidden.value = objDropDown.value; //.substr(0,1);
//alert(" hdn = " + objHidden.value);
window.location = '<?=$MyPage;?>' ;
}
}
</script>
the dropdown's markup here,..then
<table width='100%' border='0' cellspacing='5' cellpadding='3'>
<?php
$Area = $_POST['txtSelection']; //or $_POST['hdnSelect']
which has zilch in it , even though it is set successfully by jvascript
Why is this such an issue in WordPress,
How do i overcome it.
It's nuts spending a full day on something which should be so trivial (works fine in a normal php situation, os asp or asp.net,..but not in WP.)!
TIA
N
This doesn't submit the form it just tell the browser to goto that page. Hence your value always empty.
window.location = '<?=$MyPage;?>' ;
Replace that line with this instead.
document.forms["frmSB_stores"].submit();

Categories