insert multiple input text at the same name in sql and php - javascript

i want to insert multiple input in the same table using php and sql
example:
<script language="javascript">
fields = 0;
function addInput() {
if (fields != 10) {
document.getElementById('text').innerHTML += "<input type='text' name='order'><br/>";
fields += 1;
} else {
document.getElementById('text').innerHTML += "<br />Only 10 insert fields allowed.";
document.form.add.disabled=true;
}
}
</script>
<form action='insert.php' method='post'>
<input type='text' name='order'>
<div id="text">
</div>
<br /><input type='button' value='add new input' onclick='addInput()'> <input type='submit' value='submit'>
</form>
in this code i have unlimited input, i have to insert it in:
dbtable = clients_order
row name : order
++++++++++++++++++
+ id + order +
++++++++++++++++++
so when i use this code :
$order=$_POST['order'];
foreach ($order as $insert_order) {
mysql_query("INSERT INTO clients_order (order)
VALUES ('$insert_order')");
}
Error message : Warning: Invalid argument supplied for foreach()
please help me to do that
thank you

The foreach() is complaining that $order isn't an array. If you use order[] as the name field in the HTML for your field, then PHP will turn them all into an array for you.
You should also check you have an array (use is_array()) before giving it to a foreach() loop. And you should call mysql_real_escape_string() over each piece of text from $orders in order to prevent SQL injection attacks.

Related

JavaScript not running correctly from HTML form

I'm creating a web front for a database using HTML, CSS, JavaScript and PHP for my uni coursework. I've only got so far as HTML and JavaScript form validation before I've run into this weird problem.
In my HTML, I link the JavaScript as follows:
<script type="text/javascript" src="dbicw2.js"></script>
Correct file name, I've checked.
Next, I have a form which takes a user's search. It upon submitting runs my JavaScript function, and its action is a PHP file. The code is as follows:
<form action="dbicw2.php" onSubmit="return validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
Again, correct PHP filename and JS function name.
Now, my JavaScript function seems to always return True, regardless of what happens. Currently, my JS looks like:
function validate(form)
{
alert("Hi")
for (var field in form.elements) { //For elements in form
field+="" //Incase it is undefined
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
return false //Failed validation
}
}
return true //Otherwise, successful validation
}
Not even the alert message at the top runs. The form just goes through and PHP is loaded, regardless of the JS. The script neither works in Edge.
This is baffling because my code is a near clone of my professor's example, which works.
What is causing the Javascript to not be run and the PHP action done?
Edit: my professor's example code, which works:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>(prof name)</title>
<LINK REL='stylesheet' TYPE='text/css' HREF='dbicw.css'>
<script type="text/javascript" src="dbicw.js"></script>
</head>
<body>
<h1>Search for a Movie by Title</h1>
<form action="search_movie_example.php" onSubmit="return validate(this)">
Movie title:<br>
<input type="text" name="title">
<br>
<br>
<input type="submit" value="Search">
</form>
</body>
</html>
JavaScript:
function validate(form)
{
var ok=1
var msg=""
for (var i = 0; i < form.length; i++) {
if (form.elements[i].value.trim() == "") {
msg += "'" + form.elements[i].name + "' is void. "
ok=0
}
}
if (ok == 0) {
alert(msg)
return false
}
else {
return true
}
}
I think I found a mistake (hopefully THE mistake) in your code. It's really simple, but very common.
You iterate over your form elements using for (var field in form.elements), but this will iterate over the index values of the form elements, rather than over the actual elements. Change in to of to iterate over the actual values instead.
Example:
let arr = ['foo', 'bar', 'cat'];
for (let word in arr) {
console.log(word); // prints 0, 1, 2
}
for (let word of arr) {
console.log(word); // prints foo, bar, cat
}
Try this:
function validate(form) {
event.preventDefault();
alert("Hi")
for (var field of [...form.querySelectorAll('input:not([type="submit"])')]) { //For elements in form
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
}
}
}
<form action="dbicw2.php" onsubmit="validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
I added an event.preventDefault() so the page wouldn't be redirected in the live example, and changed the in to of while also altering the statement that "fetches" the input elements. The of simply allows you to iterate through the array, and the actual selector just gets all the input elements that are not of the type submit.
If you only want to alter your code to make it work, then try this:
function validate(form) {
alert("Hi")
for (var field of [...form.elements]) { //For elements in form
alert("This element: '" + field.value + "'")
if (field.value.trim() == "") { //If the string is empty
alert(field.name + " is empty.") //Alert message
return false //Failed validation
}
}
return true //Otherwise, successful validation
}
<form action="dbicw2.php" onSubmit="return validate(this)">
<input type="text" name="title">
<input type="submit" value="submit">
</form>
I again changed the in to of, and added a spread operator to convert the HTMLFormControlsCollection to an array.

Dynamically add text box in javascript

I dynamically add a text box whenever a user clicks a button to add more, which works fine. However, in PHP when I get the submitted field values by $_POST['skills'] , I only receive the first text box value, not the dynamically added ones. I'm almost positive there is something wrong with the way I am adding the text boxes in javascript.
I use the following method to add a text box field:
function addTextBoxField()
{
var input = document.createElement('input');
input.type = "text";
input.name = "skills[]";
input.size = "30";
var container = document.getElementById("skillfield");
container.appendChild(input);
}
The HTML code I have for the text box is :
...
<td>
<div id="skillfield">
<input type="text" size="30" name="skills[]" />
</div>
</td>
<td><div class="button">+ Add</div></td>
Here is the php code as well:
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$allskills = $_POST['skills'];
$size = count($_POST['skills']);
print_r($allskills);
}
The output is the following, even though I inputted three values
Array ( [0] => java )
Your field name is skills not skill .So it should be $_POST['skills'].$_POST['skills'] is an array in this case. So access try with var_dump($_POST['skills']); and you will see all the values.
As far as the $_POST['skills'] is an array, Try this..
$skill = $_POST['skills'];
foreach($skill as $value){
echo $value;
}
do you mean the values of $_POST['skills']
i dont think there is something wrong with your javascript, what is wrong is how you read the post data in your php. The post data will be an array in this case, so you access it like this $_POST['skills'][0] //value of 1st input $_POST['skills'][1] //value of 2nd input
$_POST['skills'] is an array,So use print_r() to view the array.You may use as follows
<script type="text/javascript">
function addTextBoxField()
{
var input = document.createElement('input');
input.type = "text";
input.name = "skills[]";
input.size = "30";
var container = document.getElementById("skillfield");
container.appendChild(input);
}
</script>
<form method ="post">
<td>
<div id="skillfield">
<input type="text" size="30" name="skills[]" />
</div>
</td>
<td>
<input type="submit" name="submit" value="Submit"/>
</td>
</form>
<td><div class="button">+ Add</div></td>
<?php
if(isset($_POST['submit']) && $_POST['submit'] == 'Submit'){
echo "<pre>";
print_r($_POST['skills']);
echo "</pre>";
}
?>
you could use the array length. Try to this
for($i=0;$i<=count($skills)-1;$i++)
{
$per=$skills[$i]*$skills[$i];
echo $per;
}

Insert in query string only the values of the selected checkboxes with their respective quantities inputs

I'm having a problem here in mounting a query string with the variables that I need.
I have the following part of the code:
echo "<form class='additionals'>";
foreach($connection->query($sql2) as $additional)
{
echo "
<input class='additional-checkbox' type='checkbox' name='additional_id' value='{$additional['additional_id']}'/>{$additional['additional_name']} - ${$additional['additional_price']} <input type='number' name='additional_quantity' value='1' min='1' max='5'/><br/>
";
}
echo "</form>";
In this code snippet I get the values from database and insert each of them into a checkbox.
To get the values of the selected checkboxes I'm using jQuery:
$(document).ready(function()
{
$('.add').on('submit', function()
{
var product_id = $(this).closest('tr').find('.product-id').text();
var product_name = $(this).closest('tr').find('.product-name').text();
var quantity = $(this).closest('tr').find('input').val();
if ($(this).closest('tr').find('input.additional-checkbox').is(':checked'))
{
var additionals = $(this).closest('tr').find( '.additionals' ).serialize();
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity + "&" + additionals;
}
else
{
window.location.href = "add_to_cart.php?product_id=" + product_id + "&product_name=" + product_name + "&quantity=" + quantity;
}
return false;
});
});
Let's assume that only the checkbox with value 1 is selected and the input in front related to their quantity value is 3. My output should be something like:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additional_id=1&additional_quantity=3
Here is my little problem. I have part of the output as I want, but the values of the other quantity inputs are also inserted to serialize. By this way the output is like:
add_to_cart.php?product_id=4&product_name=Pizza&quantity=1&additional_id=1&additional_quantity=3&additional_quantity=1&additional_quantity=1
How to make only the quantity of inputs relating to the selected checkboxes appear in the Query String? How to relate the inputs of checkboxes with the quantity inputs?
It looks like
var additionals = $(this).closest('tr').find('.additionals')
returns multiple forms. Is it possible, that in single TR you have more than one such form?
Try this
<input name="quantity_id" type="checkbox" data-quantity-input="quantity">
<input name="quantity" type="input" value="">
// get the data-quantity-input
var qtyInput = $(this).data('quantity-input');
// find the corresponding value if checkbox is checked
find('input[name='"+ qtyInput +'"]').val();
"data" attribute should be unique. You can use the index inside "for" loop.

Retrieving values from data base, store in input text and textarea, change, pass new one to DB using PHP?

I'm Trying to change the values in the database using PHP and MySQL.
I am getting the values from database and storing them in placeholder for each input but when i submit the form again it submit the inputs with empty values, i tried storing them in Value attribute for each input again the old value is overwriting what i write in the input field so nothing in the database change.
How can i keep the old value in the input fields but in case the content of these fields changed the new value is passed back to the database instead of the old one.
Here is my Code :
function list_products () {
$get = mysql_query('SELECT `id`, `SKU`, `sub`, `pname`, `desc`, `price`, `ship`, `qty`, `cat` FROM `products` ORDER BY `id` DESC');
if (mysql_num_rows($get) == 0) {
echo "There are no product to display!";
} else {
while ($get_row = mysql_fetch_assoc($get)) {
echo
'<h5>'.$get_row['pname'].' id: '.$get_row['id'].'</h5>
<form action="delete_product.php" method="post">
<input type="hidden" value="'.$get_row['id'].'" name="id">
<input type="submit" name="submit" value="DELETE" class="btn btn-lg btn-danger">
</form>
<form action="update_p.php" method="post">
<input type="hidden" placeholder="'.$get_row['id'].'" name="id" value="'.$get_row['id'].'">
<label>SKU:</label>
<input type="text" placeholder="'.$get_row['SKU'].'" name="SKU" value="'.$get_row['SKU'].'" required="">
<label>Name:</label>
<input type="text" placeholder="'.$get_row['pname'].'" name="pname" required="" value="'.$get_row['pname'].'">
<label>Subtitle:</label>
<textarea rows="2" maxlength="46" name="desc" placeholder="'.$get_row['sub'].'" required="">'.$get_row['sub'].'</textarea>
<label>Description:</label>
<textarea rows="4" name="desc" placeholder="'.$get_row['desc'].'" required="">'.$get_row['desc'].'</textarea>
<label>Price:</label>
<input type="text" placeholder="'.number_format($get_row['price'], 2).'" name="price" value="'.number_format($get_row['price'], 2).'" required="">
<label>Shipping:</label>
<input type="text" placeholder="'.number_format($get_row['ship'], 2).'" name="ship" value="'.number_format($get_row['ship'], 2).'" required="">
<label>Quantity:</label>
<input type="text" placeholder="'.$get_row['qty'].'" name="qty" value="'.$get_row['qty'].'" required="">
<label>Category:</label>
<input type="text" placeholder="'.$get_row['cat'].'" name="cat" value="'.$get_row['cat'].'" required=""><br>
<input type="submit" name="submit" value="EDIT" class="btn btn-success btn-lg">
</form>
<hr>
';
};
}
}
The update_p.php page:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$update_data = array(
'pname' => $_POST['pname'],
'desc' => $_POST['desc'],
'price' => $_POST['price'],
'ship' => $_POST['ship'],
'qty' => $_POST['qty'],
'cat' => $_POST['cat']
);
update_product($id, $update_data);
The update_data function :
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
mysql_query("UPDATE `products` SET " . implode(', ', $update) . " WHERE `id` = $id");
}
#MaveRick Thanks for the effort, but my question is how to overwrite the value of the input fields on the page before we send the information to the server, i think its can be done using JavaScript more than php, however to make more clear these input fields refers to values in the database already stored and i would like to give the option for the user to change them in his admin panel by retrieving the content of these fields from the database and print them in the actual input fields so in case the customer pressed edit(submit) with out touching anything the same values will be sent again to the database this way nothing will be change, and in another case where the customer added or changed any value in any of these fields then the new value will be passed. hopefully i clarified my issue now. Thanks for your help anyway.
#Prafful Garg i already tried the value field but it didn't work thanks for your help anyway
You can retrieve the data again from the database in file update_p.php as follow:
if (empty($_POST) === false && empty($errors) === true) {
$id = $_POST['id'];
$get = mysql_query("SELECT * FROM `products` WHERE `id` = '$id';");
$get_row = mysql_fetch_assoc($get);
$update_data = array(
'pname' => (empty($_POST['pname'])?$get_row['pname']:$_POST['pname']),
'desc' => (empty($_POST['desc'])?$get_row['desc']:$_POST['desc']),
'price' => (empty($_POST['price'])?$get_row['price']:$_POST['price']),
'ship' => (empty($_POST['ship'])?$get_row['ship']:$_POST['ship']),
'qty' => (empty($_POST['qty'])?$get_row['qty']:$_POST['qty']),
'cat' => (empty($_POST['cat'])?$get_row['cat']:$_POST['cat'])
);
update_product($id, $update_data);
But this is not a professional way to do it.
What you can do is a loop to create the update statement and test each input; if not empty then add to the update statement , name=value otherwise to skip this input and process the next one in the array POST. something similar to the following:
function update_product($id, $update_data) {
$update = array();
array_walk($update_data);
foreach($update_data as $field=>$data) {
$update[] = '`' . $field . '` = \'' . $data . '\'';
}
$query = "UPDATE `products` SET `id` = '$id'";
foreach($update_data AS $k=>$v){
if(!empty($v) && strlen($v)>0)
$query .= ", `".$k."` = '".$v."'";
}
$query .= " WHERE `id` = '$id';";
mysql_query($query);
}
IMPORTANT NOTE: mysql() is vulnerable and deprecated, please try to avoid using mysql() and use mysqli() or dbo() extensions instead.

document.getElementById injecting Answer from prompt in to wrong place

A while ago I found a function (on here) that would allow me to launch a Javascript prompt box on form submit, it would take a value and then submit it alongside the submitted form.
I've been racking my brain as to why this isn't working correctly. At the moment, if I click submit on the form on a row that isn't the very first row in my table, it submits the form on the first row.
The function uses document.getElementById to find where it's entering the entered text but because it's a while loop, document.getElementById("invoiceEntry").value = answer; exists on every row of the table and it injects the text in to the very first instance.
Is there an easy solution to this?
Here's a snippet of my code:
<script language="Javascript">
function invoiceCollect() {
var answer = prompt("Enter invoice number:");
if(answer) { // answer = false if "cancel" pressed.
document.getElementById("invoiceEntry").value = answer;
return true;
}
else if(answer == "") { // return false if no input entered, i.e. ""
return false;
}
else
return false;
}
</script>
<form id='invoice' method='post' action='update_item.php' onsubmit='return invoiceCollect()'>
<input type='hidden' name='invoiced' >
<input type='hidden' name='id' value='" . $row['id'] . "' >
<input type='hidden' name='invoiceNo' id='invoiceEntry' value='' >
</form>
<input type='submit' value='Invoice' form='invoice'>
I will assume that the while loop you're talking about is server side, in PHP and it wraps the HTML you posted. If that is not the case, please comment and i will delete the answer as it would be off-topic.
Problem 1:
Your function shouldn't be defined in a loop. You want all your functions to do the same thing, maybe to a different element. A single function with the element as a parameter would be all that's needed.
Problem 2:
Identifying the correct element. This is the actual problem you're facing. All your functions use the first element with that ID because that's just how HTML is defined, it expects the IDs to be unique.
The simplest solution is to add the form as parameter to the function:
JavaScript:
function invoiceCollect(form) {
form.invoiceNo.value = 'WORKS';
}
HTML:
<form onsubmit = 'return invoiceCollect(this)'>
DEMO
Make the
<input type='submit' value='Invoice' form='invoice'>
before the
</form>
so it would be like this :
<script language="Javascript">
function invoiceCollect() {
var answer = prompt("Enter invoice number:");
if(answer) { // answer = false if "cancel" pressed.
document.getElementById("invoiceEntry").value = answer;
return true;
}
else if(answer == "") { // return false if no input entered, i.e. ""
return false;
}
else
return false;
}
</script>
<form id='invoice' method='post' action='update_item.php' onsubmit='return invoiceCollect()'>
<input type='hidden' name='invoiced' >
<input type='hidden' name='id' value='" . $row['id'] . "' >
<input type='hidden' name='invoiceNo' id='invoiceEntry' value='' >
<input type='submit' value='Invoice' form='invoice'>
</form>

Categories

Resources