my database is structured as below
at present the character, groups and vault tables all have data. The games tables is empty however.
Is it possible to write an inner join on the games table that will allow for a php search box to get data from the other three tables even though the games table has no data in it?
Is there another way of doing this that I might not know about?
For example I want to write a php search script for a webpage that searches on the games tables. If a user enters 'Allistair Tenpenny', it will pull the data from the characters table and display it in the search page with the characters name and their history, same with if some one searches a vault it will display the data from the vaults table.
From what I have read of inner joins the data on each joined table must match for it to display. Is there another way to approach this?
No inner join is necessary to get the data you want. You can simply use php to use SQL to search the appropriate table based on the user input.
If there are multiple search fields on your page, just name the submit buttons differently, then have PHP check for the existence of each submit button's POST data from the form, then perform the appropriate search. An example form might be:
<form action="" method="post">
Search Character Name:<input type="text" name="charactername">
<input type="submit" name="charsubmit" value="Search">
</form>
<form action="" method="post">
Search Vault Name:<input type="text" name="vaultname">
<input type="submit" name="vaultsubmit" value="Search">
</form>
Your PHP code can then be structured as:
if (isset($_POST['charsubmit']))
{
$stmt = $db->prepare("SELECT * FROM character_table WHERE character_name = ':mydata'");
$stmt->bindParam(':mydata',$_POST['charactername']);
}
elseif (isset($_POST['vaultsubmit']))
{
$stmt = $db->prepare("SELECT * FROM vault_table WHERE vault_name = ':mydata'");
$stmt->bindParam(':mydata',$_POST['vaultname']);
}
$stmt->execute();
Using prepared statements like this is a good way to prevent SQL injection attacks, thus ensuring user entered data is NEVER put directly into a SQL statement.
Think about it yourself. There should be no redundant information in normalized relative database. All the data tables have a column history. It should not have redundant data, which you could use to identify rows in other tables, but a description of the record set in the own table. We don't know, what vault_number is for. All other tables might be connected to the vault table directly depending on your data structure. Only you know, what your intention building this structure has been.
Further more you have connected games to groups by a redundant column with the group_name. You should avoid any redundancy and give the groups an id. Then connect it to games by a foreign group_id key. Imagine what will happen, when there are 100 games in a group and you decide to rename a group or just want to correct a typo.
Instead of joining the tables why not try to add them to an array?
create an array with the elements you need to display (don't forget to add the same number of elements from all tables (not 3 from 1 table and 4 from the other)
query the first table and use add it to the array
query the the second table and add it to the array
continue adding the tables you need
display the array
Edit:
The array could consist of 4 elements:
vault_number
name
history
type (table it's comming from)
example query would be:
select vault_number, charactor_name as name, history, 'charactor' as type from charactor
select vault_number, group_name as name, history, 'group' as type from groups
You just continue adding this to your array and you can then display all results
Take into consideration what Quasimodo's clone explained about your db normalization and the approach given by Sgt AJ could go a long way.
Related
I am building a simple adress book website where you can enter information about a person and then enter information about adresses. You can then select where people lives using a drop down menu to update the building id attribute in the person to match the automaticly generated id in the building. What I can't figure out how to do print all info about all persons(this I can do) and then print the info about the building that matches each persons building id(this I have no idea how to do. Right now I am using a while loop to print each person. But I can't get the matching building to print.
Edit: also, thanks for all info I have gotten from this site in my learning of webbprograming
You could use joins in SQL to combine several tables in one query. Also you could use GROUP BY.
Just search for that and I think you will get a good tutorial in your language.
Here are some good links:
SQL JOIN, SQL GROUP BY
Could use some code and table names to help define this example a little better, but regardless, you need to change your mysql query. In your database you need at least 1 matching row between your persons table and your buildings table. This way you can JOIN them together using the common row.
I will be using id as a placeholder for the common row in this example. Somethings like this should work:
SELECT * FROM persons LEFT JOIN buildings ON(persons.id=buildings.id) WHERE persons.building_id = buildings.building_id
To get all the results from persons and buildings you will need a separate query. But, the query above should give you the results of the person's info where the building_id matches the building_id from buildings.
I need to be able to pinpoint a value in a MySQL table which is defined by two variables.
On the frontend of the site, there is a form which accepts a variety of fields. For this example let’s focus on these two:
Account Number
Account Name
I have developed a script which will use an ajax script to check the “Account Number” once entered and if it finds a match will display the “Account Name” when the user tabs out of the field.
The difficulty is to find a single result from the format of the database tables. For example:
”SELECT * FROM example_table WHERE name=’$accountnumber’”
Provides a list of all the values that equal the account number, but does not provide any record of the account name.
”SELECT * FROM example_table WHERE name=’$accountname’”
Provides a list of all the values that equal the account names, but does not provide any record of the account number.
The $record value is the only common thread between $accountnumber and $accountname.
So all in all, I need assistance creating the loop which can first take the $accountnumber value to find the $record value associated with that number. Secondly it will take the determined $record value and match it to the $accountname value. There is only one $accountnumber and $accountname value per unique $record value.
UPDATED: There have been several good comments on this question. To help provide more background, there is only one table. The best discriminator available seems to be the title value. Here is a link to the table snippet to view in greater detail:
https://docs.google.com/file/d/0By2lFlhEzILjbE1uT1hkVURmczA/edit?usp=sharing
So ultimately in this sample, a user would type 246802 and the result that is filtered out would be Fred’s Account.
Sounds like these are in the same table? Is there any discriminator to tell you whether name holds an accountnumber or accountname?
In any even, with the following assumptions you could try an ugly self join:
There are only two records with the record ID you want
these are multiple columns in the same table holding different information in the ambiguous column names
there is no better way to discriminate the record type
If so, something like this self-join should get you started:
SELECT t2.name as accountnumber from example_table as t1
INNER JOIN example_table as t2 on t1.recordID=t2.recordID
WHERE t1.name='$accountname'
EDIT Note - if my assumptions are correct and if this is data you are inheriting, I feel for you and you should look to improve it's structure. If you are designing it like this, you may want to think about it some more first.
EDIT 2
You probably want to put an index on the name column (this is the discriminator I would used based on your example).
Your query can be something like this:
SELECT t1.value as accountnumber,t2.value as accountName from example_table as t1
INNER JOIN example_table as t2 on t1.record=t2.record
WHERE t1.name='accountNumber' and t2.name='accountName'
See this SQL Fiddle: http://www.sqlfiddle.com/#!2/97c2f/1
I have a page that retrieves records from 1 table in a database when a certain condition is met.
What I want to achieve is to provide the use to with an opportunity to update each record displayed using text boxes.
I am having trouble interpreting what logic to proceed with after the user hits the 'submit' button.
Normally, if I'm updating one record (or a static number of records), I will use the apporpriate amount of SQL statements.
Since the amount of records are dynamically generated, what is the best way to update all at once? How would I know which records were retrieved in the first place to update?
FOR EXAMPLE:
OK, We have a table with student ids (ID), names (SNAME), subjects (SUBJ), grade for each subject (GRADE) and general remarks (COMMENTS).
I want to retrieve information about all students that got an 'A', and write UNIQUE congratulatory remarks for each student (such as 'good job', or 'congratulations', or etc.)
I'd retrieve the records and lay them out on the page, with a text box next to each student record for the comments to be entered. Because I don't know how many text boxes to make, I give the text boxes dynamically generated names using the student ID. The user now enters unique comments for each student, and clicks on submit.
Now, how am I supposed to update these records with the values entered in each text box?
I wouldn't know which students were retrieved in the first place - how would I know what names to use? I'm trying to avoid having to execute the query again after submitting - but is there any other way?
Hope this question was not too confusing.
thanks
Further expanding earlier answers:
You need a loop (e.g. foreach) to display and save the textareas. If the names of the textareas include the students ID, you don't need to know the name, because the text is inserted to the database by the primary key (the students ID). You may name your form-elements as array, to iterate over them, for example (where the numbers are the IDs):
<textarea name="comment[2345234]"></textarea>
<textarea name="comment[8957485]"></textarea>
Read it out as described by #evan:
foreach((array)$_POST['comment'] as $studentId => $studentComment)
{
var_dump($studentId, $studentComment);
}
And if you implement this whole thing as self-requesting form (Affenformular in german), you may also use just one single loop to save and output the textareas.
"I don't think you're understanding what I'm trying to ask." Maybe you don't understand the answers, even you stated it. You don't need a students name to save a database record. But if you really want to submit it, you may also use hidden inputs.
Use foreach() to find the values you care about, put them in an array, and process the array.
Expanding on #Ignacio's answer to make it more easily understandable:
foreach($_POST as $name_of_input => $value_of_input)
{
// do stuff - here is something so you can see the results after the submit
echo "$name_of_input :: $value_of_input <br>";
}
I'm trying to figure out how and which is best for storing and getting multiple entries into and from a database. Either using explode, split, or preg_split. What I need to achieve is a user using a text field in a form to either send multiple messages to different users or sharing data with multiple users by enter their IDs like "101,102,103" and the PHP code to be smart enough to grab each ID by picking them each after the ",". I know this is asking a lot, but I need help from people more skilled in this area. I need to know how to make the PHP code grab IDs and be able to use functions with them. Like grabbing "101,102,103" from a database cell and grabbing different stored information in the database using the IDs grabbed from that one string.
How can I achieve this? Example will be very helpful.
Thanks
If I understand your question correctly, if you're dealing with comma delimited strings of ID numbers, it would probably be simplest to keep them in this format. The reason is because you could use it in your SQL statement when querying the database.
I'm assuming that you want to run a SELECT query to grab the users whose IDs have been entered, correct? You'd want to use a SELECT ... WHERE IN ... type of statement, like this:
// Get the ids the user submitted
$ids = $_POST['ids'];
// perform some sanitizing of $ids here to make sure
// you're not vulnerable to an SQL injection
$sql = "SELECT * FROM users WHERE ID IN ($ids)";
// execute your SQL statement
Alternatively, you could use explode to create an array of each individual ID, and then loop through so you could do some checking on each value to make sure it's correct, before using implode to concatenate them back together into a string that you can use in your SELECT ... WHERE IN ... statement.
Edit: Sorry, forgot to add: in terms of storing the list of user ids in the database, you could consider either storing the comma delimited list as a string against a message id, but that has drawbacks (difficult to do JOINS on other tables if you needed to). Alternatively, the better option would be to create a lookup type table, which basically consists of two columns: messageid, userid. You could then store each individual userid against the messageid e.g.
messageid | userid
1 | 1
1 | 3
1 | 5
The benefit of this approach is that you can then use this table to join other tables (maybe you have a separate message table that stores details of the message itself).
Under this method, you'd create a new entry in the message table, get the id back, then explode the userids string into its separate parts, and finally create your INSERT statement to insert the data using the individual ids and the message id. You'd need to work out other mechanisms to handle any editing of the list of userids for a message, and deletion as well.
Hope that made sense!
Well, considering the three functions you suggested :
explode() will work fine if you have a simple pattern that's always the same.
For instance, always ', ', but never ','
split() uses POSIX regex -- which are deprecated -- and should not be used anymore.
preg_split() uses a regex as pattern ; and, so, will accept more situations than explode().
Then : do not store several values in a single database column : it'll be impossible to do any kind of useful work with that !
Create a different table to store those data, with a single value per row -- having several rows corresponding to one line in the first table.
I think your problem is more with SQL than with PHP.
Technically you could store ids into a single MySQL field, in a 'set' field and query against it by using IN or FIND_IN_SET in your conditions. The lookups are actually super fast, but this is not considered best practice and creates a de-normalized database.
What is nest practice, and normalized, is to create separate relationship tables. So, using your example of messages, you would probably have a 'users' table, a 'messages' table, and a 'users_messages' table for relating messages between users. The 'messages' table would contain the message information and maybe a 'user_id' field for the original sender (since there can only be one), and the 'users_messages' table would simply contain a 'user_id' and 'message_id' field, containing rows linking messages to the various users they belong to. Then you just need to use JOIN queries to retrieve the data, so if you were retrieving a user's inbox, a query would look something like this:
SELECT
messages.*
FROM
messages
LEFT JOIN users_messages ON users_messages.message_id = messages.message_id
WHERE
users_messages.user_id = '(some user id)'
I have an array of user ids in a query from Database A, Table A (AA).
I have the main user database in Database B, Table A (BA).
For each user id returned in my result array from AA, I want to retrieve the first and last name of that user id from BA.
Different user accounts control each database. Unfortunately each login cannot have permissions to each database.
Question: How can I retrieve the firsts and lasts with the least amount of queries and / or processing time? With 20 users in the array? With 20,000 users in the array? Any order of magnitude higher, if applicable?
Using php 5 / mysql 5.
As long as the databases are on the same server just use a cross database join. The DB login being used to access the data will also need permissions on both databases. Something like:
SELECT AA.userID, BA.first, BA.last
FROM databasename.schema.table AA
INNER JOIN databasename.schema.table BA ON AA.userID = BA.userID
In response to comments:
I don't believe I read the part about multiple logins correctly, sorry. You cannot use two different mySQL logins on one connection. If you need to do multiple queries you really only have three options. A) Loop through the first result set and run multiple queries. B) Run a query which uses a WHERE clause with userID IN (#firstResultSet) and pass in the first result set. C) Select everything out of the second DB and join them in code.
All three of those options are not very good, so I would ask, why can't you change user permissions on one of the two DBs? I would also ask, why would you need to select the names and IDs of 20,000 users? Unless this is some type of data dump, I would be looking for a different way to display the data which would be both easier to use and less query intensive.
All that said, whichever option you choose will be based on a variety of different circumstances. With a low number of records, under 1,000, I would use option B. With a higher number of records, I would probably use options C and try to place the two result sets into something that can be joined (such as using array_combine).
I think they key here is that it should be possible in two database calls.
Your first one to get the id's from database A and the second one to pass them to database B.
I don't know mysql, but in sqlserver I'd use the xml datatype and pass all of the ids into a statement using that. Before the xml datatype I'd have built up some dynamic SQL with the id's in an IN statement.
SELECT UserId FROM DatabaseA.TableA
Loop through id's and build up a comma separated string.
"SELECT FirstName, Surname FROM DataBaseB.TableA WHERE UserId IN(" + stringId + ")"
The problem with this is that wth 20,000 id's you may have some performance issues with the amount of data you are sending. This is where'd I'd use the XML datatype, so maybe look at what alternatives mysql has for passing lists of ids.