Automatically deletion of row - php

I am working a database where, I insert a row in a particular table. Then for some reason I update the same row from the same table and then fetch the values from that row in a html form. Now, the issue is when I do this, the first time I fetch the values it is correctly functioning. The next time I do this (normally after 12 to 24 hours) the values are not being fetched. I checked the database, the table no longer holds the record that I updated earlier. I am confused over this. Is there any solution for this. Please help. Thanks.
Here is my update query that I use to update the record :
$upd = "update billingrates set FirstCopyFront='".$firstcopy1."', FirstCopyFB='".$firstcopy2."', Upto50F='".$Lfiftycopies1."', Upto50FB='".$Lfiftycopies2."', Morethan50F='".$Mfiftycopies1."', Morethan50FB='".$Mfiftycopies2."', PrinterType='".$printertype."' where PaperTypeId = '".$id."' and CustomerId = '".$cid."'";
And this is how I am getting the values from previous form that I am using for updation :
$firstcopy1 = trim(mysqli_real_escape_string($link, $_POST['firstcopy'][0]));
$firstcopy2 = trim(mysqli_real_escape_string($link, $_POST['firstcopy'][1]));
$Lfiftycopies1 = trim(mysqli_real_escape_string($link, $_POST['Lfiftycopies'][0]));
$Lfiftycopies2 = trim(mysqli_real_escape_string($link, $_POST['Lfiftycopies'][1]));
$Mfiftycopies1 = trim(mysqli_real_escape_string($link, $_POST['Mfiftycopies'][0]));
$Mfiftycopies2 = trim(mysqli_real_escape_string($link, $_POST['Mfiftycopies'][1]));

Related

How to display both old and new values of particular column in sql on html using php?

Let us assume there is a form which has a text field and a submit button.
Every time I type a text and submit it should be stored in the database and displayed in a table.
Additionally, when I again submit the form the old text in SQL column value should be overwritten with this new value and both values should be displayed in table rows.
So every time I do this I want old data and new data to be appended to table rows.
How to achieve this??
Instead of overwriting the data, why not create a new entry and mark it as active, such that to get the latest data using sql, you order by primary key desc limit 1. If you need the old data you ust get the previous entry.
We have very few information, but here is some idea to achieve it :
1/ Add an last field in your table and update it each time you add a new data, then when you display it just get all data and check the last field to see which one is the last :
So imagine this table :
Table data
===============================
id_data | id_user | data | last
When you display it for your user :
select * from data where id_user = :id_user order by last desc;
This way you will get the last one with last = 1 (true) first then the other.
And when you submit a new data :
// you update all old data as "old"
update data set last = 0 where id_user = :id_user;
// you create a new data
insert into data (id_user, data, last) values (:id_user, :data, 1);
2/ Add a field date so you know wich one are older than other
Table data
==================================
id_data | id_user | data | created
When you display it for your user :
select * from data where id_user = :id_user order by created desc;
This way you will get the data order by the created date with the last one first.
And when you submit a new data :
// you create a new data with the current date
insert into data (id_user, data, created) values (:id_user, :data, NOW());
This solution is better I think so you can have some "historic" of each data.
Is it what you are looking for?
why not just append it with a pipe character like so... "|entry_data" then just explode it when you need it.
var data_array = explode("|",data);
print_r(data_array);
If you want to show all changes only for some users then better to save you last value in main table and create new history table for changes.
table_history
id | id_row | field | before | after
In this case you can without additional query show last value for some users and all data for others.
In this structure you also can save multiple fields data if you need.
And believe me, saving previous value in your table will make you life is easy in future.
In given below code i update field with new one insert data and also append your new data with old I hope this help you
Form from which you insert and update data
if(isset($_POST['submit']) && $_POST['submit']){
$text_field = $_POST['text_field'];
$query ="SELECT * FROM `table_name`"; //replace with your table name
$run=mysqli_query($conn,$query);
$result = mysqli_fetch_row($run);
$data = $result[1];
if(count($result)){
$last_string = $data.','.$text_field;
$update= "UPDATE `table_name` SET `text`='".$last_string."'";
mysqli_query($conn,$update);
}else{
$query = "INSERT INTO `table_name`(`text`) VALUES ('".$text_field."')";
mysqli_query($conn,$query);
}
}
?>
<form action="" method="POST">
<input type="text" name="text_field">
<input type="submit" name="submit">
</form>
view of data which is inserted
<?php
$query ="SELECT * FROM `table_name`";
$run=mysqli_query($conn,$query);
$result = mysqli_fetch_row($run);
if(isset($result) && count($result)){
echo "<p>$result[1]</p>";
}

Inserting data into multiple tables not functioning correctly

I have the following two tables
Table player:
player_id (int)(primary)
player_name (varchar)
player_report_count (int)
Table report:
report_id (int)(primary)
player_id
report_description
report_location
Firstly I ask the user for the player_name and insert it into the player database. From here the player is given an id.
Then I tried to grab the value of the players report count and increment the current value by one (which isn't working).
This is followed by grabbing the playerId from the player table and then inserting into the corresponding column from the report table (also does not work).
When I insert some values into the database, the names, description and report are added to the database however the playerID remains at 0 for all entries and the player_report_count remains at a consistent 0.
What is the correct way to make these two features function? And also is there a more efficient way of doing this?
<?php
$records = array();
if(!empty($_POST)){
if(isset($_POST['player_name'],
$_POST['report_description'],
$_POST['report_location'])){
$player_name = trim($_POST['player_name']);
$report_description = trim($_POST['report_description']);
$report_location = trim($_POST['report_location']);
if(!empty($player_name) && !empty($report_description) && !empty($report_location)){
$insertPlayer = $db->prepare("
INSERT INTO player (player_name)
VALUES (?)
");
$insertPlayer->bind_param('s', $player_name);
$reportCount = $db->query("
UPDATE player
SET player_report_count = player_report_count + 1
WHERE
player_name = $player_name
");
$getPlayerId = $db->query("
SELECT player_id
FROM player
WHERE player_name = $player_name
");
$insertReport = $db->prepare("
INSERT INTO report (player_id, report_description, report_location)
VALUES (?, ?, ?)
");
$insertReport->bind_param('iss', $getPlayerId, $report_description, $report_location);
if($insertPlayer->execute()
&& $insertReport->execute()
){
header('Location: insert.php');
die();
}
}
}
Main issue here is you are getting player details before inserting it. $getPlayerId will return empty result always.
Please follow the order as follows.
Insert player details in to player table and get payerid with mysql_insert_id. After binding you need to execute to insert details to the table.
Then bind and execute insert report .
Then update the player table by incrementing report count with playerid which you got in step 1.
Note : use transactions when inserting multiple table. This will help you to rollback if any insert fails.
MySQL Query will return result object. Refer it from here https://stackoverflow.com/a/13791544/3045153
I hope it will help you
If you need to catch the ID of the last insterted player, This is the function you need if you're using PDO or if it's a custom Mysql Class, you need the return value of mysql_insert_id() (or mysqli_insert_id()) and then directly use it in the next INSERT INTO statement

firbird UPDATE or INSERT without changing unique ID

I have this query in PHP
$id = ibase_gen_id(TABLE1_ID_GEN);
$query = "UPDATE OR INSERT INTO TABLE1(ID, TESTER_ID, LOT_ID, TEST_STEP) VALUES (.....)
MATCHING (TESTER_ID, LOT_ID, TEST_STEP)";
$processQuery = ibase_query($query);
this query works but when updating the record, the ID also updated. I want to update the record (TESTER_ID, LOT_ID, and TEST_STEP) without updating/changing its ID.
Thanks!

How to insert a custom inscription ID of a user in mysqli?

I'm working on a school manager script.
I don't know how to insert a custom unique id of subscription...
I just use this function to show it's unique subscription's id when showing his/her full informations from the database:
$year = date('Y');
$ID = substr($student->dateNaissance,8,10).$student->id_etudiant."/".$year;
The function is combined of 3 things:
The 2 last digits of the year of birth (example: 01/01/1981.. i take only this -->81 using the substr function)
The row id from the table on the database (ex: 50).
And the year of subcription(example: 2013)
all that gives me , for example, as result 8150/2013
what i want here is when inserting the student data into the database , i want this unique ID to be inserted as well..
The problem here is i don't know how to get the last id of a row !
Yeah, I tried to insert the student data and then update the id_subscription using this:
if(isset(....){
......
$mysqli->query("INSERT INTO table (a,b,c, ...etc) VALUES('','',''..etc)");
$year = date('Y');
$mysqli_query("SELECT * FROM table_name");
$studentID = $mysqli_insert_id();
$ID = substr($student->dateNaissance,8,10).$ID."/".$year;
$mysqli->query("UPDATE table_name SET id_subscription = $ID");
}
But its not working :\
By the way: in my table Im using an auto_increment id + the subscription_id in which i want to insert the customized id I showed above.
Assuming that row id is an auto_increment field, then you'd have to do it in two stages:
start transaction
insert everything into the DB EXCEPT your id field
use last_insert_id() to get the mysql-generated ID field
build your own id field
update the record with this new id
commit the transaction.
On Database Structure:
1. you can use auto-incremented primary key in your table and store the data(student_id) as a seperate column(recommended).
On getting 'the last id of a row':
1. Use mysql_insert_id() .. check this out

MySQL update from select and further select and updates

Currently trying to find a way to do the following inside some form of loop (preferably without a performance hit on database).
I have 3 tables user_hours, user_calendar and hours_statistics. I need to first do:
SELECT user_calendar.date_start,
user_calendar.opportunity_id,
user_hours.user_id,
user_hours.agreed_hours,
user_hours.completed_hours,
user_hours.hours_committed
FROM user_calendar
JOIN user_hours
ON user_calendar.user_calendar_id = user_hours.user_calendar_id
WHERE user_calendar.date_start = CURRENT_DATE()
AND user_hours.completed_hours IS NULL
AND user_hours.hours_committed = 'accepted'
This query could return like the following:
http://i.imgur.com/5cJ5v.png
So for each opportunity_id and user_id returned i'd like to then do:
UPDATE user_hours
SET completed_hours = agreed_hours,
hours_committed = 'completed'
WHERE opportunity_id = {opportunity_id}
AND user_id = {user_id}
AND hours_committed = 'accepted'
AND completed_hours IS NULL
Note that {opportunity_id} and {user_id} would need to be looped at this point (see screenshot) because we need to go through each user on each opportunity.
Then for each updated record i'd need to then get the total hours like:
// Get hours they have done to send to statistics data table
SELECT sum(completed_hours) FROM user_hours WHERE user_id = {user_id} AND opportunity_id = {opportunity_id} 
// Get the completed hours total somehow as a variable
$completed_hours = (from result above)
// Commit stats
UPDATE hours_statistics SET completed_hours = (completed_hours+$completed_hours)
WHERE user_id = {user_id} AND opportunity_id =  {opportunity_id} 
Could anyone help write this as a procedure or a trigger of some kind or help me in the right direction to get a starting point for looping over this stuff? Manually the querying works, just need to be looped / automatic for a stats update to run.
You can create a trigger to update hours_statistics whenever user_hours is updated (you may also want to add similar triggers for INSERT and DELETE operations, depending on your application logic).
Assuming that a UNIQUE key has been defined on hours_statistics.(user_id, opportunity_id) one can use INSERT ... ON DUPLICATE KEY UPDATE within the trigger:
CREATE TRIGGER foo AFTER UPDATE ON user_hours FOR EACH ROW
INSERT INTO hours_statistics (user_id, opportunity_id, completed_hours) VALUES
(OLD.user_id, OLD.opportunity_id, -OLD.completed_hours),
(NEW.user_id, NEW.opportunity_id, +NEW.completed_hours)
ON DUPLICATE KEY UPDATE
completed_hours = completed_hours + VALUES(completed_hours);
Then you can use a single UPDATE statement (using the multiple-table syntax to join user_hours with user_calendar) to perform all of the updates on user_hours in one go, which will cause the above trigger to update hours_statistics as desired:
UPDATE user_hours JOIN user_calendar USING (user_calendar_id, opportunity_id)
SET user_hours.completed_hours = agreed_hours,
user_hours.hours_committed = 'completed'
WHERE user_hours.hours_committed = 'accepted'
AND user_hours.completed_hours IS NULL
AND user_calendar.date_start = CURRENT_DATE();

Categories