shorter way to collect data and update a table - javascript

here is my way to submit a form.
In reality it has much more text inputs.
Everything works fine, but I hope there is a shorter way, especially on server side, regarding that data-col on client side is in fact a corresponding column name on server.
html
<form id='dform'>
<input type='text' class='dinp' data-col='nick'>
<input type='text' class='dinp' data-col='state'>
<input type='text' class='dinp' data-col='city'>
<input type='text' class='dinp' data-col='uname'>
<input type='text' class='dinp' data-col='pass'>
</form>
js
$('#msave').on('click', function(){
let id=$('.aact').attr('data-id');
let obj = {};
$('.dinp').each(function(){
let col = $(this).attr('data-col');
obj[col] = $(this).val().trim();
});
obj = JSON.stringify(obj);
$.post('a_users_pro.php', {fn: 'm_save', args: [id, obj]}, function(data){
console.log(data);
});
});
php
function m_save($id, $obj){
global $db;
$obj = json_decode($obj);
$sql = "
update users
set nick = :anick
, state = :astate
, city = :acity
, uname = :auname
, pass = :apass
where id = :aid
";
$st = $db->prepare($sql);
$st -> execute([
":aid" => $id,
":anick" => $obj->nick,
":astate" => $obj->state,
":acity" => $obj->city,
":auname" => $obj->uname,
":apass" => $obj->pass
]);
}

You can use the name attribute of input elements with your data-col value and pass the serialized form data to the AJAX request. Here is a implementation:
HTML:
<form id="myForm">
<input type="text" name="name" placeholder="name">
<input type="email" name="email" placeholder="email">
<input type="number" name="age" placeholder="age">
<input type="hidden" name="id" value="1">
<button type="submit">Submit</button>
</form>
JavaScript:
$(document).ready(function() {
$('#myForm').on('submit', function(e) {
e.preventDefault();
$.post('update.php', $('#myForm').serialize());
});
});
PHP:
<?php
if (isset($_POST)) {
// Validate request
$sql = 'UPDATE users
SET
name = :name,
email = :email,
age = :age
WHERE id = :id
';
$st = $db->prepare($sql);
$st->execute([
':id' => $_POST['id'],
':name' => $_POST['name'],
':email' => $_POST['email'],
':age' => $_POST['age'],
]);
}
?>
In your example I can't see where .aact and data-id come from. I assumed that the id value would be available to the view so I passed it to the request as a hidden input.

Related

how to get two dynamic textbox value in jquery

Thanks in advance, Actually i have a form with two hidden textbox fields one is <input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>"> and the other is <input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">, the the value is taken inside the hidden field dynamically from PHP code through loop. So how can i get the dynamic values of "item_name" textbox field and "amount" textbox field in comma seperated using Jquery when clicking the image button with id="placeOrder".
For example like this : for amount-->200,300 and for course name -->PMP,CAPM . I have written some code it will take the values within the jquery each loop but i have to pass through ajax as json format like this data : {cname:course_name,priceBox:textboxVal} so value with comma seperated value should pass through course_name & textboxVal.
My Page is
<html>
<head>
<title></title>
<script>
$(document).ready(function(){
var myArray = [];
$('.amount').each(function(){
var textboxVal = $(this).val();
//alert(textboxVal);
});
var myCourse = [];
//dynamic course name
$('.course_name').each(function(){
var course_name = $(this).val();
//alert(course_name);
});
if(textboxVal!="")
{
$.ajax({
type : "POST",
url : "/invl_exams/cart",
cache : "false",
data : {cname:course_name,priceBox:textboxVal},
success : function(result){
console.log(result);
}
});
}
});
</script>
</head>
</html>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
<td>
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="shopbusiness#myshop.com">
<input type="hidden" name="upload" value="1">
<?php
if(isset($cartDatas))
{
$itm_no = 1;
$amt = 0;
foreach($cartDatas as $key=> $cartData)
{
$prices = $cartData['price'];
$prd_price = ltrim($prices,'$');
$priceTotal = number_format((float)$prd_price, 2, '.', '');
?>
<input type="hidden" name="item_number" value="<?php echo $itm_no++;?>">
<input type="hidden" name="item_name" class="course_name" value="<?php echo $cartData['exam'];?>">
<input type="hidden" name="amount" class="amount" value="<?php echo $priceTotal;?>">
<input type="hidden" name="shipping" value="shipping Address">
<input type="hidden" name="quantity" value="<?php echo $cartData['orders'];?>">
<?php
$price = ltrim($prices,'$');
$orders = $cartData['orders'];
$amt_Total = $price * $orders;
$amt += $amt_Total;
$amt_Total = number_format((float)$amt, 2, '.', '');
///$amt_Total = round($price * floatval( $orders ),2);
}
?>
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="amount" value="<?php echo $amt_Total;?>">
<?php
}
?>
<input type="image" src="http://www.paypal.com/en_US/i/btn/x-click-but03.gif" name="submit" id="placeOrder">
</td>
</form>
You can do something like following:
$(function(){
var amount = [];
var course = [];
$('.amount').each(function(){
amount.push($(this).val());
});
$('.course_name').each(function(){
course.push($(this).val());
});
console.log(amount.join(',')); //comma seperated value
console.log(course.join(',')) //comma seperated value
});
DEMO
You can use jQuery and attribute selectors to get the value:
var item_name = $('input[name=\'item_name\']').val();
var amount = $('input[name=\'amount\']').val();
var result = item_name + ',' + amount;
Now you can put this in your click handler.
If your inputs are enclosed within form element you can use this serialize the form input values to json object and then pass it to ajax call.
var postData = $("#enclosing_form_elm").serializeObject();
and in your script add reference to serialize object function after jquery
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Just a demo https://plnkr.co/edit/7maJAUSdakDuvVqXhnzi?p=preview
Thanks to Convert form data to JavaScript object with jQuery

Creating multidimensional array from dynamic form in JQuery

I'm trying to capture values from inputs and put them in JQuery object instead of having to deal with PHP indexing.
This is the form
<form name="second_form" id="second_form" action="#" method="POST">
Add Champion
<div id="ChampionInput">
</div>
<br><br>
<input id="obj" type="hidden" name="obj">
<input type="submit" name="submit">
</form>
My script that I'm trying to use to recreate the array:
$("#second_form").submit(function(event) {
var object = [];
$('.Champion').each(function() {
var champion = {
'name': $(this).find(".ChampionInput").val(),
'change': $(this).find("input:radio:checked").val(),
'General_Description': [],
'General_Change':[]
};
$(this).find('.GeneralChange').each(function() { champion.General_Description.push($(this).children(".GeneralChangeDescription").val());
champion.General_Change.push($(this).children(".General_Change").val());
});
object.push(champion);
});
object = JSON.stringify(object);
$('#obj').val(object); //Sending object to hidden input
});
And here is the way I used to create this PHP array which messes up indexing when I delete some inputs when creating the form
foreach($_POST['champion'] as $champion){
if(isset($_POST['Release'][$ChampionNumber])){
$_POST['Release'][$ChampionNumber]=='New' ? $champions[$champion]['New']=1 : $champions[$champion]['New']=0;
$_POST['Release'][$ChampionNumber]=='Rework' ? $champions[$champion]['Rework']=1 : $champions[$champion]['Rework']=0;
}
if(!empty($_POST['GeneralChangeDescription'][$ChampionNumber])){
foreach($_POST['GeneralChangeDescription'][$ChampionNumber] as $indexGeneral=>$GeneralChangeDescription){
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] =ucfirst(trim($GeneralChangeDescription));
if(substr($GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1], -1)!='.'){
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1].'.';
}
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace('/\s\/\s/','/',$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/(\.?\d\/?%?)+/', '<strong>$0</strong>', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
$GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1] = preg_replace( '/\b\w+\.(jpg|png|gif)/', '', $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1]);
$champions[$champion]['General']['Change'][] = $GeneralChangeDescriptions[$ChampionNumber+1][$indexGeneral+1];
$champions[$champion]['General']['Type'][] = $_POST['GeneralChange'][$ChampionNumber][$indexGeneral];
}
}
$ChampionNumber++;
}
Removing champions
$('div#ChampionInput').on('click', 'a.Remove',function(){
var champion = $(this).closest('.Champion');
var id = champion.data("id");
var nextChampion = champion;
while((nextChampion = nextChampion.next()).length != 0){
nextChampion.attr("data-id",id++);
nextChampion.children('.ChampionInput').attr('placeholder','Champion '+ id);
}
championNumber=id+1;
championNumberArray=id;
champion.remove();
});
Removing changes
$('div#ChampionInput').on('click', 'a.RemoveGeneralChange',function(){
$(this).closest('.GeneralChange').remove();
});
Here is how my array looks like in PHP: http://i.imgur.com/rURnNTG.png and I want to get array looking like that after sending JQuery object through hidden input in form and obtaining it in PHP. Here is how my JQuery object looks like right now http://imgur.com/2r9iyKN which is not even close.
Here is also JSfiddle of form creation: jsfiddle.net/g50zd384/
If you really need that array, so create it in PHP after sending the form:
$array;
for($i = 1; $i <= count($_POST['champion']); $i++) {
$champion = $_POST['champion'][$i];
$array[$champion]['General'] = $_POST['GeneralChangeDescription'][$i];
$array[$champion]['Type'] = $_POST['GeneralChange'][$i];
$array[$champion]['Release'] = $_POST['Release'][$i];
}
Your form should be created with this names:
championNumber = 1;
championNumberArray = 0;
$('a#AddChampion').on('click',function(){
$('div#ChampionInput').append(
'<div class="Champion">\
<br>\
<input type="text" class="ChampionInput" name="champion['+championNumber+']" placeholder="Champion '+championNumber+'">\
<datalist id="champions"></datalist>\
<input type="radio" name="Release['+championNumber+']" value="New">New\
<input type="radio" name="Release['+championNumber+']" value="Rework">Rework\
<input type="radio" name="Release['+championNumber+']" value="None" checked>None\
Add General Change\
<div class="GeneralChanges">\
</div>\
<br>\
<div>');
championNumber++;
});
$('div#ChampionInput').on('click','a.AddGeneralChange', function(){
var id = $(this).data('id');
$(this).siblings('.GeneralChanges').append(
'<div class="GeneralChange">\
<textarea type="text" size="20" rows="3" cols="50" maxlength="500" class="GeneralChangeDescription" name="GeneralChangeDescription['+id+'][]" placeholder="Enter General Change Description"></textarea>\
<select class="General_Change" name="GeneralChange['+id+'][]">\
<option value="buff">Buff</option>\
<option value="nerf">Nerf</option>\
<option value="new">New</option>\
<option value="change">Change</option>\
<option value="bugfix">Bugfix</option>\
</select>\
</div>');
});
It is important, that you name your inputs in this way!
..not the best way, but better than sending json data in a hidden input form. I hope this could help you.

Posting JavaScript Variable to MySQL using PHP

I am trying to send a JavaScript variable to PHP but not exactly sure how to do it, a few things have said Ajax but I've never used it before and can't get my head around it. Does anyone know what the easiest way to do this would be? The column which I am attempting to populate in my DB is called 'cogs'.
I have the following JavaScript code:
<script>
$(document).ready(function() {
$('#duration-select').change(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#request').removeClass('hidden');
$('#duration-value').text('Total cost for this duration = ' + (y) + ' cogs');
if($(this).val() !== '') {
} else {
$('#duration-value').text('');
}
});
$('#request').click(function() {
var cogs = $('#cogsday').html();
cogs = cogs.replace(/\D/g,'');
var x =$('#duration-select').val();
var y = cogs * x;
$('#total').text(y);
});
});
</script>
And the following HTML code:
<label id="total"></label>
Here is where I am trying to post the data, everything else is posting except for the $cost:
<form name="form" method="post">
<div class="modal-footer">
<?php
if ($row3['availability'] === 'Available') {
if (isset($_POST['request'])) {
$to_id = $row3['customerid'];
$from_id = $_SESSION['customerid'];
$time_sent = date('Y-m-d H:i:s');
$subject = 'Request for ' . $row3['title'];
$title = $row3['title'];
$listingid = $listingid;
$cost = $_POST['total']; //posting 0
$message = $customer_data['first_name'] . ' ' . $customer_data['last_name']
$request = mysql_query("INSERT INTO messages (to_id, from_id, listing_id, time_sent, subject, message, cogs, messagenumber, title, msgrand) VALUES ('$to_id', '$from_id', '$listingid', '$time_sent', '$subject', '$message', '$cost', '1', '$title', '$randomString')") or die(mysql_error());
}
}
?>
<input type="submit" class="btn btn-success" name="request" value="Yes" />
<input type="submit" class="btn btn-danger" data-dismiss="modal" value="No" />
</div>
</form>
Then I am trying to post the value of the label id=total to my db or the JavaScript variable (y). The problem is that 0 is always being sent to the DB when it should instead be the value that is in the label where the id is total.
Use name parameter for hidden variable and it will be automatically passed to PHP .
<label id="total"></label>
<input type="hidden" name="total" id="nameID"/>
in javascript below $('#total').text(y); write $('#nameID').val(y); . Everything will work properly.
You used total label , but $_POST recognizes only input type so use input type=.... instead of a label,divs etc.
IF YOU REAllY NEED ANSWER REPLY HERE
you have make an input type and its value is to be set by that javascript and then you'll be able to get that $cost value in php code
<input type="hidden" value="" name="total" id="total">
..................
$("#total").val(y);
You can use this to send the variables....
<input type="text" id="name" class="name" placevalue="Enter you name" required /><br><br>
<input type="text" id="email" class="email" placevalue="Enter you name" required /><br><br>
<button id= "det_submit" onclick="submit_det()"> Submit </button>
<script>
function submit_det() {
var name = document.getElementById("name").value;
var email = document.getElementById("email").value;
if(name != "" && email != "") {
$.post(
'xx.php',
{
name : document.getElementById("name").value,
email1 : document.getElementById("email").value,
},
function(data){
alert(data);
});
} else {
alert("empty");
}
}
</script>
here is xx.php
<?php
if(isset($_POST['name']) && isset($_POST['email1'])) {
$name = $_POST['name'];
$email = $_POST['email1'];
//code to insert into your database......
}
?>
Use a ID and Name for hidden parameter like this
<label id="total"></label
<input type="hidden" name="name" id="name"/>
and in jQuery edit the code like this
$('#total').text(y);
$('#nameID').val(y);
hope that it will work

Keep getting null on create user

Hello guys i have this php jquery ajax create user form that passes the create details to the php script but i keep getting null on the post variables anyhelp would be appreciated! code below
Html:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*" id="createUserPass">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" id="createUserPass">
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control"><option value="yes">Ja tak!</option><option value="nej" selected="">Nej tak</option></select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
jquery:
$(document).ready(function(){
$("#submitCreateUser").click(function(){
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#createUserPassC").val();
var newsletter = $("#newsletter").val();
$.ajax({
type: "POST",
url: "createuserajax.php",
data: "username="+username+"&email="+email+"&pass="+pass+"&cPass="+cPass,
success: function(html){
if(html=='true')
{
alert(username);
}
else
{
}
},
}
);
});
});
PHP:
<?php
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
var_dump($username);
$securePassword = md5(($password));
$sqlInsertUser = "INSERT INTO users (username,email,password) VALUES ('$username','$email','$securePassword')";
$result = mysqli_query($con,$sqlInsertUser);
As adeneo says, your html form is likely being submitted the standard way before the ajax call is made because you haven't prevent the default behaviour. try the below instead:
Alternatively, you could remove <input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!"> and give the id="submitCreateUser" to some other element like a custom button or link. When you click and input tag with the type submit it will submit the accompanying form the normal way by default. This happens before the click handler hears the click so the form is submitted before your code call the ajax. Use a different element for the click and this wont happen
And don't forget for this to work at all, your php file must echo something which will be returned in your html variable, without that html will never be true and nothing will ever happen.
Part of your problem is that your input elements, specifically the ones for the password and password checks both have two separate id tags the first is duplicated and the second is a different id altogether. Also in your jquery, when you try to get the id check value you use another, different, id.
Here is a test page that address all of these issues and works as expected:
http://dodsoftware.com/sotests/createuserajax.html
The test php code:
<?php
if( isset($_POST) )
{
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['pass'];
echo 'username --'.$username.', email --'.$email.', password --'.$password;
}
?>
The html code:
<form method="post" action="" id="createForm">
<input type="text" name="createUser" class="form-control" placeholder="Brugernavn*" id="createUser">
<input type="email" name="createUserEmail" class="form-control" placeholder="Email*" id="createUserEmail">
<input type="password" name="createUserPass" id="createUserPass" class="form-control" placeholder="Kodeord*">
<input type="password" name="confirmUserPass" id="confirmUserPass" class="form-control" placeholder="Bekræft Kodeord*" >
<!-- these lines had duplicated id tags-->
<h4 id="newsletterText">Vil du have vores nyhedsbrev?</h4>
<select name="newsletter" id="newsletter" class="form-control">
<option value="yes">Ja tak!</option>
<option value="nej" selected="">Nej tak</option>
</select>
<input type="submit" name="submitCreateUser" class="btn btn-success" id="submitCreateUser" value="Opret!">
</form>
The jQuery code:
<script>
$(document).ready(function() {
$("#submitCreateUser").click(function( event ) { // add event var here
event.preventDefault(); // add this line to stop the form from submitting the normal way before the ajax call
var username = $("#createUser").val();
var email = $("#createUserEmail").val();
var pass = $("#createUserPass").val();
var cPass = $("#confirmUserPass").val(); // you were using "#createUserPassC" here in error
var newsletter = $("#newsletter").val();
var datastring = "username=" + username + "&email=" + email + "&pass=" + pass + "&cPass=" + cPass +"&newsletter=" + newsletter;
$.ajax({
type: "POST",
url: "createuserajax.php",
data: datastring,
success: function(html) {
if (html) { // changed this line from "if (html == 'true')" just for testing
alert(html); // changed this line from "alert(username);" just for testing
} else {
alert('something went wrong!');
}
},
});
});
});
</script>

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.

Categories

Resources