PHP - Inner Join Problem?
I am somewhat of a newbie and think this is a simple fix, but I have been having problems and can't seem to figure it out. I am trying to JOIN two tables, but am not getting the results I would like. I am getting the correct question number displayed whenever I try different instances, but it always defaults to the "DTCAP" question (q_code).
I have included the snippet of code and how the table structure looks. Any help would be greatly appreciated!
-------------------------------------------------------------------------------------
//Testing to ensure that the $_SESSION['code'] is DTCAP, CNROW, or MONFW after user chooses option
echo $_SESSION['code'];
$query_question=mysql_query("SELECT * FROM adventure_questions q
INNER JOIN users_adventures u ON q.q_number = u.ua_question WHERE u.ua_username = '$_SESSION[username]' AND u.ua_code='$_SESSION[code=auto:0]'"); $question_info=mysql_fetch_array($query_question); echo $question_info['q_number'].". ".$question_info['question']; ------------------------------------------------------------------------------------- adventure_questions q_id q_code q_number question 1 DTCAP 1 DTCAP question 1 2 DTCAP 2 DTCAP question 2 26 CNROW 1 CNROW question 1 27 CNROW 2 CNROW question 2 51 MONFW 1 MONFW question 1 52 MONFW 2 MONFW question 2 users_adventures ua_id ua_username ua_code ua_question ua_score 1 kjb31ca DTCAP 1 0 2 kjb31ca CNROW 2 10 3 kjb31ca MONFW 1 0 Edited by KjB31ca, 20 May 2014 - 06:39 AM. Similar TutorialsHello guys. Thanks a lot for any help with this.
My problem is that I'm trying to use MAX to get the last item in the portafolio table. This is my query:
$result = $db->prepare( "SELECT * FROM portafolio INNER JOIN imagenes ON imagenes.work = portafolio.idp WHERE work = ? ORDER BY iid DESC); $result->execute(array($_GET['work']));The main idea is not use $_GET['work'], because i want to display the last work (with their respective images) in my portafolio in the main page, so im not passing any variable by url. This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=313310.0 SELECT 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=306058.0 I have the following PHP code... $query1 = $this->db->query("SELECT `categories`.`cat_id`, `categories`.`cat_name`, `forums`.`forum_name` FROM `".$this->dbname."`.`categories` LEFT JOIN `".$this->dbname."`.`forums` USING (`cat_id`) ORDER BY `categories`.`cat_order` ASC"); $i = 0; while($row = $this->db->fetch_assoc($query1)) { $content .= ($i % 2 == 0 ? '<tr class="odd">' : '<tr>'); $content .= '<td><p><a href="index.php?cg=cgs&page=forum&do=forums:'.$row['cat_id'].'">'.$row['cat_name'].'</a></p>'; $content .= ' - '.$row['forum_name'].'</td>'; $content .= '</tr>'; $i++; } I'm getting duplicate rows of the first table (categories) being outputted. So I'm currently getting... Quote Crikey Games - Suggestions and Ideas Crikey Games - General Discussion Crikey Games - Announcements Realm Battles - Bugs, Glitches and Exploits Realm Battles - Recruiting Realm Battles - General Discussion Realm Battles - Suggestions and Ideas Realm Battles - Battle Grounds Realm Battles - Announcements When I want to be getting... Quote Crikey Games - Suggestions and Ideas - General Discussion - Announcements Realm Battles - Bugs, Glitches and Exploits - Recruiting - General Discussion - Suggestions and Ideas - Battle Grounds - Announcements Code: [Select] -- -- Table structure for table `categories` -- CREATE TABLE IF NOT EXISTS `categories` ( `cat_id` int(10) NOT NULL AUTO_INCREMENT, `cat_name` varchar(50) NOT NULL, `cat_order` int(5) NOT NULL DEFAULT '0', PRIMARY KEY (`cat_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ; -- -- Dumping data for table `categories` -- INSERT INTO `categories` (`cat_id`, `cat_name`, `cat_order`) VALUES (1, 'Crikey Games', 1), (2, 'Realm Battles', 2); -- -------------------------------------------------------- -- -- Table structure for table `forums` -- CREATE TABLE IF NOT EXISTS `forums` ( `forum_id` int(10) NOT NULL AUTO_INCREMENT, `cat_id` int(10) NOT NULL, `forum_name` varchar(50) NOT NULL, `forum_description` varchar(225) NOT NULL, `forum_order` int(5) NOT NULL DEFAULT '0', `forum_locked` tinyint(1) NOT NULL DEFAULT '0', PRIMARY KEY (`forum_id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=10 ; -- -- Dumping data for table `forums` -- INSERT INTO `forums` (`forum_id`, `cat_id`, `forum_name`, `forum_description`, `forum_order`, `forum_locked`) VALUES (1, 1, 'General Discussion', 'talk about anything you like', 2, 0), (2, 1, 'Announcements', '', 1, 0), (3, 1, 'Suggestions and Ideas', 'if you have a suggestion or idea, share it here', 3, 0), (4, 2, 'Announcements', '', 4, 0), (5, 2, 'General Discussion', 'talk about anything Realm Battles related here', 5, 0), (6, 2, 'Battle Grounds', '', 6, 0), (7, 2, 'Recruiting', '', 7, 0), (8, 2, 'Suggestions and Ideas', 'if you have a suggestion or idea for Realm Battles, share it here', 8, 0), (9, 2, 'Bugs, Glitches and Exploits', 'if you have discovered something that needs to be fixed, share it here', 9, 0); Not sure whether I'm doing something wrong with the PHP side of things, or the MySQL query. Also I can't figure out how to ORDER BY `forums`.`forum_order` ASC , when trying to add it to this query. Thanks in advance, Ace This topic has been moved to MySQL Help. http://www.phpfreaks.com/forums/index.php?topic=308855.0 hirealimo.com.au/code1.php this works as i want it: Quote SELECT * FROM price INNER JOIN vehicle USING (vehicleID) WHERE vehicle.passengers >= 1 AND price.townID = 1 AND price.eventID = 1 but apparelty selecting * is not a good thing???? but if I do this: Quote SELECT priceID, price FROM price INNER JOIN vehicle....etc it works but i lose the info from the vehicle table. but how do i make this work: Quote SELECT priceID, price, type, description, passengers FROM price INNER JOIN vehicle....etc so that i am specifiying which colums from which tables to query?? 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? 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=# 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 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 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"; 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 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 " SELECT event.*, epr1.participantId AS team_1, epr1.participantRoleId AS team_1_role, epr2.participantId AS team_2, epr2.participantRoleId AS team_2_role FROM bb_EventParticipantRelation epr1, bb_EventParticipantRelation epr2, bb_Event event WHERE event.parentId='".$leage_type."' AND epr1.id != epr2.id AND epr1.parentParticipantId = '0' AND epr2.parentParticipantId = '0' AND epr1.eventId=event.id AND epr2.eventId=event.id ORDER BY epr1.participantRoleId ASC, event.startTime, team_1, team_2 ASC " This sql gets 2 rows and combines them as one, it does work but the issue is it seems to be taking too long in loading the page also I just need some advice on a better version Thank you When I have more than one table i don't know how to echo out a field if it is the same in both fields. here's my code and I want to echo out the id from the people table: $query = "SELECT * FROM people INNER JOIN ratings ON people.id = ratings.rater_id AND ratings.event_id = '$eventid' AND ratings.complete = 'n' "; $result = mysql_query($query); while ($row=mysql_fetch_assoc($result)){ echo $row['people.id']; } I tried $row['people.id'] but it was blank. 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! 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 a database with two tables, they are designed like this Table1 has two fields (log_number, name) Table2 has two fields (log_number, city) I would like to do a search for a specific log number and display only one result for that matching log number (that we searched for) and display something like this Log Number: 59 Name: Mark City: Chicago this is my code so far my search form Code: [Select] <form method="get" action="search.php" /> Log Number <input type="text" id="log_number" name="log_number" /> <input type="submit" name="submit" value="Search" /> the search.php file Code: [Select] <?php require ('/sqlconnect.php'); $dbc = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME); $log_number = $_GET['log_number']; $name = $_GET['name']; $city = $_GET['city']; $query = "SELECT * FROM table1, table2 WHERE table1.log_number = table2.log_number"; $result = mysqli_query ($dbc, $query); while ($row = mysqli_fetch_array($result)) { echo '<b>Log Number:</b> '.$row['log_number'].'</td>'; echo '<br/>'; echo '<b>Name:</b> '.$row['name'].'</td>'; echo '<br/>'; echo '<b>City:</b> '.$row['city'].'</td>'; } mysqli_close($dbc); ?> the problem I am having with my current code is that it does not display the results of the log number i searched for, but instead returns information for all the entries (two in my case) that have matching log numbers in both table1 and table2 when i search for log number 59, i get the following result Log Number: 59 Name: Mark City: Chicago Log Number: 77 Transport Company: Doug Customer Number: San Francisco the result that I want is when i search for log number 59 ... i want it to only display that one record Log Number: 59 Name: Mark City: Chicago hope someone can help |