I have a coupon code site. I'm creating a "Black Friday" coupons and deals page.
In the sidebar I want the user to be able to see all the categories of coupons we have (apparel,shoes,electronics,etc.) and how many Black Friday coupons we have for each category.
I'm pulling in all the categories from the table "tblCategories", but what I'm having issues with is getting a count from the relational table "tblCouponsCategories" of how many coupons are in the "Black Friday" category, plus whatever other category I'm looking for. The categoryid from Black Friday is '24'. This is the code I have so far:
$result = mysql_query("SELECT name,fmtc_categoryid,categoryid FROM tblCategories ORDER BY name") or die(mysql_error());
while($row = mysql_fetch_array( $result )) {
$fmtc_categoryid=$row['fmtc_categoryid'];
$categoryid=$row['categoryid'];
$name=$row['name'];
$result2 = mysql_query("SELECT couponid FROM tblCouponsCategories WHERE categoryid='24' AND categoryid='$categoryid'") or die(mysql_error());
$count_coupons = mysql_num_rows($result2);
echo "<li><a href='http://www.mydomain.com/coupons/$fmtc_categoryid' title='View $name Coupon Codes'>$name ($count_coupons)</a></li>";
}
Here is what my relational table tblCouponsCategories is formatted like for a coupon that is both in the "Black Friday" category plus another category:
id couponid categoryid
83995 48312 5
83996 48312 9
83997 48312 14
83998 48312 11
83999 48312 24
84000 48312 38
I tink you have some mistake here:
SELECT couponid FROM tblCouponsCategories WHERE categoryid='24' AND categoryid='$categoryid' GROUP BY categoryid") or die(mysql_error());
//should be
SELECT couponid FROM tblCouponsCategories WHERE categoryid='24' GROUP BY categoryid") or die(mysql_error());
Related
I have a database set up:
and the resulting table:
I am trying to retrieve data from the database so that the output displays the players according to who has the highest score in descending order. However, I get the following output:
Pollywinkle Anderson has a high score of 600 recorded in the database yet only her score of 200 is shown. How can I retrieve each players highest score? The score is stored as VARCHAR and I read in solutions to similar questions that it needs to be converted to an INT. I have tried to do that but it's still not working. I am very new to programming in general, any help would be appreciated. My code is below. Thank you.
<?php
$sql = "SELECT * , COUNT(*) AS `phone` FROM `players` GROUP BY
CONCAT(`fname`, `surname`) ORDER BY MAX(CONVERT(`score`,INT)) DESC";
$result = mysqli_query($conn,$sql)or die(mysqli_error());
echo "<table>";
echo "<tr><th>Firstname</th><th>Surname</th><th>Email</th><th>Score</th>
<th>Number of Submissions</th></tr>";
while($row = mysqli_fetch_array($result)) {
$fname = $row['fname'];
$surname = $row['surname'];
$email = $row['email'];
$score = $row['score'];
$phone = $row['phone'];
echo "<tr><td style='width: 200px;'>".$fname."</td><td style='width:
200px;'>".$surname."</td><td style='width: 200px;'>".$email."</td><td
style='width: 200px;'>".$score."</td><td style='width: 200px;'>".$phone."
";
}
echo "</table>";
mysqli_close($conn);
?>
You can try below:
SELECT fname,surname,MAX(CONVERT(`score`,INT)) as score, COUNT(*) AS `submission`
FROM `players`
GROUP BY fname,surname
ORDER BY score desc
If you want to list your players ordered by their score you don't need a count or to group by anything. All you need to do is a simple select query with an order by, like:
select * from players order by score
I have 3 tables, members, teams & team_members.
team_members houses the ids from both the members & teams and stores them per row.
The schema of theteam_members table:
teams table:
What I'd like to be able to do is create a join where i can output the team_name from the teams table and then underneth show the members_firstname associated with that that team. So example:
Team 1
joe bloggs
jon doe
Team 2
charlie chaplin
hulk hogan
My php code looks like this:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$sql = "SELECT t.team_name, group_concat(m.firstName)
FROM members AS m
JOIN team_members AS tm
ON tm.member_id = m.member_id
JOIN teams as t
on t.team_id = tm.team_id
GROUP BY t.teamname";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo $row["member_id"] . '<br>';
echo $row["team_id"] . '<br><br>';
}
}
?>
Now I get:
Notice: Trying to get property of non-object in -- on line 30 which is:
if($result->num_rows > 0){
You should use two joins to piece together the three tables.
SELECT t.team_name as team_name, group_concat(m.firstName) as team_members
FROM members AS m
JOIN team_members AS tm
ON tm.member_id = m.member_id
JOIN teams as t
on t.team_id = tm.team_id
GROUP BY t.team_name
You then should check the status of your query before trying to work with it.
if(!$result = $conn->query($sql)) {
die(printf("Errormessage: %s\n", $conn->error));
}
Then loop through the results, and split the grouped values by the comma.
while($row = $result->fetch_assoc()){
echo $row["team_name"] . '<br>';
$names = explode(',', $row['team_members']);
foreach($names as $name) {
echo $name . '<br>';
}
echo '<br>';
}
You also could use <br> as the separator in the group_concat. You can read more about that function here, http://dev.mysql.com/doc/refman/5.7/en/group-by-functions.html#function_group-concat. If you did that you can get rid of the foreach and explode because the $row['team_members'] would be built with a linebreak for each member.
The easy way to do this in PHP is width two nested loops in first you go trought the team table and print it in the second you print all the playes width theat team id...
Something like:
do{
echo $row_team;
do{
echo $row_playa;
}while($row_plya = mysql_fetch_assoc($playas)); // whear pleya.team_id = $row_team.id
}while($row_team = mysql_fetch_assoc($teams));
I have a table deals, and columns are name, amount, division, category.
For each division category combination, I want to find top 3 entries with max amount.
The final result should be in the format: name, division, category.
$db = new PDO($hostname,$username,$password);
$query = 'Select name, division, category
From deals Where division = :division And category = :category
ORDER BY amount DESC Limit 3';
then create arrays of all your divisions and categories and loop them:
$top3s = array();
foreach($divisionArray as $division)
{
foreach($categoryArray as $category)
{
$statement = $db->prepare($query);
$statement->bindValue(':division', $division);
$statement->bindValue(':category', $category);
$statement->execute();
$top3 = $statement->fetch(PDO::FETCH_ASSOC);
$statement->closeCursor();
array_push($top3s, $top3);
}
}
print_r $top3s;
I have the following table as an example.
id uid car
1 3 BMW
2 3 AUDI
3 3 JEEP
4 5 MERC
5 6 BMW
6 6 FIAT
Now, I would like to get all cars but for only 2 users but don't know how many cars they have. When they all would have had only one car, I could just do a LIMIT 3 but how can I do this to get all the cars, but only for 2 users?
EDIT
If the 2 users are unknown you can use MySQL GROUP_CONCAT
$query = mysql_query("SELECT uid, GROUP_CONCAT(car) as cars FROM tablename GROUP BY uid ORDER BY uid ASC LIMIT 0,2");
while ($get = mysql_fetch_array($query)) {
$userid = $get['uid'];
$result = explode(",", $get['cars']);
echo '<h2>User #' . $userid . ' owns the following cars:</h2>' . "\n";
echo '<ul>' . "\n";
foreach ($result as $car) {
echo ' <li>' . $car . '</li>' . "\n";
}
echo '</ul>' . "\n";
}
Note: Don't forget to change the tablename in the SELECT query
i need to take only the items from the table "__sobi2_item" that are in the same country of the user.And use this results for the rest of the function Showupdatelisting. This is my php script:
<?php
function showUpdatedListing()
{
//i found the user country field value...
global $database;
$user =& JFactory::getUser();
$userId = $user->get( 'id' );
$sql = "SELECT (id) FROM #__community_fields WHERE fieldcode= 'FIELD_COUNTRY'";
$database->setQuery( $sql );
$fieldID = $database->loadResult();
$sql = "SELECT (value) FROM #__community_fields_values WHERE field_id= {$fieldID} && user_id= {$userId}";
$database->setQuery( $sql );
$usercountry = $database->loadResult();
// From all the entries i take only ones that have country field like the user has...
$query = "SELECT `data_txt`, `itemid`, `fieldid` FROM `#__sobi2_fields_data` WHERE (`fieldid` = 6) AND ('data_txt' = {$usercountry})";
$database->setQuery($query);
$ResultsArray = $database->loadObjectList();
// We need something here like a Query to load only the entries from $ResultsArray... ??
//....instead of this...
$config =& sobi2Config::getInstance();
$database = $config->getDb();
$now = $config->getTimeAndDate();
$query = "SELECT itemid FROM #__sobi2_item WHERE (published = 1 AND publish_down > '{$now}' OR publish_down = '{$config->nullDate}') ORDER BY last_update DESC LIMIT 0, 30";
$database->setQuery($query);
$sids = $database->loadResultArray();
// ......... show update function goes on...
?>
can anyone help me to connect and adjust these query? thanks.
NB:with the last query (4) i need to filter items of the $ResultsArray taking only ones published and ordering them by last_update. i know it is wrong and now there is no connection with the query before. This is how i have tables in mysql:
_sobi2_fields_data:
itemid
fieldid
data_txt --->(is a description column for each field)
_sobi2_item:
itemid
published --->( 1 if true, 0 if false )
last_update --->(date of the last update for the item, also equal to the publication date if there are no changes)
thanks.
I don't know what you are trying to ask as well. Your last query (number 4) doesn't make sense to me, how is it linked to the above queries?
[EDIT] I've linked your 4th table above assuming itemid is the primary key for the items in sobi2_item table and that the value is linked to the sobi_fields_data table via itemid.
SELECT
cf.id,
sfd.data_txt,
sfd.itemid,
sfd.fieldid
FROM #__community_fields cf
INNER JOIN #__community_fields_values cfv ON cf.id=cfv.field_id
INNER JOIN #__sobi2_fields_data sfd ON cfv.value=sfd.data_txt
INNER JOIN #__sobi2_item si ON sfd.itemid=si.itemid
WHERE cf.fieldcode='FIELD_COUNTRY'
AND cfv.user_id=$userId
AND sfd.fieldid=6
AND si.published=1
AND (si.publish_down > '{$now}' OR si.publish_down = '{$config->nullDate}')
ORDER BY si.last_update DESC LIMIT 0, 30
Good luck!