Table Values to PHP (Ordering Important) [closed] - php

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am currently trying to get values from tables I have in a webpage into a database using PHP. However, the order of the values inside each box is important, so I want the first box to be ranked 1 and the second box to be ranked 2 and so on... There is no limit to the number of items in each box. There may be as many as 100 or 0. Each item in each box is dragged from a bank of items into the table, which represents a topic. The tables are the output of the interface.
So example table:
Rank1
Rank2
Rank3
I've currently tried dumping the entire page once the user fills it in into a text file and parsing it from there but i'm looking for a more functional and practical way of doing it.

If I understand your goal correctly, you have two sections on your webpage. A word bank and a <table>. A user can drag and drop items from the word bank to a cell in your <table>. Next you want the order of the contents of the cell to be preserved when the data is saved to a database-table.
Given the description you have provided, it seems you may be new to using databases. It is not a problem but you will need to do some study on how databases work and how to use them.
Again, if I understand correctly, your <table> looks like the following:
| topic-1 | topic-2 | topic-3 |
-------------------------------
| ---A--- | ---J--- | ---V--- |
| ---B--- | ---J--- | ---X--- |
| ---C--- | NULL | ---Y--- |
| NULL- | NULL | ---Z--- |
To move this into a database you need to create a database, and some table, for example MyDataTable. Next that table may have three columns: id, contents, category.
Here is some info on Mysql Insert.
INSERT INTO MyDataTable(`id`, `contents`, `category`)
VALUES (1, A, Topic-1)
You will need to format that call to work correctly via php, but that is the general idea. In your php code you will need to iterate over the elements in the order you want, and you can use the id to refer to your order... Alternatively you could add another column to your database-table and have that refer to your order, which would allow you to use some other value, perhaps auto-increment, as the primary key.
I would recommend becoming comfortable with MySQL if you aren't already, before tackling your project's specific needs. Namely, INSERT, DELETE, UPDATE, SELECT and WHERE will almost certainly be necessary MySQL functions.
One resource I found very helpful in grasping MySQL is this book, SQL Antipatterns: Avoiding the Pitfalls of Database Programming .
Using the phpMyAdmin page can be very helpful in debugging SQL queries, once the query syntax is correct, you can translate it to php and incorporate your dynamic variables. Also if you store your sql-syntax in php as $sql, using var_dump($sql) can also be a great help when debugging sql syntax.
In programming, iterate over, typically refers to creating a for-loop to iterate, or step through 1-by-1, each of the items of an array or similar container.
$MyArray = array();
$MyArray = GetTableContents(); //You have to write this function.
for ($idx = 0; $idx < count($MyArray); $idx++)
{
// do my stuff, like, Insert into my DB-table.
}
In order for the code above to work, you need to fill MyArray with the contents from your <table>. In the example code above, the $idx, could be used as your id.
In addition to MySQL, it seems it would also be worth your time to learn more about php programming. Read simple tutorials, how-to's, and books. There are numerous resources on the internet about php. One such example is here.
I hope this is helpful.

Related

PHP: Best Way To Determine Position In Array [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 5 years ago.
Improve this question
What I Wish To Implement
My site does a nightly API data fetch, inserting 100,000+ new entries each night. To save space, each field name is in a seperate table with an allocated ID saving around 1,027 bytes per data set, 2.5675MB approx per night and just under a gigabyte over the course of a year, however this is set to increase.
For each user, a JSON file is requested containing the 112 entries to be added. Instead of checking my table for each name ID, I feel to save time, it would be best to create an array whereas the position in the array will be the ID, so lets use some random vegetable names;
Random List Of Vegetables
"Broccoli", "Brussels sprouts", "Cabbage", "Calabrese", "Carrots", "Cauliflower", "Celery", "Chard", "Collard greens", "Corn salad", "Endive", "Fiddleheads (young coiled fern leaves)", "Frisee", "Fennel"
When I create the insert via my PHP classes, I use the following;
$database->bind(':veg_name', VALUE);
Question
What would be the best method to quickly check what position $x is within the array?
As an alternative solution to matching the entries in PHP (which might at some point run into time and/or memory problems):
The general idea is to let the database to the work. It is already optimized (index structures) to match entries to one another.
So following your example, the database probably has a dimensional table for the field names fields:
ID | Name
---------------------------------
0 | "Broccoli"
1 | "Brussels sprouts"
2 | "Cabbage"
Then there is the "final" table facts, which has a structure like this:
User_ID | Field_ID | Timestamp
Now a new batch of entries should be inserted. For this, we first create a temporary table temp with the following format and insert all raw entries. The last column Field_ID will stay empty for now.
User_ID | Field_Name | Timestamp | Field_ID
In a next step we match each field name with its ID using a simple SQL query:
UPDATE `temp` t
SET Field_ID=(SELECT Field_ID FROM fields f WHERE f.Name=t.Field_Name)
So now the database has done our required mapping and we can issue another query to insert the rows into our fact table:
INSERT INTO facts
SELECT User_ID, Field_ID, Timestamp FROM temp WHERE Field_ID IS NOT NULL
A small side-effect here: All rows in our temp table, that could not be matched (we didn't have the field name in our fields table), are still available there. So we could write some logic to send an error report somewhere and have someone add the field names or otherwise fix the issue.
After we are done, we should remove or at least truncate the temp table to be ready for next nights iteration.
Small remark: The queries here are just examples. You could do the mapping and insertion into your facts table in one query, but then you'd lose the "unmatched" entries or have to redo the work.
Redoing the work might not be an issue now, but you said the number of entries will increase in the future, so this might become an issue.
If you're only doing 2.5 megs/night, that's almost nothing. If you gzipped that before dragging it across, it would reduce it a lot more.
Using array positions could get tricky if you're trying to use that to match something in some other table.
That being said, every array has a numeric index as well, so you can find out what that is at any point.
Try this and you'll see:
$array = array("Broccoli", "Brussels sprouts", "Cabbage", "Calabrese", "Carrots", "Cauliflower", "Celery", "Chard", "Collard greens", "Corn salad", "Endive", "Fiddleheads (young coiled fern leaves)", "Frisee", "Fennel");
var_dump(array_keys($array));
On the array, you can also do this:
$currentKey = array_search("carrot",$array);
That will return the key for a given variable. So if you're looping through an array, you can output the key(index) and go do something else with it.
Also, gzip is a form of compression that makes your data much smaller.
If you have a list of item, e.g. an array containing only strings that represent your values, you can use foreach with a key-value ($users as $index => $user) method instead of just a $users as $user like following :
$users = ["Broccoli", "Brussels sprouts", "Cabbage", "Calabrese", "Carrots", "Cauliflower", "Celery", "Chard", "Collard greens", "Corn salad", "Endive", "Fiddleheads (young coiled fern leaves)", "Frisee", "Fennel"];
foreach( $users as $index => $name ) {
echo "about to insert $name which is the #$index..." . PHP_EOL;
}
Which will echo :
about to insert Broccoli which is the #0...
about to insert Brussels sprouts which is the #1...
about to insert Cabbage which is the #2...
about to insert Calabrese which is the #3...
about to insert Carrots which is the #4...
about to insert Cauliflower which is the #5...
about to insert Celery which is the #6...
about to insert Chard which is the #7...
about to insert Collard greens which is the #8...
about to insert Corn salad which is the #9...
about to insert Endive which is the #10...
about to insert Fiddleheads (young coiled fern leaves) which is the #11...
about to insert Frisee which is the #12...
about to insert Fennel which is the #13...
Live-example available here : https://repl.it/Jpwk
Like #m13r asked, how would an index be useful in your case ?

Search my database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
Hi I am new to web technology (Well not advanced). I am trying to build an online store (computer hardware) with mysql and PHP, I am wondering how to add a search functionality (not google's).
I am planning to make a search bar where visitors can enter key word or key words for search.
The search for these key words should span many tables with totally different content.
I know about SQL syntax, I have a good understanding of REGEXPs, I am good with indexes and views...
The only thing I want is guidance, a general idea.
you should first design your database. then make website design and program it in PHP.
as far as search functionality concerns you should make something like that,
eg.
database and tables and their columns etc..
for example, if you have one table named hardwares
+--id---+---Name----+---Cost----+-Warrenty--+
+-------+-----------+-----------+-----------+
| 1 |hardware1 | 2000 | 2 |
| 2 |hardware2 | 5000 | 1 |
| 3 |hardware3 | 5000 | 3 |
+-------+-----------+-----------+-----------+
then in coding part of the website there will be query fired something like that,
select * from hardwares where Name LIKE '%$search_input%`
here, the search input is taken from the user and this query will result the particular hardwares' information and then from the results you can get ID of that hardware which is already stored in that table.
from that ID, you can make a page that will accessed by a particular query for example,
http://www.yourwebsite.com/hardwares.php?id=2
this page will load that particular hardwares' page and it will have all the information regarding to that hardware.
Search from catalog items - this is search for database.
MySQL code
SELECT nameItem FROM catalogItem WHERE `nameItem` LIKE '%search phrase%' OR `descriptionItem` LIKE '%search phrase%'
This is the simplest example.
A architecture of search I would do with caching results in a separate table.
PS See how to implement search in popular CMS

Storing in array or in fields? Which is better? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Today I was working on my website and I asked myself a simple question.
Does storing an array with all informations is better than saving those one in different fields?
For example if I store a word, a password and a number in one field on the database in this way
+-------------+----------------------------------------------------------------+
| Field | Value |
+-------------+----------------------------------------------------------------+
| all | ["test","fa26be19de6bff93f70bc2308434e4a440bbad02","25468684888"] |
+-------------+----------------------------------------------------------------+
Is it better than saving it in this way?
+-------------+------------------------------------------+
| Field | Value |
+-------------+------------------------------------------+
| word | test |
| password | fa26be19de6bff93f70bc2308434e4a440bbad02 |
| number | 25468684888 |
+-------------+------------------------------------------+
I think that the first method is faster than the last one because you need only to SELECT one field and not three or more. What do you think about it?
The second method. By far.
You should never put more than one piece of data into a single column.
A single row of data shuld contain all the information you need:
id name password
1 Fluff itsASecret
2 Flupp Ohnoes
Basically, it has to do with updates, selects, searches and pretty much everything that databases do. They are made to do it on single columns, not little bits of data inside a string.
Taking your example, how do you update the password? How do you put an index on the user ID?
What if you also had a bit of data called "NumberOfVotes" If you had it all in one column in a pseudo-array, how do you get a tally of all the votes cast by all users? Would you REALLY want to pull each entry out into PHP, explode it out, add it to the running total and THEN display how many votes have been cast? What if you had a million users?
If you store everything in a ingle column, you could do a tally really easily like this:
select
sum(NumberOfVotes)
from
yourTableName
Edit (Reply to faster query):
Absolutely not, the time it takes to compelte a query will come down to two things:
1) Time it takes to execute the query
2) Time it takes to return all the data.
In this case, the time it takes to return the data will be the same, after all, the database is returning the same amount of bytes. However, with tables that are properly set up, just FINDING the right data will be faster by orders of magnitue.
As an example of how difficult it would be to simply USE a table that has the various bits of information all mumbled together, try to write a query to update the "number" value in the row that starts with the word "test".
Having said that, there are possibly some potential cases where it can in fact be okay to store multiple "fields" of data in one column. I once saw (and copied) an exceptionally interesting permissions system for users that stored the various permissions in binary and each digit in the number equated to being allowed/not being allowed to perform a certain type of action. That was however one interesting example - and is pretty much what I would call an exception that proves the rule :)
I think that the first method is faster
is your main problem actually. You are comparing solutions from only "is it faster" point of view. While you have no measure to tell if there is any difference at all. Or, if even there is, if such a difference does matter at all. So, the only your reason is a false one. While you completely overlook indeed important, essential reasons like proper database design.
Saving in separate fields is a lot more flexible as you are then able to easily search/manipulate data using SQL queries, whereas if they were in an array you would frequently find yourself needing to parse data outside SQL. Consider the following example:
+-------------+----------------------------------------------------------------+
| Field | Value |
+-------------+----------------------------------------------------------------+
| all | ["1","fa26be19de6bff93f70bc2308434e4a440bbad02","25468684888"] |
+-------------+----------------------------------------------------------------+
Using the above table, you need to find the number field for the user with id 1, however there is nothing to search for, you can't simply to a query for the value 1 somewhere in the all field, as that would find every instance of the number 1!
You'll also encounter this problem when changing data in your DB, as you'll have to get the current array, parse it, change the value, then reinsert it.
Also you'll need to put some form of ID as a field to act as a primary key.
However with separate fields for each value, it's fairly simple:
+-------------+------------------------------------------+
| Field | Value |
+-------------+------------------------------------------+
| id | 1 |
| password | fa26be19de6bff93f70bc2308434e4a440bbad02 |
| number | 25468684888 |
+-------------+------------------------------------------+
SELECT `number` FROM mytable WHERE id = 1
The second option is better because its more readable and maintainable.
If someone who didnt write the code has to maintain it, the first option is terrible.
If you ever need to change a field, or add a field, likewise, the first option is a nightmare.
The second option requires much less work.
Keep it simple!
I think given example is trivial and that's why answer for specific example is 2nd method. But there are time's when first method is far more easy to implement. For example you create pages for website dynamically from admin panel, and in start you don't know all the values that will be used in every page. So you put general options like in 2nd method, and put something like page_data and use it to store serialized object. Now you should use serialized object for data that are not likely to change individually, as they are treated as single piece of data.
In your code you fetch serialized object, do unserialize and use them as normal. This way you can add page specific data that are not generalized for every page, but still the page's are the same.

Database structure and querying hierarchal data and trees of data [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the most efficient/elegant way to parse a flat table into a tree?
This I am finding rather tricky and would like some opinions on the matter.
I am trying to store hierarchal data (tree like) with an unknown number of levels and branches. I am wanting to be able to add new ones and delete any at any time.
I need to be able to query from any node in the hierarchy for all of the children id's in one go and efficiently due to large user base.
Lets take a hypothetical example of a website where families socialise and update their status like in facebook and at any time you can be viewing a family members "Wall" which will also include all of the recent status updates form the people below them in the hierarchy in chronological order.
Obviously the fetching posts once you have the array of family members id's who are children of this family members node is easy enough in a loop.
Lets take an example simple table structure of:
id | parentId | name
________________________
1 | NULL | John
2 | 1 | Peter
3 | 1 | Bob
4 | 3 | Emma
5 | 2 | Sam
6 | 4 | Gill
etc.... You get the idea.
I need to be able to do the above with something like this unless you think the structure needs to be adapted.
I have read up on mySql nested set model.
This seems very fiddly and could be unreliable if something was not to update correctly and would mess everything up.
I am used to using php and mysql but have been reading a bit on cassandra and thrift. Not sure if this would be easier?
There are already good approaches out there which are more simple than the solution you propose.
Here are a couple of links which explain how to do it (we use this ourselves for much the same problem you describe and it works well).
Managing Hierarchical Data in MySQL (from MySQL)
Storing Hierarchical Data in a Database (from Sitepoint, but a clearer explanation, I think)
This makes inserting/updating more complex, but selecting portions of the tree structure far faster (with only one query). It allows finding all children of any given node in one query, and finding all the ancestors of a given node with one query.
So I think I have come up with an idea.
The reason I am against the nested set model is because it seems like it is still not the best way and is not going to be the ideal performance solution.
I am going to cover a proposed solution I have been thinking about.
The concept means creating an hierarchal map table to keep track of all the relationships between each family member/node.
The way it would work is:
Using map table structure of this:
id | fMemberId | parentid
=====================================
1 | 3 | 2
2 | 4 | 3
3 | 4 | 2
1) As a new family member is created as a child of a parent we would take the parents id and create a new row in our family members table with the parent id set for future additional uses and functionality.
2) As this row is created we will create new rows with all of the parent id's for the new family member.
A quick way to do this would be to take the parent id from the new family member and do a query to the map table to find all the rows with the family member id the same as the new family members parent id and then store an array in php of the subsequent parent ids required for storing alongside the new family members id in the map table. This would then only require one sql query for grabbing all the parent id's for adding them rather than a number of queries based on the number of nodes
This would mean when we are viewing a family members feed of posts we would be able to query the db for simply the rows in the map table to get all the children id's of the current family member and subsequently query other tables for the post data.
The main trade off being the amount of potential storage required for this kind of system.
However I believe reading speed would be quicker as there is no conditional SQL statements and also maybe just as quick to write to db in this way.
We could overcome this by using InnoDB's cluster id's assigning an initial family id index and creating a new table with the "next family members id" based on the family id.
Also reliability, if a row wasn't written it would be easy enough to add it in. It prevents having to continually edit rows just to create a member.
What are your thoughts on this?
So far this seems to be a good way in my opinion. Took a lot of thinking to get to here. I also believe it could maybe be improved with time and being able to store arrays of id's per member rather than all of them. Still trying to work that one out!
Yes, your solution is called a transitive closure. I have written about it before:
What is the most efficient/elegant way to parse a flat table into a tree?
Models for Hierarchical Data
You also need the zero-length paths, e.g. 2-2, 3-3, 4-4.

MySql database design for a quiz

I'm making an online quiz with php and mysql and need a bit of help deciding how to design the database for optimal insert of questions/answers and to select questions for the quiz. The table will hold 80 questions each with 4 possible options plus the correct answer.
When retrieving the questions and options from the database I will randomly select 25 questions and their options.
Is it better to make a single column for all questions, options, and correct answers? For example:
ID | Q | OPT1 | OPT2 | OPT3 | OPT4 | ANS
Or would it be better to make a column for each individual question, option, and correct answer? For example:
Q1 | Q1_OPT1 | Q1_OPT2 | Q1_OPT3 | Q1_OPT5 | Q1_ANS | Q2 | Q2_OPT1 | Q2_OPT2...
It'd be better to store the possible answers in a seperate table. This allows you to have any amount of answers per question instead of just 4. It also allows questions to have a different number of answers. If you have more than one quiz, you may also want a Quizes Table.
Quizes:
id
name
Questions:
id
quiz
prompt
Answers:
id
question
prompt
QuizResult (someone taking a quiz)
id
quiz
// other information about the quiz taker, possibly including the time
Now the correct answer thing gets a lot more tricky. I prefer the higher implementations here:
Each question has a value and each answer has value
A system I recently worked with you could assign a point value for each question and each answer. Incorrect answers often got 0, correct answers got the full amount. You could also have partially-correct answers using this method. This is the method I would go with.
You could go and say every question is worth 10 points or you could assign different weights to different questions:
Questions:
id
quiz
prompt
value (you can make this question worth more or less)
Answers:
question
prompt
value (you can make this answer worth more or less)
Store the correct answer in the Answers Table
A more simple (but less robust) solution is to simply say which answer is correct in the Answers table.
Answers:
question
prompt
is_correct
Store the correct answer in the Questions Table
I wouldn't recommend it. When you create a question, it won't have a correct answer until you insert one. This means at least 3 queries to correctly make a question. If you use foreign key dependencies, this will quickly get annoying.
Go with option 1 where you are having one row for each question/options/answer.
Option 2 does not make any sense. Every time you want to add/delete a question you'll be modifying the database schema!! And you'll have just one row always !!
Go for your first option. It is the most normalised option, but that isn't necessarily a clinching argument. But the virtues of the normalised design are manifold:
it is a piece of cake to include new questions into your quiz portfolio. (The other option requires adding new columns to the table).
it is simple to write the select statement which returns the result set. (the alternative option requires a dynamic SQL)
it is easy to write a GUI which displays the questions and answers, because each displayed set of text maps to the same coilumn_names.

Categories