How to maintain duplicate record in database? - mysql

My table contains two columns Title and Description.
I want to provide a functionality to user to create duplicate page for existing page.
Like for existing page database store value like.
Title1 , Description1
When user clicks on duplicate page button I want to create a duplicate entry for the existing page like this.
1) Click First Time
Copy_1_Title1,
Description1
2) Click Second Time
Copy_2_Title1,
Description1
How can I create this type of functionality ? How should be my database for this ? Is this a proper way ?

I think you should create third column and name it for example copy_number, and then before creating record you can find it by title and if title exist you can get value of copy_number and increment it. Then you can use this number to display titles as you wish:
"copy_#{record.copy_number}_#{record.title}" or something like this.

#bor1s has suggested very right solution.
But for the interest you can use this mthod for duplication :)
class Page < AR::Base
def duplicate
# new_page = self.clone
new_page = Page.new self.attributes.except(:id, :created_at, :updated_at)
copy = (self.title.match(/Copy_(\d)+.*/).try([1]) || 0) + 1
new_page.title = "Copy_#{copy}_#{self.title}"
new_page.save
end
end

Related

Contao CMS Query a 'checkboxWizard' BLOB field

I have a question about how to query a 'checkboxWizard' BLOB field. In have added a such field to tl_member. This is working very fine. I can add “0 to N” selection to each members. Let’s call this field “myBlob”.
Now the questions is how to query “myBlob” with the Contao way? Let’s say I want all member that are in the postal code “12120” and that have the id “2” of “myBlob” selected. Not only “2” but at least this one.
$arrColumn[] = "tl_member.postal=?";
$arrValues[] = 12120;
$arrColumn[] = "tl_member.myBlob=?"; <- how to say “contains in the blob” here?
$arrValues[] = 2;
self::findBy($arrColumn, $arrValues)
The only way to do this (when using the default Contao method for such relationships) is to create a query like:
… WHERE myBlob LIKE '%"2"%'
So in your case it might be:
$arrColumn[] = "tl_member.myBlob LIKE ?";
$arrValues[] = '%"2"%';
However, this is of course cumbersome and might not work in all cases.
May be a better way would be to use codefog/contao-haste with its 'many to many' helper: https://github.com/codefog/contao-haste/blob/master/docs/Model/index.md
This way you will have a separate table containing the references.

Create new column in mySQL using values from other columns

I have two columns in my database I'd like to combine to make a new third column. The first column is a company name and the second is the URL to the company website.
I'd like to make a new column that is the company name hyperlinked to the website:
<a href="http://companywebsite.com>Company Name</a>
Is there a simple way to go about doing this? I'm VERY new to mySQL and can't figure out how I'd even go about doing this.
Bonus points for coming up with a way where when I add a new entry with company name and URL it automatically generates a value for this new hyperlink column.
Thanks.
As Polvonjon write, use CONCAT:
SELECT brief_description, CONCAT('', innovation_name, '') FROM inno_db
By the way - inno_db is a very odd name for a table in the database; it's a particular type of storage engine for MySQL. Do you not think "companies" is a better name?
Creating a new column is a bad idea - you have to keep it updated, and you're duplicating data, which leads to bugs in the long term. Ideally, you use the query to populate your WP screen.
If you can't do that, as the comments recommend, you could create a view, from which you can just do a straight select:
create view WPPlugin
as
select brief_description,
CONCAT('', innovation_name, '')
FROM inno_db
in your plug in code, you then do select * from WPPlugin.
Try use CONCAT function:
SELECT company, url, CONCAT('', company, '') FROM companies
But I will not advice to using this sample of getting anchor tag.
Try to use VIEW element in your MVC app.
Assuming you have a table with three columns
CREATE TABLE mytable (
company_name text
, url text
, hyperlink text
)
Then you would need to UPDATE the value of the third column (hyperlink) based on what you need, something like:
UPDATE mytable
SET hyperlink = '<a href="http://' || url || '>' || company_name || '</a>';

how to set a multi-column unique in web2py

In order to make many to many relation ship I make a middle table to combine two tables ,the tables like this:
db.define_table('problem',
Field('task_id','reference task'),
Field('title','string',unique=True,length=255))
db.define_table('task',
Field('title','string',unique=True,length=255),
Field('course_id','reference courses'))
db.define_table('belong',
Field('task_id','reference task'),
Field('problem_id','reference problem')
)
db.belong.task_id.requires=IS_IN_DB(db,'task.id','%(title)s')
db.belong.problem_id.requires=IS_IN_DB(db,'problem.id','%(title)s')
I use SQLFORM to insert into belong table.I want there are no duplicate task and problem. suppose there is a record like (1,task1,problem1)already exist in belong table,then if I choose task1 in SQLFORM,how to make the problem_id dropdown list not to show problem1. I have found similar question here
and do some test like the following in db.py:
test1:
db.belong.problem_id.requires=IS_NOT_IN_DB(db(db.belong.task_id==request.vars.task_id),'belong.problem_id').
test2:
db.belong.problem_id.requires=IS_NOT_IN_DB(db(db.belong.task_id==request.vars.task_id),'problem.id','%(title)s').
test3:
def my_form_processing(form):
a = form.vars.task_id
b=form.vars.problem_id
query=(db.belong.task_id==a)&(db.belong.problem_id==b)
if query :
form.errors.a= 'the record has existed'
def assignproblem():
form=SQLFORM(db.belong)
if form.process(onvalidation=my_form_processing).accepted:
response.flash='form accepted'
elif form.errors:
response.flash='form has errors'
else:
response.flash='please fill out the form'
return dict(form=form)
but it still not been solved.
If you want the choices in the problem_id dropdown to change dynamically based on the task_id selection, then you will need to use JavaScript (and likely make an Ajax request to populate the dropdown). For possible solutions, see this answer.
As for your tests above, test1 should do the proper validation, but only after the form has been submitted (i.e., the form will allow any combination of task_id and problem_id to be selected but will then report an error if a duplicate combination has been submitted).
test3 does not work as is because the query object just specifies the database query without actually doing a select from the database. Instead, you must call the .select() method, or more simply, the .count() method:
if db((db.belong.task_id == a) & (db.belong.problem_id == b)).count():
form.errors.a= 'the record has existed'

Dynamically selecting MySQL updates

This is more of a theory question. I have a page with a bunch of various textfields, dropdown boxes, etc. Each user has his/her "own page" that can be updated via this update page that I am referring to. He updates the fields at his choosing. It passes about 30 variables (if every field is inputted) to a "preview page". If the person likes the preview page, then they click an "update" button at the bottom of the preview page and all the various variables are updated into the appropriate MySQL table and their "own page" that others see is updated dynamically. (let me know if this explanation isn't clear).
Inserting this information for the first time is easy. However, when a user wants to update only a few of the fields for his page later, this is where I am confused. How do I make the MySQL update query dynamic to recognize an update to ONLY the fields on the page that the user wants to update (while he leaves the other fields blank, thus leaving the old information intact for those columns, and they are disregarded in the update query).
Let me know if what I'm asking doesn't make sense and I'll try again.
Thanks for your help.
The easiest way to do this would be
UPDATE MyTable m SET m.f1 = COALESCE(input1,m.f1), m.f2 = COALESCE(input2,m.f2), ....
WHERE m.id = key;
The COALESCE will return the first non-null value (or null if all values are null).
Note that you can insert a default value after the existing field value if you want to force a default.
Like so:
UPDATE MyTable m SET m.f1 = COALESCE(input1,m.f1,default1), m.f2 = COALESCE(input2,m.f2,default2), ....
WHERE m.id = key;
See: MySQL: how to use COALESCE
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_coalesce

MS Access: Auto update fields in same table

Sorry but I'm not very experienced when it comes to things like this.
I have a table called "Measure Table" with the fields "ID", "Proxy" and "ProxyID".
I created a form based on this table. ID is a label pre-populated from the table. Proxy is a drop down menu with the options "For" or "From". ProxyID contains a drop down with the same numbers as ID.
I would like a user to go to a specific record in the form (say for ID:I800), select "For" from the Proxy drop down and then select ProxyID (lets say L800). For the record for L800, I want it to automatically change the proxy to "From" and the ProxyID to I800.
Is this possible in Access?
Thanks so much for any help provided
Here is a visual of what i wnat to happen:
I want the table to look like this before the update(when the user selects "For" and "L800"):
Record# ID Proxy ProxyID
1 I800 For L800
2 L800
Then the table is automaticaly updated to:
Record# ID Proxy ProxyID
1 I800 For L800
2 L800 From I800
Okay, here is the gist of what you need to do to solve your immediate problem (updating the corresponding row in the other table.
Simply add an event handler to the AfterUpdate event of the form to perform the update to the other row. The code should look very similar to this...
Private Sub Form_AfterUpdate()
Dim RelatedID As String
Dim Proxy As String
If (UCase(Me.Form!Proxy) = "FOR") Then
RelatedID = Me.Form!ProxyID
CurrentID = Me.Form!ID
DoCmd.RunSQL ("UPDATE [Measure Table] SET ProxyID='" & CurrentID & "', Proxy='From' WHERE ID='" & RelatedID & "'")
End If
End Sub
Caveats:
As I mentioned in the comments, this data structure is a very bad idea and will create a lot of extra work for you to maintain the data integrity according to the implicit rules you are specifying as a matter of course with this design. I realize you have an existing DB to deal with, but frankly it would probably be less work to fix the DB design than maintain this one in the long run.
Some additional considerations you didn't ask about, but are going to need to deal with:
What happens if someone updates
either of the entries in a pair
directly in the table instead of
using your form? There really isn't a
good way to apply the above logic to run when
except in the context of using the form.
What happens in this code if the related row doesn't exist for some reason?
What happens if the related row "The FROM" row is updated in the form?
What happens if either row is deleted from the table?