I never did such PHP/MYSQL tricks to join multitables. Please who has experience in this field Help:
$qry=mysql_query("select {$table_prefix}user_cv.*, {$table_prefix}advertising.* from {$table_prefix}user_cv, {$table_prefix}advertising where {$table_prefix}user_cv.publish='yes' and {$table_prefix}advertising.publish='Y'");
mysql query return 0 results .
$qry = "SELECT {$table_prefix}user_cv.*, {$table_prefix}advertising.*
FROM {$table_prefix}user_cv
LEFT JOIN {$table_prefix}advertising ON {$table_prefix}advertising.publish='Y'
WHERE {$table_prefix}user_cv.publish='yes'";
mysql_query($qry);
I did not test this! I could be wrong but it might be a step in the right direction. (Still new myself)
Related
This should be a basic question, but I haven't used Mysql for a very long time and forgot all the basic stuff. So SO programmers please bear with me.
I have 2 tables like this:
Table 1 (events): here
Table 2 (users): here
I would like to select all rows in the events table where event_invitees contains a username. I was able to do this using:
SELECT * FROM meetmeup_events WHERE event_invitees LIKE '%$username%'
Now I'd like to also select the event_invitees's photo from the users table (column called user_userphoto). My attempt to this was this:
$result = mysql_query("SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
WHERE event_invitees LIKE '%$username%'
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter");
$rows = array();
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
This gave me an error: mysql_fetch_assoc(): supplied argument is not a valid MySQL result resource
How can I do this? What am I missing? Can you give me some examples?
Thanks in advance! I'll be sure to accept the working answer!
You should change your mysql functions to either mysqli / PDO, although the problem seems to be the query itsef. Should be:
SELECT meetmeup_events.*, meetmeup_user.user_photo
FROM meetmeup_events
INNER JOIN meetmeup_user
ON meetmeup_user.user_username = meetmeup_events.event_inviter
WHERE event_invitees LIKE '%$username%'
(the WHERE clause at the end)
Sql fiddle demo: http://sqlfiddle.com/#!2/852a2/1
Its just a matter of getting the query coded in the correct order, and you might like to make it a little more managable by using alias's for the table names
Try this :-
SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'
This of course assumes that all the column names are correct and the mu.user_username = me.event_inviter does in fact make sence because those fields are in fact equal
Additional Suggestion
You are not actually issuing the query for execution by mysql.
You have to do this :-
$sql = "SELECT me.*,
mu.user_photo
FROM meetmeup_events me
INNER JOIN meetmeup_user mu ON mu.user_username = me.event_inviter
WHERE me.event_invitees LIKE '%$username%'";
$result = mysql_query($sql);
$rows = array('mysql_count' => mysql_num_rows($result) );
while($r = mysql_fetch_assoc($result)) {
$rows['meetmeup_user'][] = $r;
}
echo json_encode($rows);
Now in your browser using the javascript debugger look at the data that is returned. There should at least be a mysql_count field in it even if there is no 'meetmeup_user' array, and if it is zero you know it found nothing using your criteria.
i have a bit of a problem, ive never used JOIN before, and this is the first time, and i got into some problems:
<?php
//$count to keep the counter go from 0 to new value
$count=0;
//I need to select the level for the users building first, meanwhile i also
//need to get the money_gain from the table buildings, which is a table that
//is common for each member, which means it doesnt have a userid as the other table!
//And then for each of the buildings there will be a $counting
$qu1 = mysql_query("SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user");
while($row = mysql_fetch_assoc($qu1))
{
$count=$count+$row['level'];
echo $row['level'];
}
?>
So basically ive heard that u should tie them together with a common column but, in this case thir isnt any.. im just lost right now?
EDIT Oh right, I need the right level to be taken out with the correct money_gain too, in building_user its 'buildingid'and in buildings, its just 'id'! have no idea how to make a common statement though!
From your edit,
SELECT building_user.level,buildings.money_gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id;
You essentially get the records for the user joining them at the building id
Performance-wise, joins are a better choice but for lightweight queries such as this, the query above should work fine.
You can also give each column a neater name
SELECT building_user.level as level,buildings.money_gain as money gain FROM building_user,buildings WHERE building_user.userid=$user AND building_user.buildingid = building.id;
and access them as
$level = $row['level'];
$gain = $row['gain'];
i think you problem is, that MySQL doesn't know how to JOIN the two Tables. Therefor you have to tell MySQL how to do that.
Example
SELECT * FROM TABLE1 INNER JOIN Table1.col1 ON TABLE2.col2;
where col1 and col2 are the columns to join (a unique identifier)
<?php
$count=0;
$qu1 = mysql_query("SELECT bu.level, bs.money_gain FROM building_user bu, buildings bs WHERE bu.userid=$user");
while($row = mysql_fetch_assoc($qu1))
{
$count=$count+$row['level'];
echo $row['level'];
}
?>
Try this
$qu1 = mysql_query("SELECT building_user.level,buildings.money_gain
FROM building_user
JOIN buildings ON building_user.building_id = buildings.id
WHERE building_user.userid=$user");
building_user.building_id is the foreght key of table building_user and
buildings.id is the primary key of table buildings
I have two tables:
sk_accounts //details of user
acnt_user_id
acnt_fname //first name
acnt_lname
acnt_profile_picture
acnt_member_class
so on........
sk_following //table containing details of users who are following others
id
flwing_follower_id //id of the user who are followed by other followers
flwing_following_user_id
following_date
I want to display details of the follower based on the following Mysql code.Unfortunately it returns zero rows eventhough there are 3 rows.My query is like this:
$query_following = "SELECT sk_following.flwing_following_user_id,
sk_accounts.acnt_fname,
sk_accounts.acnt_lname,
sk_accounts.acnt_member_class,
sk_accounts.acnt_profile_picture
FROM sk_following
INNER JOIN sk_accounts
WHERE sk_following.flwing_follower_id='$id' AND sk_accounts.acnt_user_id=sk_following.flwing_following_user_id AND CONCAT(sk_accounts.acnt_fname,' ',sk_accounts.acnt_lname)='$name'";
$result_following = mysql_query($query_following);
$count_following = mysql_num_rows($result_following);
echo $count_following;
Note:$id and $name contain values
Kindly help me.Thanks in advance.
Try this,
"SELECT sk_following.flwing_following_user_id,
sk_accounts.acnt_fname,
sk_accounts.acnt_lname,
sk_accounts.acnt_member_class,
sk_accounts.acnt_profile_picture
FROM sk_following
LEFT JOIN sk_accounts ON sk_accounts.acnt_user_id=sk_following.flwing_following_user_id
WHERE sk_following.flwing_follower_id='$id'
AND CONCAT(sk_accounts.acnt_fname,' ',sk_accounts.acnt_lname)='$name'";
may this help you.
Hard to completely understand without seeing sample data and desired output, but should your JOIN be on the flwing_follower_id and not the flwing_following_user_id?
SELECT sk_following.flwing_following_user_id,
sk_accounts.acnt_fname,
sk_accounts.acnt_lname,
sk_accounts.acnt_member_class,
sk_accounts.acnt_profile_picture
FROM sk_following
INNER JOIN sk_accounts ON sk_accounts.acnt_user_id=sk_following.flwing_follower_id
WHERE sk_following.flwing_follower_id='$id'
AND CONCAT(sk_accounts.acnt_fname,' ',sk_accounts.acnt_lname)='$name'
Good luck.
I am writing a php site using a mysql database for a class of mine and cannot for the life of me figure out what is wrong with it. I have a query that works locally on my machine (on an identical db to the one on the teacher's server) but when I upload it, it doesn't work. The problem is that the query is returning 0 results even though the db has info in it that should be showing.
function bigAssQuery($whereCondition)
{
$queries[] = 'CREATE TEMPORARY TABLE subAssignments (SELECT ua.assignmentid, ua.assignmentnum, ua.description
FROM Course c JOIN UserAssignment ua ON ua.crn = c.CRN AND ua.term = c.term
WHERE c.CRN = "'.$_SESSION["crnum"].'" AND c.term = "'.$_SESSION["mysem"].'")';
$queries[] = 'CREATE TEMPORARY TABLE subStudents (SELECT s.studentid, s.lastname, s.firstname
FROM Course c JOIN Student s ON s.crn = c.CRN AND s.term = c.term
WHERE c.CRN = "'.$_SESSION["crnum"].'" AND c.term = "'.$_SESSION["mysem"].'")';
$queries[] = 'CREATE TEMPORARY TABLE subRubric(SELECT assignmentid, re.rubricelementid, re.learning_goal_char
FROM RubricElement re JOIN RubricAssignmentRelation rar ON re.rubricelementid = rar.rubricelementid)';
$queries[] = 'CREATE TEMPORARY TABLE subAssignRub(SELECT subAssignments.assignmentid, rubricelementid, learning_goal_char, assignmentnum, description
FROM subRubric JOIN subAssignments ON subAssignments.assignmentid = subRubric.assignmentid)';
$queries[] = 'CREATE TEMPORARY TABLE subAssignRubStud (SELECT *
FROM subAssignRub CROSS JOIN subStudents)';
$queries[] = 'CREATE TEMPORARY TABLE subAssignInstRubStud (SELECT sars.assignmentid, ai.ainstanceid, rubricelementid, learning_goal_char, assignmentnum, description, sars.studentid, lastname, firstname
FROM subAssignRubStud sars LEFT JOIN AssignmentInstance ai ON sars.studentid = ai.studentid AND sars.assignmentid = ai.assignmentid)';
$queries[] = 'CREATE TEMPORARY TABLE subTotal (SELECT assignmentid, siars.ainstanceid, s.ainstanceid As scoreAID, siars.rubricelementid, learning_goal_char, assignmentnum, description, studentid, lastname, firstname, score
FROM subAssignInstRubStud siars LEFT JOIN Score s ON siars.ainstanceid = s.ainstanceid AND siars.rubricelementid = s.rubricelementid
ORDER BY lastname, assignmentid)';
$queries[] = 'SELECT *
FROM subTotal
'.$whereCondition.' Order By lastname, assignmentnum, learning_goal_char';
return($queries);
}
Then when the db is queried the code looks like this. . .
$queries = bigAssQuery($whereCondition);
$result = 1;
foreach($queries as $query)
{
$result = $db->query($query);
if(!$result)
{
echo '<script type="text/javascript">
window.onload=function(){ alert("Error: Could not extract course information. Please try again later."); }
</script> ';
exit;
}
}
$num_rows = $result->num_rows;
I assure you that the local and remote databases are identical. I see no reason why no results are coming back. I did test a few simple temp tables to see if the server wasn't reading those tables for some reason, but they weren't an issue in my tests. I would try with nested subqueries, but it gets so convoluted so quickly that I can't organize it. Maybe there is a better way?
Also, just to clarify the queries aren't failing, they just aren't returning anything when I know that they should.
I apologize for the wall of text, but any help is appreciated.
EDIT: I really don't know which of the queries the problem lies. I do know that I'm probably missing some important information. Part of that lies in my web inexperience. I test locally first because I've got the debugger working, but I honestly don't know how to do remote debugging. I'm using netbeans and xdebug. If someone could suggest a how to get remote debugging set up I would probably be able to come up with some better data. Any suggestions would be helpful
EDIT AGAIN: Found the problem. Embarrassingly enough it was an error in data entry; one of my foreign keys was incorrectly entered. Thanks everybody for pointing me in the right direction.
On having a quick look, your code is stoping the execution of the PHP inappropriately. You should at least the let the remainder to continue. Simply exit out of loop using break; instead.
if(!$result)
{
echo '<script type="text/javascript">
window.onload=function(){ alert("Error: Could not extract course information. Please try again later."); }
</script> ';
break; //exit the loop only NOT THE PHP's Execution
}
Furthermore, check every query individually and run them separately on phpMyAdmin to see, if they are executing correctly. Find the break point and fix the error.
In my application i have three tables, reservation, patient and sub_unit, i need to take the patient_id from reservation table and query the patient table for patient data,same time i need to take the sub_unit_id from the reservation table and query the sub_unit name from the sub_unit table... i need to put all this data in to an one array in the sequence like
patient_id, sub_unit_name, patient_name, address and pass it to the Codeigniter table class to draw a table.
How can I query three tables in the same time to query out this data? can you guys help me out?
Using code igniter syntax it can be done as follows -
$this->db->select('r.patient_id, s.sub_unit_name, p.patient_name, p.address');
$this->db->from('reservation r');
$this->db->join('patient p', 'p.id = r.patient_id');
$this->db->join('sub_unit s', 's.id = r.sub_unit_id');
$query = $this->db->get();
You can check your formed query by -
echo $this->db->_compile_select();exit;
Select r.patient_id, s.sub_unit_name, p.patient_name, p.address
from reservation r, sub_unit s, patient p
where r.patient_id = p.patient_id and r.sub_unit_id = s.sub_unit_id
The join syntax is very straightforward in SQL. You are probably looking for something like this:
SELECT reservation.patient_id,
sub_unit.sub_unit_name,
patient.patient_name,
patient.address
FROM reservation
JOIN patient ON (patient.id = reservation.patient_id)
JOIN sub_unit ON (sub_unit.id = reservation.sub_unit_id);
In MySQL, the default join is an Inner Join, which I think is what you're looking for. You may also want to look into Outer Joins which are also very useful.
it worked guys , i did it like this using Codeigniter active records ,hope you guys can use it too
function get_data(){
$sql = 'SELECT * FROM visit,patient,sub_unit WHERE visit.patient_patient_id = patient.patient_id AND visit.sub_unit_sub_unit_id = sub_unit.sub_unit_id';
$this->db->order_by("reference_number", "desc");
$query = $this->db->query($sql);
return $query;
}
thanx for all your support!