I am trying to make a members page. For the rank it shows numbers so I made another table that has the rank id (1,2,3 etc) and added a name to it also.
Here is my code.
<?php
$getCoB = mysql_query("SELECT * FROM `members`
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY `id`");
$id = ($getCoB['rank']);
$rankInfo = mysql_query("SELECT * FROM `ranks` WHERE `id` = '".$id."'");?>
<h2 class="title">Council of Balance members</h2>
<style>tr:nth-of-type(odd) { background-color:#F0F0F0;}</style>
<div style='padding:5px;'>
<?php
if(mysql_num_rows($getCoB) == 0)
{
echo "There are no Council of Balance members.";
} else {
echo "<table cellpadding=20 width=100%>";
while($row = mysql_fetch_assoc($getCoB))
{
echo "<tr><td style='background-color:transparent;'><b>". $row['name']
. "</b></td><td>Rank: ".$rankInfo['name']." <br/> Role: ". $row['role']."</td>";
}
echo "</table>";
}
?>
The problem is rankInfo['name'] is not showing up. I tried to do something on this line while($row = mysql_fetch_assoc($getCoB)) and tried to make it something like this while($row = mysql_fetch_assoc($getCoB)) || while($rank = mysql_fetch_assoc($rankInfo) and changed this part <td>Rank: ". $rankInfo['name'] . " to this <td>Rank: ". $rank['name'] . " but I end up with an error. If I leave it like it is, it just shows Rank: without the name I added into my database.
You can combine your two queries into one using an inner join.
<?php
$getCoB = mysql_query("SELECT m.name as member_name, m.role, r.name as rank_name
FROM `members` as m INNER JOIN `ranks` as r ON m.rank = r.id
WHERE `CoB` = '1' && `user_state` = '1' ORDER BY m.id");
?>
Because of how INNER JOIN works, this will only display members who have corresponding records in the ranks table. If there are some members that you want to display that have no rank record, use LEFT JOIN instead.
Then when you echo out the data, be sure to refer to the item you have fetched ($row) each time. In your code, you are referring to $rankInfo['name'], where $rankInfo is not a variable, but a mysql query from which no rows have been fetched.
while($row = mysql_fetch_assoc($getCoB)) {
echo "<tr><td style='background-color:transparent;'><b>". $row['member_name']
. "</b></td><td>Rank: ". $row['rank_name'] . " <br/> Role: " . $row['role'] . "</td>";
}
Related
I am new to PHP and I just cannot figure out my code. I am using MySQL and PHP.
table: person
PK: personID
Other fields: lastName, firstName, hireDate, imgName
table: validMajors
PK: majorAbbrev
Other Fields: majorDesc
(Junction) table: personMajors
personID, majorAbbrev
When I run my code (using NATURAL JOIN) it will display the image, last&first name, and hire date. Which is great! But I need it to display their majors as well (I would like the majorAbbrev to be displayed). It also does not display people who are in the person table but are not in the personMajors table, which is an issue because we have staff members in the person table (who do not have a major since they are not a student)
Here is my code:
<table align="center">
<?php
$connection = mysqli_connect(DBHOST, DBUSER, DBPASS, DBNAME);
if ( mysqli_connect_errno() ) {
die( mysqli_connect_error() );
}
$sql = "SELECT * FROM person NATURAL JOIN personMajors ORDER BY lastName";
if ($result = mysqli_query($connection, $sql)) {
// loop through the data
$columns=4;
$i = 0;
while($row = mysqli_fetch_assoc($result))
{
if($i % $columns ==0){
echo "<tr>";
}
echo "<td class='staffImage badgeText frameImage displayInLine'>" . "<img src='images/staff/".$row['imgName'].".jpg'>". "<br>".
"<strong>" . $row['firstName'] . "</strong>" ." ".
"<strong>" . $row['lastName'] . "</strong>" . "<br>" .
"Hire Date: ".$row['hireDate'] ."</td>";
"Major: " .$row['majorAbbrev'] ."</td>"; //Does not display
if($i % $columns == ($columns - 1)){
echo "</tr>";
}
$i++;
}
// release the memory used by the result set
mysqli_free_result($result);
}
// close the database connection
mysqli_close($connection);
?>
</table>
Any ideas/solution will be greatly appreciated!
Because you are not concatenating your php properly. You ended (;) your echo after displaying the $row["lastName"].
You can try these to join the three tables:
SELECT * FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Or you can define what columns to call in your query:
SELECT person.personID,
person.lastName,
person.firstName,
person.hireDate,
person.imgName,
validMajors.majorAbbrev,
validMajors.majorDesc
FROM person
LEFT JOIN personMajors ON person.personID = personMajors.personID
LEFT JOIN validMajors ON personMajors.majorAbbrev = validMajors.majorAbbrev
Then you can call the results with the way you are calling it right now (cleaner version):
echo '<td class="staffImage badgeText frameImage displayInLine">
<img src="images/staff/'.$row["imgName"].'.jpg"><br>
<strong>'.$row["firstName"].'</strong>
<strong>'.$row["lastName"].'</strong><br>
Hire Date: '.$row["hireDate"].'
Major: '.$row["majorAbbrev"].'
</td>';
(Second try): Is the person to major relationship one to one or one to many?
OK, this SELECT Statement should work:
SELECT person.*, validMajors.* FROM person AS p, validMajors AS vm, personMajors AS pm WHERE p.personID = pm.personID AND pm.majorAbbrev = vm.majorAbbrev
I am trying to print out a users name and totalspent value in ascending order of totalspent. I.e, user that has spent the most will be outputed first then the next highest spender etc.
This is my current code, however, this only seems to output a single table row an infinite amount of times.
$query = "SELECT * FROM (
SELECT * FROM `members` ORDER BY `totalspent` DESC LIMIT 10) tmp order by tmp.totalspent asc";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
select member_name, totalspent from tmp order by totalspent desc;
still can you show snippet of your table and snippet of answer you desire
The best way I can prefer for you to join two tables. The code should like follows-
$query = "SELECT * FROM temp.tmp, mem.members WHERE temp.totalspend = mem.totalspend ORDER by temp.totalspend ASC";
$result = $mysqli->query($query);
while ($row = $result->fetch_assoc()) {
echo $row['name'] . " - $" . $row['totalspent'] . "<br/>";
}
I believe, it will work for your smoothly... TQ
I have a left join, code shown below that takes,
id
referrer
search term
client_id
From table 1 and then takes the following columns from table 2 using the left join query underneath.
client_id
visit_id
timedate
url1
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){ ?>
<div id=''>
<?php "<br />";
echo $row['referrer']. " - ". $row['search_term'];
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo "<br />"; ?>
</div>
<?php
}
What I am trying to do is format the rows so the referrer and search term only shows once and not on every line so that the results would look like this.
Referrer Search term
timedate url1 1
timedate Url1 1
timedate url1 1
referrer Search Term
timedate Url1 2
timedate Url1 2
timedate Url1 2
the numbers 1 and 2 are to represent different visit id's by which the results are grouped. At the moment i get the referrer and search term after every row because it is in the loop and understand that. Just don't know if i can show the referrer and searc term just once per group of results.
You have to save the current pending referrer-searchterm combination and check if it changes, if yes, print out the referrer-searchterm line:
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate" .
"ORDER BY referrer, search_term";
$result = mysql_query($query) or die(mysql_error());
$currentReferrerSeatchTerm = null;
while($row = mysql_fetch_array($result)){
$newReferrerSearchTerm = $row['referrer']. " - ". $row['search_term'];
echo '<div id=""><br>';
if($currentReferrerSeatchTerm != $newReferrerSearchTerm){
echo $newReferrerSearchTerm . '<br>';
$currentReferrerSeatchTerm = $newReferrerSearchTerm
}
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo '<br></div>';
}
I usually set a var to store the referrer then check that on each loop through. If it's the same as the previous, do nothing. If it's different, display the new header info (referrer & search_term in your case) and then update the var.
$query = "SELECT table1.id, table1.search_term, table1.referrer, table1.client_id, table2.client_id, table2.url1, table2.visit_id, table2.timedate ".
"FROM table1 LEFT JOIN table2 "
"ON table1.id = table2.visit_id WHERE table1.ip_address = '$ip_address' AND table1.client_id='$client_id' Group BY visit_id, timedate";
$result = mysql_query($query) or die(mysql_error());
$prevRef = '';
while($row = mysql_fetch_array($result)){ ?>
<div id=''>
<?php "<br />";
if($prevRef != $row['referrer']) {
echo $row['referrer']. " - ". $row['search_term'];
$prevRef = $row['referrer'];
}
echo $row['timedate']. " - ". $row['url1']. " - ". $row['visit_id'];
echo "<br />"; ?>
</div>
<?php
}
I have a inner join statment which is working 90% as it is displaying what I need it to display but unfortunately it is not displaying to the right user logged in. It is being displayed to whoever logs into my system. Here is the code:
<?php
$result = mysql_query("SELECT * FROM Agendas INNER JOIN Meetings ON Meetings.secretary WHERE Agendas.approval = 'disapproved' AND secretary = '". $_SESSION['username']."'")
or die(mysql_error()); ;
if (mysql_num_rows($result) == 0) {
echo 'You Have No New Messages';
} else {
while($info = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td><br/>" .'Title: '. $info['title']." </td>";
echo "<td><br/>" .'Approved: '. $info['approval']. "</td>";
echo "<td><br/>" .'Reason: '. $info['reason']."</td>";
echo "<hr>";
}
}
echo "</tr>";
echo "</table>";
?>
my database tables look like this:
Meetings: meeting_id, title, chairperson, secretary, tof, occurances, action
Agendas: agenda_id, subject, duration, meeting_id, approval, reason.
thanks soo much for any help :)
i think you're doing something wrong in the join clause. how about this:
$result = mysql_query("SELECT * FROM Agendas INNER JOIN Meetings ON Agendas.meeting_id = Meetings.meeting_id WHERE Agendas.approval = 'disapproved' AND secretary = '". $_SESSION['username']."'")
or die(mysql_error());
I have a MySQL database called "bookfeather" with several tables that contain list books. Under each table, each book has a given number of votes. The PHP code below allows the user to enter in a book title ($entry), and then returns the total number of votes that book has in all tables ($sum).
How could I use PHP to make a 2-column, 25-row table that lists the 25 books in the database with the highest value for $sum (in descending order)?
Thanks in advance,
John
mysql_connect("mysqlv10", "username", "password") or die(mysql_error());
mysql_select_db("bookfeather") or die(mysql_error());
// We preform a bit of filtering
$entry = strip_tags($entry);
$entry = trim ($entry);
$entry = mysql_real_escape_string($entry);
$result = mysql_query("SHOW TABLES FROM bookfeather")
or die(mysql_error());
$table_list = array();
while(list($table)= mysql_fetch_row($result))
{
$sqlA = "SELECT COUNT(*) FROM `$table` WHERE `site` LIKE '$entry'";
$resA = mysql_query($sqlA) or die("$sqlA:".mysql_error());
list($isThere) = mysql_fetch_row($resA);
$isThere = intval($isThere);
if ($isThere)
{
$table_list[] = $table;
}
}
//$r=mysql_query("SELECT * , votes_up - votes_down AS effective_vote FROM `$table[0]` ORDER BY effective_vote DESC");
if(mysql_num_rows($resA)>0){
foreach ($table_list as $table) {
$sql = "SELECT votes_up FROM `$table` WHERE `site` LIKE '$entry'";
$sql1 = mysql_query($sql) or die("$sql:".mysql_error());
while ($row = mysql_fetch_assoc($sql1)) {
$votes[$table] = $row['votes_up'];
$sum += $row['votes_up'];
//echo $table . ': "' . $row['votes_up'] . " for $entry from $table\"<br />";
}
}
}
else{
print "<p class=\"topic2\">the book \"$entry\" has not been added to any category</p>\n";
}
//within your loop over the DB rows
//$votes[$table] = $row['votes_up'];
//afterwards
if($sum>0){
print "<table class=\"navbarb\">\n";
print "<tr>";
print "<td class='sitenameb'>".'<a type="amzn" category="books" class="links2b">'.$entry.'</a>'."</td>";
print "</tr>\n";
print "</table>\n";
//echo "<p class=\"topic3\">".''.$entry.''. "</p>\n";
echo "<p class=\"topic4\">". number_format($sum) . ' votes in total.'."</p>\n";
Try something like this. All of this hasn't been tested so please add comments for changes. I'll work with you to get the code right.
// After getting your array of tables formated like
$tableArray = array("`tableA`", "`tableB`", "`tableC`");
// create a table statement
$tableStatement = implode(", ", $tableArray);
// create a join statement
$joinStatement = "";
for ($i = 1; $i < count($tableArray); $i++) {
if ($joinStatement != "")
$joinStatement .= " AND ";
$joinStatement .= $tableArray[0] . ".site = " . $tableArray[$i] . ".site"
}
$firstTable = $tableArray[0];
$sql = "SELECT SUM(votes_up) FROM " . $tableStatement . " WHERE " . $joinStatement . " AND " . $firstTable . ".site LIKE '" . $entry . "' GROUP BY " . $firstTable . ".site ORDER BY SUM(votes_up) DESC";
Edit --------
I now realize that the query above won't work perfectly because votes_up will be ambiguous. Also because you probably want to be doing joins that grab records that are only in one table. I think the concept is the right direction even though the query may not be perfect.
You can do something like
$selectStatement = "SUM(tableA.votes_up) + SUM(tableB.votes_up) as total_votes_up"
I did something like this recently. In your database, you'll have to rename each field to a corresponding book name.php like (TaleofTwoCities.php). Now on your page that will display the vote results, you'll need to include some php files that will drive the database query on each load. I called mine "engine1.php" and "engine2.php." These will do all your sorting for you.
$query1 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 0,1"));
$query2 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 1,1"));
$query3 = mysql_fetch_row(mysql_query("SELECT url FROM pages ORDER BY counter DESC
LIMIT 2,1"));
and so on.. then..
$num1 = "$query1[0]";
$num2 = "$query2[0]";
$num3 = "$query3[0]";
That part sorts your listings by the number of votes from highest to lowest, with url, in your case, being the name of the books(remember you want it to end in .php - you'll see why in a second), and counter being the field that logs your votes.
Make your second engine.php file and add something like this:
$vquery1 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book1.php'"));
$vquery2 = mysql_fetch_row(mysql_query("SELECT counter FROM pages WHERE
url='book2.php'"));
$vnum1 = "$vquery1[0]";
$vnum2 = "$vquery2[0]";
and so on... Until you get to 25 for both this and engine 1.
Now, in your results page, after you put in the require_once(engine.php) and require_once(engine2.php) at the start of your body, start an HTML table. You only want two columns, so it'll be something like..
<table border=1 cellspacing=0 cellpadding=0>
<tr>
<?php include $num1; ?>
</tr>
<tr>
<?php include $num2; ?>
</tr>
And so on... By naming your field with "book1.php" and including the engines, $num1 will change to a different .php file depending on votes from high to low. Now all you have to do is make small php files for each book like so - no headers or anything because you're inserting it into the middle of html code already:
<td style="width:650px;"><center><img src="images/book1.jpg" alt="" border="none"
/></a></center></td>
<td style="width:150px;">Votes: <?php echo $vnum1;?></td>
And there you have it. A code that will dynamically give you results from high to low depending on the number of votes each book has.