As i am far from an expert in php this got me stunned and i can't seem to make a script for it.
Lets see if i can explain this as clearly as possible.
Lets say i have table1 and table2
Table1 = (teamid, name, round1pos, round1score, round2pos, round2score)
Table2 = (id, tournamentid, teamid, name, round1pos, round1score, round2pos, round2score...till round10pos/round10score)
When copied from table1 to table 2 i want to add 2 fields in front of it. (id and tournamentid)
The problem i am facing is that Table1 has a different amount of roundxpos/roundxscore each time.
Basically what i want to do is once a tournament is over i want to delete the table. but copy the data inside it to another table to archive the results. but each tournament can have a different size of rounds.
I hope someone can understand what i am trying to achieve +_+.
You should create a third table, remove the roundX columns from your existing tables and reference them with their IDs.
rounds: team_id, tournament_id, no, pos, score
You should normalize your tables but in the meantime....
I'm assuming the main problem is handling the variable number of roundxpos and roundxscore columns in the code.
Hope this helps:
Get the results of this query: SHOW COLUMNS FROM Table1 WHERE Field LIKE 'round%pos'
Get the results of this query: SHOW COLUMNS FROM Table1 WHERE Field LIKE 'round%score'
Create the table2 inserts by looping through field names
//example, assuming results are fetched into an associative array
$query = "INSERT INTO table2 (tournamentid, teamid, name)";
foreach($roundpos_fields as $f){ $query .= "," . $f['Field']; }
foreach($roundscore_fields as $f){ $query .= "," . $f['Field']; }
$query .= "( SELECT $tournamentid, '' teamid, name";
foreach($roundpos_fields as $f){ $query .= "," . $f['Field']; }
foreach($roundscore_fields as $f){ $query .= "," . $f['Field']; }
$query .= ")";
Related
We have a HTML search page, having multiple text fields to search.
The user can input as many values as he want in text field and on submit, the query should return appropriate results.
We have different tables as
candidate
candidate_contact
company
etc.
Example:
User enters like candidate should have java skills also lives in California but should not have experience less than 2 years.
These records can be in same or different tables (like skills and country in same table and exp in another table)
Its like including and excluding search result.
$query = array();
if (!empty($_POST['keyword_s_dec']))
{
$query[] = "candidate.cand_desc = '".mysql_real_escape_string($_POST['keyword_s_dec'])."'";
$join.="JOIN candidate_contact ON candidate.cand_desc=candidate_contact.cand_id";
//$join.="select * from candidate join candidate_contact ON candidate.cand_number=candidate_contact.cand_id WHERE candidate.cand_desc='".$_POST['keyword_s_dec']."'";
}
if (!empty($_POT['keyword_s_location']))
{
$query[] = "candidate_contact.cand_location = '".mysql_real_escape_string($_POST['keyword_s_location;'])."'";///edit
$join.=" AND JOIN candidate_contact ON candidate.cand_number=candidate_contact.cand_id";
}
//$condition = implode(' AND ', $query);
$condition = implode(' AND ', $query);
$sql = "SELECT * FROM candidate".$join.' where '.$condition;
where - candidate is my main table and candidate_contact is another table.
where -cand_desc is database column in candidate & keyword_s-dec is text field id.
where- cand_location is my database column in candidate_contact and keywors_s_location is text field id.
This code is being slightly guided by one of stack overflow member and we though this should be edit to get more precised to the problem.
SELECT candidate.*,candidate_contact.feild_name1,candidate_contact.feild_name2
FROM candidate
LEFT JOIN candidate_contact
ON candidate.cand_number=candidate_contact.cand_id where $condition
Note:- add the table name with .(dot)in the where clause to define which feild name you want to do the comparision as shown in selection field area of the query and can continue joinning different tables in the same way as above before the where clause.
Hope this will solve your problem
if (!empty($_POST['keyword_s_dec']))
{
$query[] = "candidate.cand_desc = '".mysql_real_escape_string($_POST['keyword_s_dec'])."'";
$join.=" JOIN candidate_contact ON candidate.cand_number=candidate_contact.cand_id";
}
if (!empty($_POST['keyword_s_preflocation']))
{
$query[] = "candidate_contact.cand_location = '".mysql_real_escape_string($_POST['keyword_s_preflocation'])."'";///edit
//$join.=" LEFT JOIN candidate_contact ON candidate.cand_number=candidate_contact.cand_id";
}
$condition = implode(' AND ', $query);
$sql = "SELECT * FROM candidate ".$join.' where '.$condition;
#karvin.developer If the join condition gets same it won't work. I made some mistakes but re-read your statements from the start and it worked for me like heaven. Thank you karvin.developer :)
I have a table that is being displayed in a form, which looks like this: http://puu.sh/5VBBv.png
The end of the table, City, is displaying an ID of a city, which is supposed to be linked to another table (http://puu.sh/5VBIG.png).
What I've done for my INNER JOIN query is:
mysql_query("SELECT * FROM cities INNER JOIN people ON people.cityid = cities.id") or die(mysql_error());`
and I'm trying to output it into a table:
echo "<td>" . $row['cityid'] . "</td>";
My issue is that I'm not quite sure how to actually display the cityid that corresponds to the city name. I've tried using ['name'] and other values as the value to output in the table, and I can't find any solution for this anywhere so far. I'm just learning joins, so I don't exactly have any knowledge on what I could be doing wrong. Is there anything immensely obvious?
First your use of * in the join query could be ambiguous. If cities had a name column and people had a name column, you won't know which one you're getting. Second you can do this a couple ways. I think you're trying to get a city id from a city name. If that's correct you can either make and ajax call and query it directly or define an array as follow:
$res = mysql_query("...");
$city_ids = Array();
while ($ary = mysql_fetch_assoc($res)) {
city_ids[$ary['name']] = Ary['id'];
}
Then when you get the name, you just loop up $ary['name'].
Selecting from people and joining cities makes more sense. Then select the fields you need.
SELECT people.*, cities.name as city_name FROM people JOIN cities ON people.cityid = cities.id
Then, echo $row['city_name']
Select ID from cities city, people person where person.ID = city.ID
You are selecting the ID from both Cities and People, and joining on the ID
EDIT: Added the first SQL query.
A section of my website has two dropdown menus. All the options in both are populated using SQL queries. Dropdown#1 is a list of class sections (like A1 for example). Once the professor selects a section, Dropdown#2 is populated with the student ID's (like 1234567 for example).
Student information is found in table 1. Among this information is the 'professorName' column. In order to associate the student with a class section, I need to match 'professorName' column with an identical column found in table 2, because class sections are only found in table 2.
Till here everything works great, because at the end of my query I put ORDER BY student ID. However, two of the class sections are associated to two different professors. In order to deal with this issue, I used the following code to loop through each professor name.
$from site = $_POST['section'];
$query = ("SELECT professorName FROM Table 2 WHERE classSection='$fromsite'");
$NumberofProfessorNames = $objMSSQL->getAffectedRows();
echo $NumberofProfessorNames;
for ($j=0; $j<$NumberofProfessorNames; $j++)
{
$section= $query[$j][professorName];
$output = $objMSSQL->getTable("SELECT DISTINCT StudentID from table1 WHERE professorName='$section' ORDER BY StudentID");
for ($i=0; $i<$objMSSQL->getAffectedRows(); $i++)
{
echo "<option value='".$output[$i][studentID]."'>".$output[$i][studentID]."</option>";
}
}
The problem is that for the only two sections where this is even necessary (because there are two professorNames), since it is looping like this, it is ending up ordered like this in the dropdown#2:
1234567
2345678
3456789
4567890
1234123
2345765
3456999
4567000
My limited experience in programming is keeping me from understanding how I can fix this seemingly simple issue.
Thank you for your help.
Rather than loop over the professors and query table1 for each, join table1 and table2 in the second query and only query the database once. For example:
$query = [... FROM Table2...];
$NumberofProfessorNames = $objMSSQL->getAffectedRows();
echo $NumberofProfessorNames;
$output = $objMSSQL->getTable("
SELECT DISTINCT StudentID
from table1
join table2
on ...
WHERE [the same clause you used in $query]
ORDER BY StudentID"
);
for ($i=0; $i<$objMSSQL->getAffectedRows(); $i++)
{
echo "<option value='".$output[$i][studentID]."'>".$output[$i][studentID]."</option>";
}
It's more elegant (and almost certainly more efficient) than generating a WHERE IN clause.
Yu can do it this way:
$section = "('";
for ($j=0; $j<$NumberofProfessorNames; $j++)
{
$section.= $query[$j][professorName] . "','";
}
$section = substr($section, 0, -3) . ')'; //$section contains ('prof1','prof2')
$output = $objMSSQL->getTable("SELECT DISTINCT StudentID from table1 WHERE professorName IN $section ORDER BY StudentID");
for ($i=0; $i<$objMSSQL->getAffectedRows(); $i++)
{
echo "<option value='".$output[$i][studentID]."'>".$output[$i][studentID]."</option>";
}
that is querying for all your professors in just one sql with IN() syntax.
UPDATE: I've just noted you use sql server instead of mysql, so I've changed the IN() syntax a bit and change the link to the sql server help docs.
It sounds like your tables aren't normalized. Good form would have a sections table, a students table, and a professors table. Information in each table should be specific to the table's topic.
students
student_id
student_last_name
student_first_name
student_address
etc
sections
section_id
section_name - multiple sections can tend to have the same name but differing content
section_description
section_year - sections can change from year to year
faculty
faculty_id
faculty_name - this is not a key field, more than one person can have the same name.
faculty_address
faculty_type - adjunct, fulltime, etc.
You would then have relational tables so you can associate professors with sections and students with sections.
faculty_2_sections
f2s_id
faculty_id
section_id
student_2_sections
s2s_id
student_id
section_id
This makes it super simple because if a student is logged in, then you already have their student id. If it's a professor, you already have their faculty_id
If you're pulling for students, your sql might look like this:
$sql = "select * from students s,sections sc,faculty f,faculty_2_sections f2s,student_2_sections s2s where student_id='$student_id' and s2s.student_id=s.student_id and s2s.section_id=sc.section_id and f2s.faculty_id=f.faculty_id and f2s.section_id=s2s.section_id";
If you're pulling for faculty you would do this:
$sql = "select * from students s,sections sc,faculty f,faculty_2_sections f2s,student_2_sections s2s where faculty_id='$faculty_id' and f2s.faculty_id=f.faculty_id and f2s.section_id=s2s.section_id and s2s.section_id=sc.section_id and s2s.student_id=s.student_id";
You can then pull a list of sections to populate the section_ids pull-down to only show students or faculty for a specific section.
I have a table (country_table) with a list of all countries and their respective ids.
|country_id|country_name|
|ES |Spain |
.
.
.
I have an array, fetched from another table using fetch_array that looks like this:
$array = Array(
[0]=>Array([country_id]=>'ES')
[1]=>Array([country_id]=>'DE')
[2]=>Array([country_id]=>'GB'))
How can I select the records (country_id and country_name) from country_table that do not exist in the table but exist in the array?
$sql ="SELECT country_id, country_name FROM country_table
WHERE country_id NOT IN (". implode(",", $array) .")";
implode() function will generate comma-seprated string representation of array elements .
This is the sql.
select country_id, country_name from table where country_id not in ('ES','DE','GB');
// gather unwanted id's first
$notInIds = array();
foreach ($array as $arr) $notInIds[] = $arr['country_id'];
// prepare query
$query = 'SELECT `country_id`, `country_name` FROM `your_table`
WHERE `country_id` NOT IN (' . implode(',',$notInIds) . ')';
// then execute it
For the question: "How can I select the records (country_id and country_name) from country_table that do not exist in the table but exist in the array?"
I guess you have to write some code (eg. in PHP) in order to achieve the result you want.
The problem is that you can not display data that is not in the table (eg. country_name), that's not possible as you don't know this data. The only possibility would to show the country_id's which are in the array and not in the table as this is the only data you have...
I am designing a MYSQL database for online tutoring website
Let's say, I have:
faculty table with (faculty_id, faculty name)
subject table with (subject_id, subject name)
student table with (student_id, student name)
class table with (class_id, faculty_id, student_id, subject_id)
Now I would like to run SQL queries on the class table to find out all students enrolled with a particular faculty & under a particular subject for which I have:
$sql=("SELECT *
FROM class
WHERE (faculty_id = '" . mysql_real_escape_string($_POST['faculty_id']) . "')
and (subject_id = '" . mysql_real_escape_string($_POST['subject_id']) . "')");
However, I can't seem to figure out how to retrieve student name, faculty name, and subject name instead of just the faculty_id, student_id & subject_id stored in the class table.
Is there some type of SCHEMA and foreign key relations I need to create which automatically link the ID numbers to their respective rows in the respective tables so i can run UPDATE, DELETE, and INSERT queries based on these ID numbers?
Am I missing something important here? I'm not an expert in DB design. Please help.
That's not something that happens in your schema, it's something that you do when you query the database.
To get information from a related table, you JOIN that table.
SELECT
class.class_id,
student.name AS `student_name`,
faculty.name AS `faculty_name`,
subject.name AS `subject_name`
FROM
class
INNER JOIN
student
ON
student.student_id = class.student_id
INNER JOIN
faculty
ON
faculty.faculty_id = class.faculty_id
INNER JOIN
subject
ON
subject.subject_id = class.subject_id
WHERE
class.faculty_id = ?
AND
class.subject_id = ?
You'll have to replace any column names with what they actually are (your examples had spaces in them, so I'm sure those aren't the real names), and put your PHP code with the post values where the ? are... good time to read up on PDO parameterized queries too.
$sql=("SELECT * FROM class c, student s WHERE (c.faculty_id = '" . mysql_real_escape_string($_POST['faculty_id']) . "') and (c.subject_id = '" . mysql_real_escape_string($_POST['subject_id']) . "') and s.student_id = c.student_id");
You need to also select values from the table student.