I'm kinda a noob so I don't know if this is actually possible.
I have two field in my MySQL database that I want to correlate:
Level int(11)
Rank enum('Hobo','Shippai','NoLifer',Troublemaker','gangster') (and so it continues.)
I want so that level 1=Hobo, level 2=Shippai etc. etc.
Currently it looks like this:
Level: {$ir['level']}
And want it to look like this on the website:
Rank: Hobo
Thanks in advance for any help...
Edit:
Here's the code for the table:
";
$exp=(int)($ir['exp']/$ir['exp_needed']*100);
print "
Name: {$ir['username']}Crystals: {$cm}
Level: {$ir['level']}
Exp: {$exp}%
Money: $fm
Gang: ";
$qs=$db->query("SELECT * FROM gangs WHERE gangID={$ir['gang']}");
$rs=$db->fetch_row($qs);
if(!$db->num_rows($qs) )
{
print "No Gang";
}
else
{
print" {$rs['gangNAME']} ";
}
print "
Property: {$ir['hNAME']}
Days Old: {$ir['daysold']}
Health: {$ir['hp']}/{$ir['maxhp']}
Energy: {$ir['energy']}/{$ir['maxenergy']}
Brave: {$ir['brave']}/{$ir['maxbrave']}
Will: {$ir['will']}/{$ir['maxwill']}
";
Create a new table called rank_define inside have, id(int, primary key, auto increment), name(char20), add your named ranks so it looks like this:
id | name
1 | Hobo
2 | Shippai
In your code
$user_id = 1; // or whatever the users rank is
$query = mysql_query("SELECT `name` FROM rank_define WHERE id='$user_id'");
This will return a result set so you will want to do:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "rank: " . $row['name']; // will output rank: Hobo
}
I think this is what you mean, is it for a user account or something different? This is assuming no account and you are just searching for a result.
If it were to be part of a user account system you would want a table for users eg: id (auto inc, primary key, int), name, rank, (etc..)
In rank their rank is inserted from the rank_define table, so 1 = hobo, 2 = shippai etc. Then you would query that table
Updated answer:
Okay so you have the while loop.while ($row = mysql_fetch_array($query, MYSQL_NUM)) {.
It will go something like this:
<table>
<?php
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
echo "<tr>";
echo "<td>Name: " . $row['name'] . "</td>"; // will output their name / account whatever
echo "<td>Rank: " . $row['rank'] . "</td>"; // will output their rank
echo "</tr>";
}
?>
</table>
Related
So i'm pretty new to sql and i'm trying to figure out how to connect two tables together.
I have a table named customers and a table named pets and i want to assign the pets to specific customers.
I am able to assign them a customer value but only as the id, i can't figure out how to take that id and change it to say, a customer name when i reference it back in a table that displays my data.
so for example in my customer table the
customer id = 10; customerName = "John Smith";
then i have the pets table
petId = 16; petName = Alfredo; customerId = 10;
Is there a way to reference that customerID = 10 back to the customer table from the pets table so I can pull the name of the customer instead of the id?
this is my code to display the table that list the pets query, where $row['customer'] I want to show the customer name, not the id.
Thanks
<?php
$sql = "SELECT * from pets ORDER BY petName ASC";
echo "<table class='tableInfo' cellpadding='8'>";
echo "<tr><th>Pet Name</th><th>Owner</th><th colspan='2'>Action</th></tr>";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_array($result)){
echo "<tr>";
echo '<td>' . $row['petName'] .'</td>';
echo '<td>' . $row['customerId'] .'</td>';
echo '<td>Edit</td>';
echo '<td>Delete</td>';
echo "</tr>";
}
echo "</table>";
?>
Yes hi there, you can definitely do that with an inner join:
select * from pets
join customers on pets.customerId = customers.customerId
order by petName
It sounds the query may be returning an error. Perhaps print the error with:
$res = mysqli_query($con, $sql) or die ('Query failed: ' . mysqli_error($con));
while ($row = mysqli_fetch_assoc($res)) {
// Do something with row
}
i am new to PHP and mysql, I am trying to build a table. However, I have a very interesting bug that i can't fix.
code:
//Initializing mysql queries
//-----------------------SELECTING GOALS------------
$sql= "SELECT * FROM goals";
$records = mysql_query($sql);
//-----------------------SELECTING SERVICES---------
$sql2= "SELECT * FROM services";
$records2 = mysql_query($sql2);
//----------------SELECTING THE JUNCTION----------
$sql3 = "SELECT services.sid AS sid, services.name, objectives.oid
FROM services, objectives, servo
WHERE servo.s_id = services.id AND servo.obj_id = objectives.id";
$records3 = mysql_query($sql3);
$sql4 = "SELECT oid, gid, statement, GROUP_CONCAT(DISTINCT gid) AS GOID
FROM goals, objectives, obgoals
WHERE obgoals.go_id = goals.id AND obgoals.ob_id = objectives.id
GROUP BY oid";
$records4 = mysql_query($sql4);
<?php
while ($product = mysql_fetch_assoc($records2)) {
echo "<tr>";
$sid = $product['sid'];
$service = $product['name'];
echo "<td><a href='objectives.php?sid=" . $sid . "&service=" . $service . "'>" . $product['sid'] . "</a> </td>";
echo "<td>".$product['name']."</td>";
echo "<td>";
while ($g4services = mysql_fetch_assoc($records)) {
echo $g4services['gid'];
}
echo"</td>" ;
}
?>
Basically, my table has 30 rows and 3 columns, the last column is supposed to print out values from a database, this part is done by this piece of code
while ($g4services = mysql_fetch_assoc($records)) {
echo $g4services['gid'];
}
However, instead of printing the results for each row, it only prints the results for the first row, basically the first while loop runs and creates the the table with the 30 rows, but the second while loop only prints values on first row only. Essentially this is happening:
|SID|Name Of Service| Objectives|
-------------------------------
|S1| Service 1 | make the best cars|
|s2| Service 2 | |
|s3| Service 3 | |
|s4| Service 5 | |
|s5| Service 5 | |
.....
.....
....
|s30| Service30 | |
for some reason, my objectives column is not populated by the while loop, it only works for the first row. If someone can help me work the while loop to print the values for every row, it will be huge help. I will greatly appreciate it. Thanks.
The problem is that you're reading all the results of $records during the first iteration of the outer while loop. On future iterations, there are no more rows left, so the inner while loop completes immediately.
You can read those results once into a variable outside the loop, and then show that variable during the loop:
$all_g4services = '';
while ($g4services = mysql_fetch_assoc($records)) {
$all_g4services .= $g4services['gid'];
}
while ($product = mysql_fetch_assoc($records2)) {
echo "<tr>";
$sid = $product['sid'];
$service = $product['name'];
echo "<td><a href='objectives.php?sid=" . $sid . "&service=" . $service . "'>" . $product['sid'] . "</a> </td>";
echo "<td>".$product['name']."</td>";
echo "<td>$all_g4services;</td>" ;
}
Your second while loop is not required. It is runnning for each row. Remove it. Then for each row you have to find the entry that matches and echo only that.
echo $g4services['gid']
I dont know how to correct it for you as I dont know the relationship between the two.
I have two tables, employee as the parent and license as the child. They both have a Lic_ID column for reference, this column is the PK in license and the FK in employee. The license table also has a column Lic_Type which holds the name of the license.
I am trying to create a table with list boxes so the employee table can be updated. The list box value needs to be populated with the license.Lic_ID and the license.Lic_Type is to be displayed in the option. Here is what I have:
(Employee name, Id, etc. called out up here)
<?php
echo "<select name=\"Lic\">";
echo "<option value=\"\">Select...</option>";
$sql = $mysqli->query("SELECT Lic_ID, Lic_Type FROM license");
while($row = $result->fetch_assoc())
{
echo "<option value=\"" . $row['Lic_ID'] . "\">" . $row['Lic_Type'] . "</option>";
}
echo "</select>";
?>
So that works good, it shows the license type and has the value set to the license id. What I want to do is have <option selected="selected"> if the license id is set for an employee. This code doesn't work, but I think it illustrates what I'm trying to do:
<?php
echo "<select name=\"Lic\">";
echo "<option value=\"\">Select...</option>";
$sql = $mysqli->query("SELECT license.Lic_ID, license.Lic_Type, employee.Lic_ID FROM employee INNER JOIN license ON employee.Lic_ID = license.Lic_ID");
while($row = $result->fetch_assoc())
{
echo "<option value=\"" . $row['license.Lic_ID'] . "\"";
if($row['employee.Lic_ID'] = $row['license.Lic_ID']){echo "selected=\"selected\";}
echo ">" . $row['license.Lic_Type'] . "</option>";
}
echo "</select>";
?>
Is there a way to accomplish what I'm trying to do?
I think there may have been some confusion on what exactly I was trying to accomplish, I apologize for not being very clear. Anyways, I stumbled over the answer today, so I thought I should post it.
$sql1 = ("SELECT Emp_Name, Lic_MAT_ID FROM employee");
if(!$result_employee_query = $mysqli->query($sql1))
{
die ("There was an error getting the records from the employee table");
}
while($employee = $result_employee_query->fetch_assoc())
{
echo "Employee Name: " . $employee['Emp_Name'] . "<br>";
echo "License: ";
echo "<select>";
$sql2 = ("SELECT Lic_MAT_ID, Lic_MAT_Type FROM license_mat");
if(!$result_license_query = $mysqli->query($sql2))
{
die ("There was an error getting the records from the license table");
}
while($license = $result_license_query->fetch_assoc())
{
echo "<option value=\"" . $license ['Lic_MAT_ID'] . "\"";
if($license['Lic_MAT_ID'] == $employee['Lic_MAT_ID'])
{
echo " selected=\"selected\"";
}
echo ">" . $license ['Lic_MAT_Type'] . "</option>";
}
echo "</select><br>";
}
As I understand your problem: You want to see if the License has been added to ANY users or has it been unassigned. If any of the users have the license set then it's "selected", othervize not.
First you have to assign the keyword "multiple" to your select object to make it a listbox:
echo "<select name=\"Lic\" multiple=\"multiple\">";
Second: I would write this kind of query:
$sql = $mysqli->query("SELECT l.Lic_ID, l.Lic_Type, e.cnt FROM licence l left outer join (select Lic_id, count(*) cnt from employee group by Lic_id) e on l.Lic_ID=e.Lic_id");
It selects the Lic_ID, Lic_Type and the count of how many employees have the respective Lic_ID set to it (left outer join)
and in the code just check, if the count is higher then 0
if($row['cnt'] > 0){
echo "selected=\"selected\";
}
I'm developing a website that has some audio courses, each course can have multiple lessons. I want to display each course in its own table with its different lessons.
This is my SQL statement:
Table: courses
id, title
Table: lessons
id, cid (course id), title, date, file
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
Can someone help me with the PHP code?
This is the I code I have written:
mysql_select_db($database_config, $config);
mysql_query("set names utf8");
$sql = "SELECT lessons.*, courses.title AS course FROM lessons INNER JOIN courses ON courses.id = lessons.cid GROUP BY lessons.id ORDER BY lessons.id" ;
$result = mysql_query($sql) or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<p><span class='heading1'>" . $row['course'] . "</span> </p> ";
echo "<p class='datum'>Posted onder <a href='*'>*</a>, latest update on " . strftime("%A %d %B %Y %H:%M", strtotime($row['date']));
}
echo "</p>";
echo "<class id='text'>";
echo "<p>...</p>";
echo "<table border: none cellpadding='1' cellspacing='1'>";
echo "<tr>";
echo "<th>Nr.</th>";
echo "<th width='450'>Lesso</th>";
echo "<th>Date</th>";
echo "<th>Download</th>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['nr'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . strftime("%d/%m/%Y", strtotime($row['date'])) . "</td>";
echo "<td><a href='audio/" . rawurlencode($row['file']) . "'>MP3</a></td>";
echo "</tr>";
echo "</table>";
echo "<br>";
}
?>
One thing that comes to mind is you're starting with lessons and pulling the course details over with it. That means you're going to have a new row per lesson with a joined course. You may want to sort by course (so they're grouped) then (in PHP) keep a tally of "current course". When the course changes, switch to new heading paragraph, table, etc.
Pseudo code:
$currentCourse = null; // intitialize the course
$query = your select sorted by course;
while ($row in $query)
{
if ($currentCourse != $row['course'])
{
if (!is_null($currentCourse))
{
// there was a course before it, close the current one
}
// begin setting up heading1, table beginning, etc.
$currentCourse = $row['course']; // set this as the active course
}
// dump the current row as a table entry
}
// close the table (same code as in the second if statement)
You close the while loop on line 8 of your code block. Remove that '}' on line 8.
Also the HTML element doesn't exists!
I think I know what's your problem. You need a while loop that loops al the "courses" and in that loop you execute a second query where you select the lessons where the course_id is equal to the current course id you're looping. A little dummy code for you.
<?php
while($row = mysql_fetch_assoc(mysql_query("SELECT * FROM courses"))) {
//display the course
while($row2 = mysql_fetch_assoc(mysql_query("SELECT * FROM lessons WHERE course_id=" . $row['id']))) {
//display the lessons of that course
}
}
?>
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.