How bad it is to copy paste my own code blocks? - php

! Actually, I am learning PHP from last couple of months and now I am in a stage where I can program small things like a simple Login Page in PHP and mySQL or a Contact Form. I have wrote a lot of codeblocks like inserting something into a database or selecting something from a database etc. etc. But, I always copy paste my own code-blocks from previous projects while working on a new one. So, I want to know whether this tendency is unique to me only or each of the beginner passes through the same phase once during their journey of being a developer?
Please bear with me because I know this isn't really a programming question and doesn't worth your time as well. I tried finding out in Google as well but this is a snap of what I found:
I mean to say that most of the search results dealt with copy pasting other's code which is not the case of what I am talking about. In order to save time I do copy paste my own code blocks almost everytime. So, how bad is this behaviour of mine?
I again apologize for not posting a question that is worth your time but I am finding it hard to learn to code by myself without having any mentor nearby ( Actually, I searched for a mentor who could teach PHP before giving it a start all by myself, but I found none in my area ) for clearing my doubts and as such Internet is the thing which I mostly depend upon for learning about anything.

This question probably belongs on https://softwareengineering.stackexchange.com but I'll try to give you a decent answer and some guidance.
People re-use their own code all the time. You do not however want to copy/paste if possible. The issue with copy/paste is when you have something used more than a few times - like a MySQL database connection - and it needs updating. I'd rather modify one file (or one small group of files) and have all of my webapps fixed/updated than having to modify 2 or 3 database calls in 9 different web apps...
For things that I use everywhere/all the time - talking with our course management systems API, authenticating a user against our LDAP server, connecting to a MySQL database and running queries, processing forms that are emailed, etc - I've built up my own (or coworkers have) sets of functions, classes, etc. Which I then keep in a single directory, and can include as needed.
If you do this, you want your functions/object methods to be as generic as possible - for example, my MySQL query function takes several arguments - an associative array with connection info (since we have several DB servers based on purpose), a query, and an array of parameters. It returns an array with a status code, and then appropriate data - the record set result for inserts, the ID of the last insert, the count of rows affected (for delete/update). This one function handles 50+ queries and connects to 4 different MySQL servers.

Related

Will there be issue if there is multiple database access by different users?

I am currently developing a PHP website and since the website will be used by many people, I just want to know if there will be a problem if there is multiple database access at the same time from those different users, and if so how to go about it. Thanks in advance.
SIMPLE ANSWER: As long as your code is well designed, No.
Elaborating: In a MySQL server, databases are made to work very efficiently and to handle a large set of tasks. Among these tasks include the constant querying of tables inside separate databases, among which include statements that SELECT data, UPDATE data, INSERT rows, DELETE rows, etc.
There are some corner cases that can happen however. Imagine if two people are registering on your website for the first time, and both of them want to register the username Awesomesauce. Programmers often code algorithms that first check if the current username exists, and if it doesn't, INSERT a new row in the users table with the new username and all the other relevant info (password, address, etc). If both users were to click the Register button at the same time, and if your code was badly designed, what could happen is two rows could be created with the same username, in which case you would have a problem.
Luckily, MySQL as features to prevent such corner cases. A UNIQUE INDEX could be implemented on the username column, hence forcing the database not to accept one of the two users who tried to register the name at the exact time.
All in all, if your code is well designed, you shouldn't have a problem.
It all depends on how much traffic, how large your site's database is and a host of other factors.
But for starters, i'ld say there's really nothing to worry about.
I think you should go with MySQL since you are just starting out with php, but you can pretty much use whatever you want with PHP's PDO http://php.net/manual/en/book.pdo.php. There is a lot of online support for mysql with php, so I would start there.
I would suggest make multiple tables in same db rather than multiple db. Though there won't be any problem even if there are multiple db access at same time.
Refer following link to know how its done:-
How do you connect to multiple MySQL databases on a single webpage?
While your question is way too broad, if you want horizontal scaling (adding more servers) look at a PHP/NoSQL solution. Otherwise, something like PHP/MySQL will be fine.
A bit of reading for you here: Difference between scaling horizontally and vertically for databases

Recreate a database using existing php code

So I have an old website which was coded over an extended period of time but has been inactive for 3 or so years. I have the full PHP source to the site, but the problem is I do not have a backup of the database any longer. I'm wondering what the best solution to recreating the database would be? It is a large site so manually going through each PHP file and trying to keep track of which tables are referenced is no small task. I've tried googling for the answer but have had no luck. Does anyone know of any tools that are available to help extract this information from the PHP and at least give me the basis of a database skeleton? Otherwise, has anyone ever had to do this? Any tips to help me along and possibly speed up the process? It is a mySQL database I'm trying to use.
The way I would do it:
Write a subset of SQLi or whatever interface was used to access the DB to intercept all DB accesses.
Replace all DB accesses with the dummy version of yours.
The basic idea is to emulate the DB so that the PHP code runs long enough to activate the various DB accesses, which in turn will allow you to analyze the way the DB is built and used.
From within these dummy functions:
print the SQL code used
regenerate just enough dummy results to let the rest of the code run, based on the tables and fields mentioned in the query parameters and the PHP code that retrieves them (you won't learn much from a SELECT *, but you can see what fields the PHP code expects to get from it)
once you have understood enough of the DB structure, recreate the tables and let the original code work on them little by little
have the previous designer flogged to death for not having provided a way to recreate the DB programatically
There are currently two answers based on the information you provided.
1) you can't do this
PHP is a typeless language. you could check you sql statements for finding field and table names. but it will not complete. if there is a select * from table, you can't see the fields. so you need to check there php accesses the fields. maybe by name or by index. you could be happy if this is done by name, because you can extract the name of the fields. finally the data types will missing. also missing: where are is an index on, what are primary keys, constrains etc.
2) easy, yes you can!
because your php is using a modern framework with contains a orm. this created the database for you. a meta information are included in the php classes/design.
just check the manual how to recreate the database.

When to use stored procedures and triggers vs the applicative layer

I have a dilemma, which I hope you will have some expert opinions on.
I have a table called CARDS with a column STATUS. If a record's status changes from 'download' to 'publish', I have to insert the record reference into another table called CARD_ASSIGNMENTS. Additionally, the record needs to be added into CARD_ASSIGNMENTS as many times as there are active records in SCANNERS.
In other words, if there are two active scanners, I will end up with two records in CARD_ASSIGNMENTS as below:
ID CARD_ID SCANNER_ID STATUS_ID
1 1 1 4
2 1 2 4
My dilemma is that I'm not quite sure what would be the most efficient way to execute the above. I've considered the following options:
From PHP - Do one UPDATE query and then the INSERT queries.
Create a stored procedure, which will take care of updating the CARDS record and adding records into the CARD_ASSIGNMENTS. Then, just call that stored procedure from PHP.
Create an ON UPDATE trigger for the CARDS table which will take care of processing INSERTS into the CARD_ASSIGNMENTS table.
PS. A simplified version of my database is available on MySQL Fiddle
Thanks,
Kate
Interesting question.
I'm going to give you clues about how to approach the problem.
So, you have to start by defining precisely three things:
the expected functionality
the access policy to the functionality
the technical upgrade policy
Here I'll detail these points.
So, the first point is that you have to define your functionality. By doing so, you will be able to tell whether adding a card implies always, in all the possible paradigms (sorry for the pedantic word I can't find a more proper one) of your information system, that this card MUST exist in the other table according to the specifications you provided. This 1-1 functional link must be said TRUE or FALSE. This is really important.
Said with other words, if there's at least one possibility that one day you don't want to copy that record to the other table, it means the trigger is a wrong solution, or at least it should be thought with an emergency mode (for example a variable inside that allows it to not get executed in some conditions) setup on.
Then comes the second point, about the access policy. You have to know whether the allowed accessing systems will do so by using your application layer or if they could develop their own (SAAS style). If so, your php layer will be useless and the stored procedure is an excellent option, since every single technical and business layer will go trough it yes or yes.
The last thing to know is whether you're possibly going to upgrade your php layer one day. In most of the cases the answer is yes. If so, you might have to modify the part containing this sql logic you're talking about. Then, having everything into a stored procedure vs storing it hardcoded into the php will definitely save you time, and improve stability.
Left brain right brain, I'm going to tell you my personal opinion afterall. I really love going with stored procedures but not using any triggers. If the environment allows it, I would go for an underlying batch, calling a set of defined stored procedures, concentrating the activity outside of the online scope.
The advantages are the following:
none or less risks of interruption of the online workflow since you reduce the number of operations
different schedule to alliviate the database load
more secure policy since executing the stored procedure requires only one grant, while using the same sql with php would require insert/update grants
better logging quality: you can have a log per job
better emergency response: when a job fails (if well thought) you can restart it, and that's it.
Long post, but that was interesting and I really wanted to share these ideas.
Cheers!
I would use triggers. Some developers say, that if you have too many triggers and stored procedures, the database lives its own life, that means you never know what is going to happen on insert, update etc. But in my opinion, triggers may help you a lot to keep database consistent, so even if someone inserts data directly from some administration tool, the integrity is still kept, because all necessary commands are executed. If you choose stored procedures, you would still have to know, that you need to call this procedure to insert any new data.

data system design

Need some ideas/help on best way to approach a new data system design. Basically, the way this will work is there will be a bunch of different database/tables that will need to be updated on a regular (daily/weekly/monthly) basis with new records.
The people that will be imputing the data will be proficient in excel. The input process will be done via a simple upload form. Then the system needs to add what was imported to the existing data in the databases. There needs to be a "rollback" process that'll reset the database to any day within the last week.
There will be approximatively 30 to 50 different data sources. the main primary interface will be an online search area area. so all of the records need to be indexed/searchable.
Ideas/thoughts on how to best approach this? It needs to be built mostly out of php/mysql.
imputing the data
Typo?
What you are asking takes people with several years formal training to do. Conventionally, the approach would be to draw up a set of requirements, then a set of formal specifications, then the architecture of the system would be designed, then the data design, then the code implementation. There are other approaches which tend to shortcut this. However even in the case of a single table (although it does not necessarily follow that one "simple upload form" corresponds to one table), with a single developer there's a couple of days work before any part of the design could be finalised, the majority of which is finding out what the system is supposed to do. But you've given no indication of the usage nor data complexity of the system.
Also what do you mean by upload? That implies they'll be manipulating the data elsewhere and uploading files rather than inputting values directly.
You can't adequately describe the functionality of a complete system in a 9 line SO post.
You're unlikely to find people here to do your work for free.
You're not going to get the information you're asking for in a S.O. answer.
You seem to be struggling to use the right language to describe the facts you know.
Your question is very vague.

Is PHP serialization a good choice for storing data of a small website modified by a single person

I'm planning a PHP website architecture. It will be a small website with few visitors and small set of data. The data is modified exclusively by a single user (administrator).
To make things easier, I don't want to bother with a real database or XML data. I think about storing all data through PHP serialization into several files. So for example if there are several categories, I will store an array containing Category class instances for each category.
Are there any pitfalls using PHP serialization in those circumstances?
Use databases -- it is not that difficult and any extra time spent will be well learnt with database use.
The pitfalls I see are as Yehonatan mentioned:
1. Maintenance and adding functionality.
2. No easy way to query or look at data.
3. Very insecure -- take a look at "hackthissite.org". A lot of the beginning examples have to do with hacking where someone put the data hard coded in files.
4. Serialization will work for one array, meaning one table. If you have to do anything like have parent categories that have to match up to other data, not going to work so well.
The pitfalls come when with maintenance and adding functionality.
it is a very good way to learn but you will appreciate databases more after the lessons.
I tried to implement PHP serialization to store website data. For those who want to do the same thing, here's a feedback from the project started a few months ago and heavily modified since:
Pros:
It was very easy to load and save data. I don't have to write SQL queries, optimize them, etc. The code is shorter (with parametrized SQL queries, it may grow a lot).
The deployment does not require additional effort. We don't care about what is supported on the web server: if there is just PHP with no additional extensions, database servers, etc., the website will still work. Sqlite is a good thing, but it is not possible to install it on some servers, and it also requires a PHP extension.
We don't have to care about updating a database server, nor about the database server to use (thus avoiding the scenario where the customer wants to migrate from Microsoft SQL Server to Oracle, etc.).
We can add more properties to the objects without having to break everything (just like we can add other columns to the database).
Cons:
Like Kerry said in his answer, there is "no easy way to query or look at data". It means that any business intelligence/statistics cases are impossible or require a huge amount of work. By the way, some basic scenarios become extremely complicated. Let's say we store products and we want to know how much products there are. Instead of just writing select count(1) from Products, in my case it requires to create a PHP file just for that, load all data then count the number of items, sometimes by adding stuff manually.
Some changes required to implement data migration, which was painful and required more work than just executing an SQL query.
To conclude, I would recommend using PHP serialization for storing data of a small website modified by a single person only if all the following conditions are true:
The deployment context is unknown and there are chances to have a server which supports only basic PHP with no extensions,
Nobody cares about business intelligence or similar usages of the information,
There will be no changes to the requirements with large impact on the data structure.
I would say use a small database like sqlite if you don't want to go through setting up a full db server. However I will also say that serializing an array and storing that in a text file is pretty dang fast. I've had to serialize an array with a few thousand records (a dump from a database) and used that as a temp database when our DB server was being rebuilt for a few days.

Categories