Recommendation / Marrying Up Algorithm in PHP? - php

Is there something that has been already developed and is Open Sourced?
I'd like to develop a site that is like:
http://www.swap.com/
What I envisage is that a USER A puts in what they have, dvd's, book's, cd's, etc.
USER A then puts in what they are looking for themselves.
The system then does a check against all the users. It finds that USER B is requesting items thats in USER A's inventory.
So USER A can swap item X for USER B item X.
I just don't want to try (operative word here being try) to reinvent the wheel if its kinda been done before.
Thanks

Hmm... not too hard to code, as dionyziz said it's a very simple SQL query. Since you don't want to recreate anything, I suggest looking into inventory scripts. These are scripts generally used to keep track of a store or business's inventory of items for sale, however if you find one that's designed to manage multiple "stores", then each "user" could be a store with their own "inventory".
A quick search for "open source php inventory script" turned up http://www.phpwares.com/
Not sure if it supports multiple "stores", though.

This can easily be done with an SQL query. SELECT from your whole userbase those items who match your currently logged in user's requests.

Related

What is the best way to wait that an administrator validate something before comitting it?

I'm building a web application where several groups have their own page but if they want to modify it, an administrator has to validate it before.
For example, can change to change its logo, post new photo, change their phone number, their name, their location etc... Basically they can edit a value in the database but only if the administrator accepts it. The administrator has to validate every modification because... our customer asked us to.
That's why we have to create a system that could be called "pending queries" management.
At the beginning I thought that keeping the query in the database and executing when an administrator validate it was a good idea, but if we choose this option we can't use PDO to build prepared statements since we have to concatenate string to build our own statement, wich obvious security issues.
Then we thought that we should keep PHP code that calls the right methods (that use PDO) in our database and that we will execute with eval() when the administrator validates it. But again, it seems that using eval() is a very bad idea. As says this Rasmus Lerford's quote : "If eval() is the answer, you're almost certainly asking the
wrong question".
I thought about using eval because I want to call methods that uses PDO to deal with the database.
So, what is the best way to solve this problem ? It seems that there is no safe way to implements it.
Both your ideas are, to be frank, simply weird.
Add a field in a table to tell an approved content from unapproved one.
Here's one possible approach, with an attempt to keep the things organised to an extent, as the system begins to scale:
Create a table called PendingRequests. This will have to have most of the following fields and maybe quite a few more:
(id, request_type, request_contents, reqeust_made_by, request_made_timestamp,
request_approved_by, request_approved_timestamp, ....)
Request_contents is a broad term and it may not just be confined to one column alone. How you gather the data for this column will depend on the front-end environment you provide to the users (WYSIWYG, etc).
Request_approved_by will be NULL when the data is first inserted in the table (i.e. user has made an initial request). This way, you'll know which requests to present in the administration panel. Once an admin approves it, this column will be updated to reflect the id of the admin that approved it and the approved changes could eventually go live.
So far, we've only talked about managing the requests. Once that process is established, then the next question would be to determine how to finally map the approved requests to users. As such, it'd actually require a bit of study of the currently proposed system and its workflow. Though, in short, there may be two school of thoughts:
Method 1:
Create a new table each for everything (logo, phone number, name, etc) that is customisable.
Or
Method 2:
Simply add them as columns in one of your tables (which would essentially be in a 1:1 relationship with the user table, as far as attributes such as logo, name, etc. are concerned).
This brings us to Request_type. This is the field that will hold values / flags for the system to determine which field or table (depending on Method 1 or Method 2) the changes will be incident upon - after an admin has approved the changes.
No matter what requirement or approach it is to go about database management, PHP and PDO are both flexible enough to help write customisable and secure queries.
As an aside, it might be a good idea to maintain a table for history of all the changes / updates made. By now, it should probably be apparent that the number of history tables will once again depend on Method 1 or Method 2.
Hope that helps.

mysql database and multiple users

I'm working on a web site that will have multiple users. Say 5 users total.What I need to make sure is, that each user will only be able to access the data they input.
Think of a CRM or Job Board. So john will only be able to access johns info, edit, add, etc. Same with jane and june.
Now if my reading is correct, all i need to do is make sure the queries pull only the data based off their unique id correct?
so the database table for the users looks like:
Database: xxxxx, Table: xh_user
user_id
user_username
user_fname
users_email
users_password
users_salt
so if johns user_id is 7, when he logs in, it queries his id and displays only his content from the database.
Am i correct on this?, or is there a different or better way to accomplish this?
As long as your foreign keys are setup correctly so that the data is linked to the user_id (PK) then it should be fine. Alternatively you can setup a user_roles table which contains access rights.
As far as I know and how I have been programming, yes. If you are looking for extra security, perhaps check the user's password/salt against what is in the database.
l i need to do is make sure the queries pull only the data based off their unique id
I'm not sure what you mean by this, but it is too a general/broad statement to be either bad or good. It really depends on the system you're building. This is by no means a generally applicable statement.
Now in your current set-up this looks somewhat correct, but in the long-ish term you might need some data be public, or at least accessible by several people. This is impossible in your current design.
I would split the access and content, as they are separate things. Save what users (or look up a role-based pattern) have access to what data in separate tables, so you can build on what you have later, and add multiple user functionality.
This could become a long discussion, so I'll end with this: The bottomline with all database design is that you should save your information in a way that represents logical units, as it is in the real world (Yes, I'm taking some shortcuts here). So coupling a username to an id seems normal. But making the connection between a job and a user isn't that logical per se. A job can be visible to multiple users, no sweat. Or more then one user could have added the information. You could say that only 1 user is the 'owner' of a job or any other piece of data, but it seems too restrictive to make your access control purely out of who "owns" the data.
But then again, it is only a warning for the future. If you never need this, you don't.
You could have multiple databases, one per user. You'll need to have a way to do schema changes & upgrades though, like phinx. I wouldn't recommend this unless you foresee users having multiple users on their own account.

MySQL - Organizing Database Content (Sports League)

I'm designing a PHP/MySQL solution for my youth athletic organization that will display schedules and standings for the teams participating in any given season. Unfortunately, I'm just learning the ropes when it comes to database design and having a bit of a challenge wrapping my brain around what should be a relatively simple concept. Perhaps someone can step in and clarify a few points?
What I'm unclear on is how exactly to structure the database(s) and tables to get started correctly. This is what I will ultimately need to set-up:
We have approximately 50 member schools. Each will need their own log-in ID and password. I was thinking about storing these in their own separate database because the accounts will be re-used again each season to represent teams and allow the coaches to log-in and update their game results.
Each season has two different sports. For example, the upcoming fall season has a girls volleyball league and a boys flag football league. Each league then has multiple divisions (divided by geographic region) in which the schools play their regular-season schedule. I'm not sure if each season needs its own separate database, each league, etc.
Each division's regular-season will be imported from a scheduling program (via an Excel spreadsheet) and displayed on its own webpage where schools can view their upcoming games and log-in to update results.
As game results are updated, I'm going to need to find a way to have those results reflected on a separate webpage where that division's league standings are displayed.
For a clearer demonstration of what I'm trying to do, have a look at these two mock pages I created for the schedules and standings data, respectively:
http://www.712jefferson.org/pal/schedules.html
http://www.712jefferson.org/pal/standings.html
This is where I'm looking for your guidance. How exactly should I structure the MySQL framework for all of this data?
I'm thinking a separate database for the school log-in ID's and then a separate database for each seasonal sport (e.g. Boys Volleyball 2013) with separate tables for each division and x-number of columns to represent the schedules and standings therein.
Does that sound about right? Am I thinking about it all wrong? Any assistance or guidance to help flesh out this thought process would be MUCH appreciated!
Thank you so much!
Ouch. You have taken on a big job. Are you absolutely sure that nothing you are going to do cannot be done by something that is already available? Well, if you are sure, read on.
Firstly, the hardest part of what you want to do is managing your user access. I'd advise that you start off by writing your user management module before you go any further.
For what you want, it seems likely that Drupal or one of the other senior CMS systems would be a great way to bootstrap the system. Drupal will handle your user management right out of the box (or with minimal problems) and you could write the rest of your code as static nodes. This also makes it easy to add blogs, forums, news and to manage mailing lists etc.
As stated in the comments above, you do need to keep your data together. it would be good to keep data for historical comparisons too.
If not extending a CMS, after you have got back from the psychiatrist, you will need something along the lines of:
header file to access the db and check for user authentication.
footer file to display your data
individual page files to present or obtain your data.
Database structure for handling the users (at minimum) should be IRO:
Person - details of individual users
username - link person to a username
email - email addresses
club - sports club details
password - passwords
logon - record of logon attempts
role - record of role of individuals in your site
permissions - list of required permissions to access areas of the site
role_permissions - default permissions for each role
person_role - link person to role
person_permissions - link person to permissions (only needed if some individuals need extra permissions not given routinely by their role)
club_person; person_email; - link people to clubs and to their email addresses.
To handle the matches you will need:
team - team name, group and club reference
grouping - list of groups eg by age.
divisions. - list of divisions
venue - list of venues. Include GPS!!!
match - division, grouping, team1, team2, venue, date, time
result - team1 reported result, team 2 reported result, approved result (you may need to intervene!) match.
As you can see you need a fair few tables but YOU MUST NOT try to do the fun stuff with the actual teams UNTIL you have your user access working properly.
What I have sketched out for you is a db in normal form. No textual data is duplicated and the data is easy to retrieve, index and display. I do feel this question is too broad for SO as designing a database for you is a bit out of scope but I do think the general format is useful.
Each table should only contain unique necessary data eg:
Person: personid int, surname, forename, style, whenadded, whoadded, inuse
email: emailid, email, whenadded, whoadded, inuse
email_person: emailpersonid,emailid,personid, whenadded,whoadded,inuse
This allows multiple people to share one email and multiple emails to be applied to one person with no text duplication. IDs should be type INT AUTO_INCREMENT PRIMARY KEY rather than SERIAL as this saves a whole lot of storage space and you'll never fill an INT in this application.
The other tables should be created in the same way. The whoadded and whenadded columns are optional and quite storage hungry but can be very useful. inuse is essential set this to a BOOL and you can remove teams without deleting them - the data is not lost. A whenremoved and whoremoved is useful too for audit.
A word on passwords - please ensure you store these as a SALTED HASH. If you do this, when your site is hacked, no-one will have the password that they also use for their internet banking exposed. People are often idiots. You have to look after them.
As I said, a bit out of scope so I'll end the answer there - it gives you as requested the basic outline of a 4th Normal Form Db that will be robust and extendable but leaves you to do the work. Why not ask more questions if the problem turns out to be too hard.
Good luck.
ADDED:
DIY Framework:
If you don't want to learn to use one of the existing frameworks or CMS, you will need to write your own. Oddly, this is actually very easy.
header.php:
<?PHP
$mysqli=new mysqli(credentials....)//connect to database and present a mysqli or pdo object.
session_start(); //open a session
//you will need to authenticate your session here - see below
?>
footer.php:
<HTML>
<HEAD>
<TITLE>
<?PHP echo $pagetitle;?>
</TITLE>
</HEAD>
<BODY>
<?PHP echo $content;?>
</BODY>
</HTML>
These are used by mypage.php:
<?PHP
require("header.php");
//do some stuff that generates $content
$pagetitle="mypage.php";
require("footer.php:);
?>
It should be stressed that this is the bare minimum you will need and is truly sucky - it is just presented to show how this should be begun, not an exemplar of ideal code. It will work though.
The key is creating a header that presents the variables you will need, such as a db connection, username, user logon status etc. and a footer you can enter details into to present the data. The footer is the only place where you combine HTML and PHP.
Use your $_SESSION to store information that needs to persist between pages.
These files can be as simple or complex as you like - I created my own ages ago that do several checks on the user and session and can display scripts, custom CSS files and such in the footer. It's not hard to do if you start simple and build on as you need. SO will be here to help you.
One word of caution: although you can start very simple, what you are trying to do has legs and will get out of hand. Please audit your code after you have it up and running to make sure that you have not inadvertently included security flaws. It is very easy to include these as you get into a project and need a quick fix and they can be devlishly hard to spot later on unless you are looking for them.
I am in your shoes, and the best solution I found was to use Backend as a Service (Baas) providers such as Parse.com or Stackmob.com or many others. They do complete database hosting for you plus your user management (login/register/forgot_password etc) so you don't have to worry about it. You access them via REST API and they also have PHP libraries on the Github.
Since you are new to database management, which is a non-trivial task, this solution may save you some headache.
Of course, you still have to decide how to organise your tables (or 'classes' in Parse, 'schema' in Stackmob etc) but they also provide help with their relation APIs. They have a pre-defined User table specifically designed for storing users.
Surely their API is not as flexible as SQL but it also safe from SQL injection, a downside of that flexibility. On the other hand, they also offer custom code to enhance that flexibility.
Edit.
Forgot to mention, those BaaS platforms also allow to store arrays as database fields, which can be really handy.
This can be a big build. You may want to try an existing service for league management. There's a few out there. I know a few friends who use Teamopolis and are very happy with the service, and I think it accomplishes everything you're looking for.

ebay style watch this item

Are there any tutorials out there for adding a "watch this" feature to an online store, so users can see when an item is put on sale for example.
My current setup is in php and mysql and I do not offer this feature but would like to give me customers more control over what they are watching and have the ability to be notified when items are put on sale.
All of the products in the shop are listed in a table with unique prod ids. I was then planning on adding a new table for 'sales' - upon a certain event I would like to automate emails to each user who has added the prod id to their watch-list.
Very similar functionality to ebay's watch item feature -but given the potential scale of the work I want to gauge how easy it will be to implement and maintain before committing to much time/effort to it!
Thanks
JD
No matter what you choose to "watch" the general concept is pretty simple. You have a relational table with the user id and the item id. This table is added to on event (click or form submit, however you choose to do so) Either way it is very easy to implement. If you know how to insert to the database then I need not explain the process.
Then you can either run a search and notify script when a table is modified, or run a cron that checks every minute.
This is so vague it hurts my soul to post it, but ultimately the general concept is simple. log a relation. check every minute to see if the user needs to be notified. end of story.
Now, for a more detailed description or actual code, you may want to narrow down your request. It would help to know if you're using a framework or running straight mysql queries. Can you setup a cron? etc.
I'll update if you provide info sufficient for a clear response.

How should I store user levels for a site wide point system? in the DB? or on the fly?

I am in the process of building a user experience/level system on my site. The effect I am trying to achieve is similar to that of the popular game site, Kongregate, whereby when a user completes particular actions on the site they are awarded points. Once the points reach a certain amount the user will level up. This has the effect of giving the site a game like feel, while also grabbing the user's attention.
The problem I'm having is figuring out if it's best to...
1. Store each level in a database table and then match the user up to that level via an ID?
2. OR store the user's experience for the actions completed and then summing that number up everytime I need to call on the level?
It should also be noted that the level will be used to figure out other aspects of this system. i.e. A user at level 10 will gain additional schwag for their profile, added functionality on the site, etc... A LA Stack O.
Any pointers on the proper direction to take?
Store the levels and their associated "swag"/"privileges" in the database.
Store the user's current level on their profile in the database.
Store the user's actions that result in points in the database
When they add points from your site (by commenting, or playing a game or whatever), calculate it on the fly, but once it's definitely done adding up, store it in the database (in the actions table) and update their total points (in the user table or whatever) so it's available to other parts of the site.
This makes everything easier:
when you want to see what privileges they have it's just a matter of comparing their total to the next lowest (or equal) "swag" level
when you want to get their total it's a single call instead of a bunch of queries and math
when you want to show a list of what they've done you have it right in the database
You won't duplicate code by adding up their total on every different type of page that needs to show the total.
...probably tons of other reasons. data is in the name of the tool for a reason.
I think it's best to determine the "level" everytime the user gets more points. So when he / she does something to get more points, do the calculation then and there. If the point warrants a level increase, then change the level_id within the user's profile. That way you minimize calculations on the server side.

Categories