I've got a bit of a strange situation, Im building a site to keep track of outgoings, on my website you can insert an infinite number of 'outgoings' or 'bills' into my table, this is done using AJAX.
Once inserted, the record then shows up on the page and the user has an option to update, or delete the record.
My problem, is that when the record is inserted and posted back, I don't know what ID the record has fr4om the table so the update function doesn't work correctly. I've tried adding a a hidden field 'random-key' that when the user inserts a record, a random number is inserted and the this is posted back for my update function only I cant seem to get it working.
Has anybody an idea on how best to perform this?
Thanks
My code...
PHP form
<form id='bill-upd'>
<input type='hidden' value='".$info['rand']."' name='rand2' id='rand2'>
<input type='hidden' value='".$info['id']."' name='billid' id='billid'>
Total <input type='text' id='total' name='total' /><br />
Bill name<input type='text' id='bill-name' name='bill-name' /><br />
Bill descriptiion <input type='text' id='bill-description' name='bill-description' /><br />
Bill colour<input type='text' id='bill-colour' name='bill-colour' />
<input type='button' value='submit' onClick='updateBill();' />
</form>
UPDATE PHP PAGE
$uid = $_SESSION['oauth_id'];
$id = mysql_real_escape_string($_POST['billid']);
$bill = mysql_real_escape_string($_POST['total']);
$billname = mysql_real_escape_string($_POST['bill-name']);
$billdescription = mysql_real_escape_string($_POST['bill-description']);
$billcolour = mysql_real_escape_string($_POST['bill-colour']);
$rand = mysql_real_escape_string($_POST['rand2']);
#update Record
$query = mysql_query("UPDATE `outgoings` SET id = '$id', user_id = '$uid', bill = '$bill', bill_name = '$billname', bill_description = '$billdescription', bill_colour = '$billcolour', rand = '$rand' WHERE user_id = '$uid' AND rand = '$rand' ") or die(mysql_error());
While Inserting the new record, Get the newly added id (assuming that you have a unique id for each record) from the table and return that as the part of result you are returning after your ajax call. Then you can use that id for updating the record.
You can use the below script to send the details to be updated to the update page
$("#bill-upd").submit(function(e){
e.preventDefault();
$.post("update.php",{
billid: $("#billid").val()
total: $("#total").val();
bill-name : $("#bill-name").val();
bill-description : $("#bill-description").val();
bill-color: $("#bill-color").val();
},
function(result){
//Update / Show a message to user about the action.
//alert(result);
});
});
});
And in your update.php page, change your query like this
$query = mysql_query("UPDATE `outgoings` user_id = '$uid', bill = '$bill', bill_name = '$billname', bill_description = '$billdescription', bill_colour = '$billcolour', rand = '$rand' WHERE id = '$uid' AND rand = '$id' ") or die(mysql_error());
Assuming ID is the unique id / Primary key in the table which we can use to update a table record.
When you use an INSERT query, you can use mysql_insert_id() to get the value of the AUTO_INCREMENT field created for the inserted row. You can send this back with JSON so Javascript knows the ID of your newly inserted row. However consider if another user (using a different browser) adds a row while another user has the page open, Javascript won't get the new row. Example:
User 1 loads page and sees no rows.
User 1 adds Row #1.
User 2 loads page and sees Row #1.
User 2 adds Row #2 and now sees Rows #1,2
User 1 adds Row #3, but only sees Rows #1,3
And now User 2 will only see rows #1,2
You should probably really be SELECT * from table after every query to make sure you have all rows (including the ones other users may have inserted). You should also consider using PDO.
Related
I'm a beginner in PHP and PDO.
I'm trying to fetch database data from a database table, display it on a list and add a button that when clicked it adds the itemid value to another table with the name_id of the user.
The issue is even though the list is displaying the items in order and correctly,the button is not working 100%, when pressed on any item from the list it always posts the first itemid value from the database column.
Any help is appreciated.
echo ''.$itemid.'';
echo'<form action="" method="post"><button name="get" type="submit">CLICK ME</button></form>' ;
if(isset($_POST['get'])){
$query = "update table set fetched_item_id='".$row['item_id']."' where name_id='".$_SESSION['id']."' ";
if($query)
{
$query = $conn->prepare($query);
$query->bindParam('1', $itemid);
$query->execute();
echo "Success!";
exit;
}
I tried everything I could according to my knowledge.
I have a form that retrieves data from a database and displays it in respective fields. The user then has the ability to make changes to the form and update those values. I'm able to correctly display the data from the database(SELECT) by clicking a submit button and update it as well(UPDATE) by clicking another submit button. What I want to do is store all the data before update in a separate table, sort of as an audit log that will tell me what the previous fields were and what the new update is like. I want to have both the Update and Insert query on the same submit button as well. How do I go about inserting the 'former' values in my table.
Here's my working update statement:-
if(isset($_POST['submit'])){
// Updating the dealer info using sfid
$sql = "UPDATE tbl_dealer_info ";
$sql .= "SET phone = '".$phone."', email = '".$email."', SFID = '".$sfid."', account_name = '".$account_name."', parent_account = '".$parent_account."', awi_code = '".$awi_code."', sales_portal_id = '".$sales_portal_id."', iae = '".$iae."', rsm_val = '".$rsm_val."', door_type_val = '".$door_type_val."', payment_method_val = '".$payment_method_val."', region_val = '".$region_val."', street_address = '".$street_address."', city = '".$city."', state = '".$state."', zip = '".$zip."', area = '".$area."', market = '".$market."', boost_app = '".$boost_app."', virgin_app = '".$virgin_app."', virgin_mob_app = '".$virgin_mob_app."', start_date = '".$start_date."', bank_name = '".$bank_name."', bank_acc_number = '".$bank_acc_number."', routing_number = '".$routing_number."' WHERE SFID = '".$sfid."' ";
$sql .= "LIMIT 1";
$result = mysqli_query($conn, $sql);
One easy way to do this is using hidden values example
<form>
<input type="text" name="phoneNumberNew">
<input type="hidden" name="phoneNumberOld">
</form>
With this what you can do is submit the form to wherever your table is held and populate the table where the textbox is the new data and the hidden one will be your old data. From there you can submit it onward using more hidden values or whatever means you see fit. This is just one option for you based upon technology everyone has available! :)
When the user submits, the form data will be sent to the action="" page you defined.
In that page, run the select query again, which will give you the current values.
Then run the update query.
In your log you can then output the current values (from the select you did before), and the new values (from the update fields you got from the form).
--- Added this after the OP`s comment:
Let`s say you have a page like profile.php to update a user.
User A goes to profile.php?username=A
User B goes to profile.php?username=B
you can then build your select and update queries and specify which user you want to update.
Another method, which is better and more secure is to setup a session cookie. You then read that cookie to know which session, and hence which user is using the page.
Obviously you want something to ensure the person modifying users is allowed to do so, but that is outside your question (users - roles - security management).
There will then be no chance of mixing up users.
What I want to do is have a button allows that when clicked takes away 1 from the column 'tickets' in the table 'event' and adds it to the column 'ticket' in the table 'user'.
Code for button
form action="sendellie.php" method="post">
<input type="submit" value="Buy tickets"/>
</form>
Snippet of Code for processing page (sendellie.php)
<?php
$sql = "UPDATE event SET tickets = tickets-1 WHERE name='Ellie Goulding'";
$sql = "UPDATE user SET ticket = ticket+1 WHERE name = '$uname'";
?>
The problem with the code above is that it does not work. It does not take away or add anything.
Any suggestions or tips would be much appreciated. Thanks
I have a form that shows some images and other data from a mysql table. Using radio buttons the 'galley' field for the selected image gets changed to 3. I have this working ok, however there should only ever be one value of 3 in the table. How could i change the code below to also change any 3 already in the table to a 1 value?
// if featured is checked, then set gallery field to 3
if(isset($_POST['featured'])){
$chk = (array) $_POST['featured'];
$p = implode(',',array_keys($chk));
$t = mysqli_query($link, "SELECT * FROM gallery WHERE id IN ($p)");
if ($t){
$q = mysqli_query($link, "UPDATE gallery SET gallery=3 WHERE id IN ($p)");
header('Location: galleryadmin.php'); exit();
}
else{
echo '<script type="text/javascript"> alert("Dog Has Not Been Featured, Try Again
Or Contact Site Developer") </script>';
}
}
Can anyone help?
UDPATE yourtable
SET gallery = IF(id = $p, 3, 1)
for records where id = $p, the if returns 3. For any other record, it returns 1, and those 1/3 values get assigned to the gallery field.
This is somewhat inefficient, if you're on a very large table, where it'd be re-writing all but one record to basically have the same value the record had before. Performance-wise, you might be better off using a transaction and two queries:
start transaction;
update yourtable set gallery=1 where gallery=3;
update yourtable set gallery=3 where id=$p;
commit;
which should theoretically only change two records: the "old" gallery-3, and the new one that's becoming gallery-3.
I've made a 'like' button for my product pages with this code:
<?php
if('POST' == $_SERVER['REQUEST_METHOD']) {
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type = "submit" value = "like"/>
</form>
Works like a charm excpet for one minor problem being that every visit to the page registers a 'like'.
Could someone help explain what i need to chnage/add in order that new 'likes' are only registered when the actual form is submitted?
Thanks
Dan
A better solution rather than submitting the page and the whole page reloading would be to make an AJAX request, this is how Facebook 'likes' work.
This can be achieved using the jQuery JavaScript library.
The general outline would be:-
1) Click button
2) Send AJAX request
3) Update HTML to show button has been clicked and prevent reclicking of button.
<?php
if($_POST['like']) {
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type = "submit" value = "like" name='like'/>
</form>
This should work ;-)
<?php
if ($_POST['like']){
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
?>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="POST">
<input type = "submit" name="like" value = "like"/>
</form>
First of all - in your sql you have:
`product_id` = '1'
do not use id value as a string:
`product_id` = 1
About your problem:
Add another condition:
if ('POST' == $_SERVER['REQUEST_METHOD']) {
if ( !empty($_POST['submitType']) && ( $_POST['submitType'] == 'like' ) ) {
$sql = "UPDATE table set `likes` = `likes`+1 where `product_id` = '1'";
$result=mysql_query($sql);
}
}
and in html:
<input type = "submit" name="submitType" value = "like"/>
Sounds like some kind of old question, but I wonder why noone has said, that op's approach doesn't sound quite right. You try to just count likes (set likes=likes+1). It has many disadvantages:
You miss information, who gave the like. Thus you won't be able to reconstruct the whole picture
Users won't be able to "undo" likes (as you don't record who liked the post)
In case of many concurrent likes I feel like you'd get some kind of data race or a long delays, because MySQL would need to process every request on a single field in order.
Much better idea is to create separate table in the DB named "product_likes" with columns like product_id, user_id, date. Of course, product id and user id should be unique together.
Thus you'll always know the full picture and will be able to see who liked the product. Even if accidentally you'll issue the second like from the same user about the same product, it won't be stored due to db constraints.
Also it will be possible to extend it to i.e. emotions-reactions, just by adding new column like "like_type" and updating the constraint correspondingly.