PHP - Join On Same Table?
Hi, well, I think it's about joining within the same table, but I'm not sure. Here's my problem:
I have a table with a number of categories and undercategories, see screendump of database he I show the categories in my select by: <option value="<?php echo $row['id']; ?>"><?php echo $row['name']; ?></option> This gives me (here sorted alphabetically): 1.semester 3.semester 5.semester Underkategori_1_i_1.semester Underkategori_1_i_3.semester Underkategori_1.1_i_3.semester But I would like for it to show the path (the relation between categori and under-/subcategory (see "parent" and "path" in the database (screenshot above)), so that is will display the list like this: 1.semester 1.semester/Underkategori_1_i_1.semester 3.semester 3.semester/Underkategori_1_i_3.semester 3.semesterUnderkategori_1_i_3.semester/Underkategori_1.1_i_3.semester 5.semester etc. How can I join either "parent" or "path" with "id" (see screendump of database above) to create a listing like that? Or is that the correct way to do it at all? Hope someone can help me out! Similar TutorialsSELECT R.RegionName, A.City FROM `activepropertylist` A, `ParentRegionList` R, `RegionEANHotelIDMapping` RM WHERE MATCH(City, RegionName) AGAINST ('hervey bay' IN BOOLEAN MODE) and A.EANHotelID = RM.EANHotelID and RM.RegionID = R.RegionID and R.RegionType = 'Neighborhood' schema http://developer.ean.com/database-catalogs/relational/geography-data/ book a suit search box example http://www.bookasuite.com/I am trying to join 3 tables together to get the correct information from expedia tables for my auto drop down box the schema is here, located in the link and I am looking auto search like book a suite do(link also provided) problem is I can manage to get the word hervey bay out of the property region list table but the incorrect city comes back from the activeproperylist table(it seems to be showing something from the other table for the city) here is my query This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=321459.0 Hi, I have a fantasy football website, and on a user account page I want to display fixtures that are coming up that include teams that the current user has chosen. My test_teams table stores all the team names and their teamid. The test_selections table is where each users team selections are stored, it has two columns, userid and teamid. The test_fixtures table has two columns, hometeam and awayteam, these two cloumns hold the teamid of the teams that are playing. The code below correctly displays the fixtures that contain any of the current users team selections. However, it is only displaying the teamid of the teams that are playing as they have not been matched to the test_teams table to get the team name. Does anybody now how I can do this? I believe it can be done using a left join but so far I just keep getting errors when i try to write the code. Any help would be very much appreciated. Code: [Select] <table width="380" border="0"> <?php $query = "SELECT test_fixtures.competition, test_fixtures.date, test_fixtures.hometeam, test_fixtures.awayteam FROM test_fixtures, test_selections WHERE test_selections.userid = '{$_SESSION['userid']}' AND (test_selections.teamid = test_fixtures.hometeam OR test_selections.teamid = test_fixtures.awayteam)"; $result = mysql_query($query) or die(mysql_error()); while($row = mysql_fetch_assoc($result)) { ?> <tr> <td width="85" class="fixtures_date"><?php echo $row['date']; ?></td> <td width="30" class="fixtures_comp"><?php echo $row['competition']; ?></td> <td width="135" class="fixtures_home_teams"><?php echo $row['hometeam']; ?></td> <td width="25" class="fixtures_center">v</td> <td width="135" class="fixtures_away_teams"><?php echo $row['awayteam']; ?></td> </tr> <?php } ?> </table> I'm outputting my DB to a table. I want to include a JOIN so the table shows name, email, and company (which is in a different table). Not sure where to put the join. 2 other things I'd like to do: Not all users have email and I want any NULL to output as N/A instead of NULL. Would like the rows to alternate background color between white and blue for each row. Any hints appreciated. $query= "select * from Managers"; $result=mysql_query($query); echo mysql_error(); echo '<table align="center" cellspacing="1" cellpadding="2"> <tr> <td align="left"><b>Name</b></td> <td align="left"><b>Email</b></td> <td align="left"><b>Company</b></td> </tr> '; while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { echo '<tr bgcolor="' . $bg . '"> <td align="left">' . $row['name'] . '</td> <td align="left">' . $row['email'] . '</td> <td align="left">' . $row['company.name'] . '</td> //Need JOIN here </tr> '; } Dear All, As I would like to create json as below format { "data": [ { "title": "After getting a COVID-19 Vaccine", "content": [ { "list": "You may have some side effects, which are normal signs that your body is building protection." }, { "list": "Following symptoms can take place, and it usually resolves within 2 to 3 days." }, { "list": "Common Side Effects pain, redness, swelling, warmth, nausea, muscle pain, tiredness, headache" } ] }, { "title": "After getting a COVID-19 Vaccine", "content": [ { "list": "You may have some side effects, which are normal signs that your body is building protection." }, { "list": "Following symptoms can take place, and it usually resolves within 2 to 3 days." }, { "list": "Common Side Effects pain, redness, swelling, warmth, nausea, muscle pain, tiredness, headache" } ] } ] } The information is from mysql select command: SELECT (tb_helpinfo.title_eng) as title,(tb_helpdetail.content_eng) as content FROM tb_helpinfo INNER JOIN tb_helpdetail ON tb_helpinfo.id = tb_helpdetail.helpinfo_id
I have two mysql tables, one is called "posts", the other is called "removed_posts", I have joined them together and can get some of the information from the tables, but I want to be able to get all of the information. This is my query, and the variables I need the information to go to: Code: [Select] $quer = mysql_query("SELECT posts.id, removed_posts.post_id FROM posts, removed_posts WHERE posts.id=removed_posts.post_id AND removed_posts.user_id='".$session."'"); while($get_post = mysql_fetch_array($quer)) { $session = $_COOKIE['id']; $to_id = $get_post['to_id']; $from_id = $get_post['from_id']; $post = linkify(nl2br(htmlentities($get_post['post']))); $date = time_stamp($get_post['date']); $id = $get_post['id']; What that's doing is selecting the id from 'posts' table, and selecting the post_id from the 'removed_posts' table (The query checks to make sure posts.id is equal to removed_posts.post_id), it does that just fine, since I defined what information I wanted it to get in the query, however, now I need to get the other information which will come from the 'posts' table. $get_post['to_id'], $get_post['from_id'], $get_post['post'], and $get_post['date'] I hope that's not toooooo confusing, any help would be appreciated I'm trying to conditionally add a table to a select query using the join, but I always get an "no such table" error. I'm not at all sure if the syntax is correct, so I decided to ask.
I'm using the sqlite C API interface and my tables and query were constructed using sprintf, so please ignore any %d, %s that may appear
CREATE TABLE IF NOT EXISTS tbl_master ( id INTEGER PRIMARY KEY AUTOINCREMENT, volume TEXT(16) UNIQUE NOT NULL DEFAULT '', note TEXT(%d) NOT NULL DEFAULT '', items INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS tbl_file ( id INTEGER PRIMARY KEY AUTOINCREMENT, volume_key TEXT(16) NOT NULL DEFAULT '', name TEXT(%d), size TEXT(20), type TEXT(4), path TEXT(%d), file_id INTEGER ); CREATE TABLE IF NOT EXISTS tbl_hash ( id INTEGER PRIMARY KEY AUTOINCREMENT, hash TEXT(33) NOT NULL DEFAULT '', volume_key TEXT(16) NOT NULL DEFAULT '', file_key INTEGER NOT NULL DEFAULT 0 ); CREATE TABLE IF NOT EXISTS tbl_media ( id INTEGER PRIMARY KEY AUTOINCREMENT, runtime TEXT(10) NOT NULL DEFAULT '', frame TEXT(12) NOT NULL DEFAULT '', type_key TEXT(4) NOT NULL DEFAULT '', hash_key TEXT(33) NOT NULL DEFAULT '', volume_key TEXT(16) NOT NULL DEFAULT '', file_key INTEGER NOT NULL DEFAULT 0 );I milled over a few JOIN tutorials, but I'm still unclear on the exact usage of JOIN; I'm trying to add the media table if the file type is a vid, snd, or pix, but I need file information regardless. I've tried various flavors of the following query, but each time I get the table doesn't exist error. Selects, deletes, updates, inserts work on all tables, so I'm guessing my syntax is wrong with the JOIN. SELECT tbl_file.*, tbl_hash.hash FROM tbl_file AS f, tbl_hash AS h LEFT OUTER JOIN tbl_media AS m ON ((f.type='VID' OR f.type='SND' OR f.type='PIX') AND m.file_key=f.file_id) WHERE ((f.volume_key=tbl_master.volume AND (h.volume_key=tbl_master.volume AND h.file_key=f.file_id))) ORDER BY f.path ASC;Any ideas on how to pull off what I'm trying to do would be greatly appreciated. Thank you for your time. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=308855.0 Hello everyone,
I am hopping someone can help me sort out a query.
I have two tables, one table is a players table, and a second table is a player_vitals data that stores heights and weight changes. I want to list all the players showing the latest height and weight change.
this query will not fetch the latest height and weight
SELECT a.player_id, a.player_first_name,a.player_last_name, b.player_height, b.player_weight First off Please bear with me. I am newbie. Here is a table name 'Employes' and has following Columns. ID(PK) | FirstName | LastName | SecurityLicence | CrowdLicence | DriversLicence | Password | And through form all the values are assigned to these columns and user gets registered. I have done it using this code and its working fine. Code: [Select] <?php session_name('YourVisitID'); session_start(); if(!isset($_SESSION['FirstName'])) { header("Location: http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/index.php"); exit(); } else { $page_title = 'Register'; include('templates/header.inc'); if(isset($_POST['submit'])) { require_once('mysql_connect.php'); // connect to the db //Create a function for escaping the data. function escape_data($data) { global $con; // need connection if(ini_get('magic_quotes_gpc')) { $data = stripslashes($data); } return mysql_real_escape_string($data, $con); } $message = NULL; if(empty($_POST['firstName'])) { $fn = FALSE; $message .= '<p>you forgot to enter your first name!</p>'; } else { $fn = escape_data($_POST['firstName']); } if(empty($_POST['lastName'])) { $ln = FALSE; $message .= '<p>You forgot to enter your last name!</p>'; } else { $ln = escape_data($_POST['lastName']); } if(empty($_POST['licenceId'])) { $li = FALSE; $message .='<p>You Forgot enter your Security Officer Licence Number!</p>'; } else { $li = escape_data($_POST['licenceId']); } if(empty($_POST['crowdLicenceNo'])) { $cln = FALSE; $message .='<p>You Forgot to enter your Crowd Controller Licence Number!</p>'; } else { $cln = escape_data($_POST['crowdLicenceNo']); } if(empty($_POST['driverLicenceNo'])) { $dln = FALSE; $message .='<p>You forgot to enter your Driving Licence Number!</p>'; } else { $dln = escape_data($_POST['driverLicenceNo']); } if(empty($_POST['password'])) { $p = FALSE; $message .='<p>You forgot to enter your password!</p>'; } else { if($_POST['password'] == $_POST['password2']) { $p = escape_data($_POST['password']); } else { $p = FALSE; $message .='<p>Your password did not match the confirmed password</p>'; } } if($fn && $ln && $li && $cln && $dln && $p) { $query = "SELECT ID FROM Employes WHERE SecurityLicence='$li'"; $result = @mysql_query($query); if(mysql_num_rows($result) == 0) { $query = "INSERT INTO Employes (FirstName, LastName, SecurityLicence, CrowdLicence, Driverslicence, Password) VALUES ('$fn', '$ln', '$li', '$cln', '$dln', PASSWORD('$p'))"; $result = @mysql_query($query); if($result) { echo '<p>You have been registered</p>'; } else { $message = '<p>We apologise there is a system error.</p><p>' . mysql_error(). '</p>'; } } else { $message = '<p>That Security Licence is already registered</p>'; } mysql_close(); } else { $message .='<p>Please try again</p>'; } } //print the message if there is one if (isset($message)) { echo '<font color="red">', $message, '</font>'; } } ?> <script type="text/javascript"> function validate_form() { var f = document.forms["regForm"]["firstName"].value; if(f==null || f=="") { alert("First Name must be filled out"); return false; } var l = document.forms["regForm"]["lastName"].value; if(l==null || l=="") { alert("Last Name must be filled out"); return false; } var sl = document.forms["regForm"]["licenceId"].value; var s = /^\d{5,}$/g.test(sl); var sll = sl.length; if(s==false) { alert("Security Licence No must be filled out in digits"); return false; } else if(sll>=7) { alert("Invalid Security Licence No"); return false; } var csl = document.forms["regForm"]["crowdLicenceNo"].value; var k = /^\d{5,}$/g.test(csl); var csll = csl.length; if(k==false) { alert("Crowd Controller Licence No must be filled out in digits"); return false; } else if(csll>=7) { alert("Invalid Crowd Controller Licence No"); return false; } var d = document.forms["regForm"]["driverLicenceNo"].value; var v = /^\d{6,}$/g.test(d); var dl = d.length; if(v==false) { alert("Driver's Licence No must be filled out in digits"); return false; } else if(dl>=11) { alert("Invalid Driver's Licence No"); return false; } } </script> <h3>Employment Registration Form</h3> <form action="<?php echo $_SERVER['PHP_SELF']; ?>" name="regForm" method="post" onsubmit="return validate_form()"> <fieldset> <legend>Enter informations in the form below</legend> <table> <tr><th>First Name:</th><td><input type="text" name="firstName" /></td></tr> <tr><th>Last Name:</th><td><input type="text" name="lastName" /></td></tr> <tr><th>SO Licence No:</th><td><input type="text" name="licenceId" size="5" /></td></tr> <tr><th>CC Licence No:</th><td><input type="text" name="crowdLicenceNo" size="5" /></td></tr> <tr><th>Driver's Licence No:</th><td><input type="text" name="driverLicenceNo" size="10" /></td></tr> <tr><th>Create Password:</th><td><input type="password" name="password" size="10" /></td></tr> <tr><th>Confirm Password:</th><td><input type="password" name="password2" size="10" /></td></tr> </table> <input type="submit" name="submit" value="Register" /> <input type="reset" value="Reset" /> </fieldset> </form> <?php include('templates/footer.inc'); ?> Here is another Table "Jobs", with the following columns. JobID(PK) | ID(FK) | JobDate | JobStart | JobFinish | JobLocation | RequestedBy | For Example I am the owner of the company and want to assign jobs to my registerd workers using a form. I assign JobDate=12/12/12 JobStart=1900 JobFinish=2300 JobLocation=Perth Requestedby=John. And I do it using form. JobID will be incremented automatically. Now what i dont understand is how do I assign ID(FK) to it?? I am newbie this question may sound stupid to many of you but hey please help. Or should I replace ID(FK) with the SecurityLicence of the worker, Like this JobID(PK) |ToSecurityLicence | JobDate | JobStart | JobFinish | JobLocation | RequestedBy | What I want is when the workers signs in He should see the job assigned to him. Can I do it using inner join??? if so how to right PHP code for comparing these two tables??? I am way too much confused. Too many of you I have made a fool of myself asking this question. But I believe a person who doesnt ask the question is fool foreva. If somebody could Help I would really really aprreciate it. Thanks. I'm trying to pull from my database every spell or attack that is equal to `All`, but it doesn't seem to be working. All it is doing is pulling all the spells, regardless of class = `All`, and also 0 of the attacks. It should be producing a single attack that is = to `All` as no spells are = `All`. Any help would be greatly appreciated! Thanks! (This is my first attempt at a JOIN statement...) $query = "SELECT attacks.id, attacks.name, attacks.price, attacks.class, attacks.descript, spells.id, spells.name, spells.price, spells.class, spells.descript ". "FROM attacks, spells ". "WHERE attacks.class = 'All' || spells.class = 'All' order by attacks.name, spells.name asc"; I'm trying to figure out the best way to do this if I'm doing it right with my for loop. With how many numAnswers there are for the selected poll its going to put the div with the label and text box for each of those but its giong to go and tie in each of those pollAnswers with what ID of the pollAnswer to the pollAnswer table. Code: [Select] $pollsQuery = " SELECT polls.question, polls.statusID, polls.numAnswers, DATE_FORMAT(polls.dateExpires, '%m/%d/%Y') AS dateExpires FROM polls WHERE polls.ID = '" . $pollID . "'"; $pollsResult = mysqli_query ( $dbc, $pollsQuery ); // Run The Query $row = mysqli_fetch_array ( $pollsResult, MYSQL_ASSOC ); $pollAnswers = " SELECT pollAnswers.ID, pollAnswers.answer FROM pollAnswers WHERE pollAnswers.pollID = '" . $pollID . "'"; $pollAnswersResult = mysqli_query ( $dbc, $pollAnswers ); // Run The Query Code: [Select] <fieldset class="answerLeg"> <legend>Edit Poll Answers</legend> <?php for ( $j = 0; $j <= $numAnswers; $j++) { ?> <div class="field required answers"> <label for="answer<?php $j?>">Answer <?php $j?></label><input type="text" class="text" name="answer<?php $j?>" id="answer<?php $j?>" title="Answer <?php $j?>"/> <span class="required-icon tooltip" title="Required field - This field is required, it cannot be blank, and must contain something that is different from emptyness in order to be filled in. ">Required</span> </div> <?php } ?> </fieldset> I'm an amateur PHP/mySQL person, trying to learn some more things, and I've hit a snag trying to do something I haven't done before. Okay, here's what I'm trying to do. I have 3 tables: Items (which includes `id` as the primary key) and a TON of information about each item. Shop (which includes `id` as the primary key) and shop name and location. Sale which has shop_id and item_id. So, what I'm trying to do is have a form where someone can input in an item name and a shop name and have that item then added to the shop. This is where the Sale table comes into play too, as that's going to house each of the items and what shop it's in. I currently have the following queries: $query5 = $db->execute("SELECT id FROM items LEFT JOIN sale ON items.id=sale.item_id"); $query6 = $db->execute("SELECT id FROM shop LEFT JOIN sale ON shop.id=sale.shop_id"); I have the following form: if ($name == "") { $errors++; $errorlist .= "Name is required.<br />"; } if ($location == "" ) { $errors++; $errorlist .= "Location is required.<br />"; } if (!isitem($itemname)) die("That item does not exist."); } if ($errors == 0) { $query = doquery("INSERT INTO `sale` SET `item_id`=`$item`"); admindisplay("New Item Added.","Add Items"); $page = <<<END <b><u>Add Item</u></b><br /><br /> <form action="create_shop.php?do=additem" method="post"> <table width="90%"> <tr><td width="20%">Name:</td><td><input type="text" name="itemname" size="30" maxlength="255" value="" />**Be sure the item is already in the database and matches it IDENTICALLY.</td></tr> <tr><td width="20%">Location:</td><td><input type="text" name="location" size="30" maxlength="55" value="" /><br /><span class="small">Where is the item obtained (unique shop name, please!)</span></td></tr> </table> <input type="submit" name="submit" value="Submit" /> <input type="reset" name="reset" value="Reset" /> </form> What next steps do I need to take? Am I even on the right path? Thanks for any and all help anyone provides!! I really appreciate it! Not sure if it is because it is too early in the morning but I am having a problem. Code: [Select] $mpid = # $query = "SELECT table1.title, table2.* ". "FROM table1, table2 ". "WHERE table1.mpid = table2.mpid"; How do I only show the info from the 2 tables where mpid=# Hi I want to know I can select which ID I get from an inner join? Not sure If I should post here or in the MYSQL forum, but as it's using OOP I posted here. Code: [Select] $sql = "SELECT * FROM area_county INNER JOIN area_country "; $sql .= "ON area_county.country_id = area_country.id "; $sql .= "ORDER BY area_country.country, area_county.county ASC "; $sql .= "LIMIT {$per_page} "; $sql .= "OFFSET {$pagination->offset()}"; $list = Area_county::find_by_sql($sql); foreach($list as $lists){ $ID = $lists->id; $country_id = $lists->country_id; $county = ucwords($lists->county); $country = ucwords($lists->country); echo $ID; } I want it to show the ID of the county, NOT the id of the country. both tables in the database have the ID column called id. I know this can be done, but not to sure how. Thanks Im currently working on a new feature called 'Request Player'. Basically what this does is allows managers to request players within their club for a upcoming fixture. There a multiple teams within a club (Senior As, Senior Bs, Colts U21s). Each team is controlled by a manager. And then they can add players as they need. Anyway, I'm having problems with the sql JOIN. I have currently got this: $check = "SELECT u.* FROM users AS u LEFT JOIN requests AS r ON (u.id = r.player_id) WHERE (u.id = r.player_id)"; I have got two tables. users - all the managers and players. requests - all the requests the managers make to other teams within their club. In the request table i have got this: id player_id - the players that has been requested. fixture_id - the fixture the manager wants to have that player for. accepted - if he has been accepted or not. This comes later on. At the moment i have got it working so that it inserts this data, although the code is working but i want to have a mysql query that checks if a manager has any incoming requests from other teams within the club. BUT only request that has been made to his team.... Could someone please help me out? This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=332358.0 hi i created a page where users can reply to a post and i saved there reply in a table i called comment.when new visitors click on a topic they can see the topic and the people that comment on the topic..Now my problem is this when i click on any topic it display the comment on that topic whch is good but also display comments from other topics wchich is not supposed to be.i have tried joining the tables but i keep getting syntax errors.is joining the comment table to the topics table the solution?? if so can anyone give me the proper way of joining a table but if there is another way kindly tell me.Thanks I have two tables book and category,
book
id title author category isbn 1 fun times Joe 1 16161514 (new record) 2 fishing trip Jim Juvenile Science 88771615 (old record) 3 beach hunt Sam 3 81009991 (new record) 4 day out John 3 81009991 (new record) 5 farm fun Jim Classic Kids 88771615 (old record)category id cat_name 1 horror 2 science 3 kidsI use the join query below to display a list of all book info, works fine. SELECT b.id, b.title, b.category, b.author, b.isbn, b.publicationYear c.cat_name FROM book AS b INNER JOIN category AS c ON b.category = c.idThe problem I am facing is that all some of the books (1000's actually) in the db have been imported from a previous db, and instead of containing an integer for the category they contain a string such as 'General Fiction' or 'Popular Classics' etc. Must I import all of these categories into the 'category' table and assign an integer to them, or is there a way of simply displaying the string that is contained within the 'book' table as it stands? I use the code below to display the html table of results; while($row = $res->fetch_array()) { echo '<tr>'; echo '<td>' . $row['id'] . '</td>'; echo '<td>' . $row['title'] . '</td>'; echo '<td>' . $row['author'] . '</td>'; echo '<td>' . $row['cat_name'] . '</td>'; echo '<td>' . $row['isbn'] . '</td>'; echo '<td>' . $row['publicationYear'] . '</td>'; echo '</tr>'; echo '</tbody>'; }; |