Subtract number from column and add to another - php

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

Related

display next record from database [PHP / MYSQL]

So I have a database, with a table in it. In the table, there's only one "ID" field
ID
1
2
3
..
what I want to do is to display the ID individually on my page, starting from ID=1. and when I click a button, the next ID will be displayed (ID=2, ID=3, .. each button click)
So this is my code
<?php
...
$id = (isset($_GET['id']) ? intval($_GET['id']) : 1);
$result = $db->query("SELECT * FROM id_table WHERE id>='$id' ORDER BY id ASC limit 2 ");
$row = $result->fetch_assoc();
...
<form action="" method="POST">
<h1 class="mb-3">
<?php echo($row['id'])?>
</h1>
<button onclick="" class="btn btn-primary btn-xl">Next</button>
</form>
ID is successfully displayed. But I've been struggling to make a working next button.
If this is a bad coding, please let me know and point me in right direction, so I can fix my mistakes. Thank you in advance, have a great day!

How to submit the values of form before update and after update

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.

Print specified page, update DB MYSQL and PHP

I have the following code:
<iframe onscroll ="caise4.php" name="frame4"></iframe>
<input type= "submit" onclick ="frames['frame4'].print()" value = "WATER/ELECTRICITY" id = "id4"></a>
This would allow me to print a different page when the button/frame is clicked.
And i have the following PHP code:
<?php
if(isset($_POST['frame4'])){
$SQL_1 = "INSERT INTO `tick4` (`ticket_id`, `ticket_date`) VALUES (NULL, CURRENT_TIMESTAMP)";
$result_1 = mysqli_query($db, $SQL_1);
$SQL_2 = "UPDATE v_attente_service AS vas
JOIN (SELECT COUNT(ticket_id) AS cnt FROM tick4) AS ti
SET vas.NOMBATTE = ti.cnt
WHERE vas.CODESERV=4";
$result_2 = mysqli_query($db, $SQL_2);
}
?>
When the user clicks, a new row needs to be inserted in the table "tick4". Then "NOMBATTE" in "v_attente_service" is updated.
Basically, when the user prints a ticket, the number of tickets is updated, and the number of people waiting in the queue is also updated.
The problem I have: I get redirected to the page preview, but nothing is displayed there. Also, nothing gets updated in my tables.
I am using phpMyAdmin by the way.
Any help would be greatly appreciated. Thank you.

Adding and updating db row with PHP/AJAX

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.

PHP/MySQL Like Button

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.

Categories