I'm kind of new to PHP/MySQl so I would like some guidelines on how these thing work, hard to google this...
So, im trying to learn php/mysql and I'm about to write a small page with customers and each customer could have a few projects.
so, my db is set up as follows (guess this would need heavy modifications):
- customers (id, name, description)
- projects (id, name, description)
- users (id, name )
<?php
if(isset($_GET['id'])) {
$query = "SELECT * FROM customers WHERE id = '". $_GET['id']."'";
$results = mysql_query($query);
while($row = mysql_fetch_array( $results ))
{
echo "<h3>" . $row['name'] . "</h3>";
echo "<br />";
$query = "SELECT * FROM projects ORDER by name ASC";
$results = mysql_query($query);
echo "<table>
<tbody>";
while($row = mysql_fetch_array( $results ))
{
echo "<tr>
<td><a href='main.php?id=" . $row['id'] . "'>" . $row['name'] . "</a></td>
<td>" . $row['description'] . "</td>
</tr>";
}
echo "</tbody>
</table>";
}
} else {
$query = "SELECT * FROM customers ORDER by name ASC";
$results = mysql_query($query);
echo "<table>
<thead>
<tr>
<th width='20%'>Customer</th>
<th width='80%'>Description</th>
</tr>
</thead>
<tbody>";
while($row = mysql_fetch_array( $results ))
{
echo "<tr>
<td><a href='main.php?id=" . $row['id'] . "'>" . $row['name'] . "</a></td>
<td>" . $row['description'] . "</td>
</tr>";
}
echo "</tbody>
</table>";
}
?>
As you can see it missing some heavy things, for instance, if I choose Customer A or B I receive the same projects, I don't know how to separate the projects and "bind" them to a certain customer. And my intention is to "bind" users to projects and customers as well.
Any hints into the correct direction is appreciated!
You can have an INNER JOIN in the select query, like so:
"SELECT * FROM customers c INNER JOIN projects p ON p.name = c.name WHERE c.id = '". $_GET['id']."'";
Here, I have considered that you DO HAVE a name column in customer table which is the same as that in project.
You would need to add some tables.
First a table that represents the relation from Customers to Projects. This would be like
Customer ID | Project ID
1 | 1
2 | 3
....
Same would be needed for Customer and User.
Now you can reference to this table to get your needed information and perform the necessary joins to get your data.
You need another table which has the key (customers.id,projects.id) In this way you link each customer to their own projects, and you'd need to select the data from that table depending on the id of the customer. Probably you'll need a customer/user table too, to link user id to customer id.
Edit for clarity: The new table should look something like:
CREATE TABLE customer_projects (
customer_id INT NOT NULL,
project_id INT NOT NULL,
PRIMARY KEY (customer_id, project_id));
Then you assign each customer to their projects in this table. To get the details (customer name, project name), you'd need to do a "join" with other tables, something like:
SELECT customers.*, projects.* FROM customer_projects
LEFT JOIN customers ON customers.id = customer_projects.customer_id
LEFT JOIN projects ON projects.id = customer_projects.project_id
WHERE customer_projects.customer_id = '1' // 1 is an example of a customer id.
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 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 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>";
}
I have three tables:
I want to display 'Event Details' which shows attending employee details (listo f employee ids from the 'attending_employees table > corresponding employee details form 'employee' table), what team they belong to (from the club_teams table) and the event details from the 'club_events' table).
Currently I am using multiple mysqli queries to display this information however cannot get my head around pulling the data from the database in one query (ie: LEFT JOIN). Your assistance would be greatly appreciated!
Below are the queries i am currently using:
$query = msqli_query($con, "SELECT * FROM attending_employees")or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0){
while($attending = mysqli_fetch_array($query)){
foreach($attending['club_event']){
$eventid = $attending['club_event'];
$query = msqli_query($con, "SELECT * FROM club_events WHERE club_event_id = '$eventid'")or die(mysqli_error($con));
while($event_details = mysqli_fetch_array($query)){
// Echo event details
}
}foreach($attending['employee']){
$empid = $attending['employee'];
$query = msqli_query($con, "SELECT * FROM employees WHERE employee_id = '$empid'")or die(mysqli_error($con));
while($event_employees = mysqli_fetch_array($query)){
// Echo employee details
}
}foreach($attending['team']){
$teamid = $attending['team'];
$query = msqli_query($con, "SELECT * FROM club_teams WHERE clb_team_id = '$teamid'")or die(mysqli_error($con));
while($event_team = mysqli_fetch_array($query)){
// Echo team details
}
}
}
}
This method is highly inefficient and wasteful since its retrieving duplicate data (ie: all repeated 'club_event_id's in the 'attending_employees' table.)
Try this:
$query = msqli_query(
$con,
"SELECT"
. " attending_employees.*"
. ", club_events.*"
. ", employees.*"
. ", club_teams.*"
. " FROM"
. " attending_employees"
. " LEFT JOIN club_events ON club_events.club_event_id = attending_employees.club_event"
. " LEFT JOIN employees ON employees.employee_id = attending_employees.employee"
. " LEFT JOIN club_teams ON club_teams.clb_team_id = attending_employees.team"
) or die(mysqli_error($con));
Hi i have the following query/table from a local bookstore
$queryadmin ="SELECT last_name, first_name, user_id FROM users";
$recordz = #mysqli_query ($dbc, $queryadmin);
while ($row = mysqli_fetch_array($recordz, MYSQLI_ASSOC)) {
echo '<tr>
<td align="left">' . $row['first_name'] . '</td>
<td align="left">' . $row['last_name'] . '</td>
<td align="left">' . $row['user_id'] . '</td>
</tr>'
;}
now i want an additional column from another table where the numbers of books each user has lend out are displayed.
So the query if nested seperately would go something like this
$query2 = mysql_query("SELECT FROM mirror3 WHERE userid='".$row['user_id']."'", $link);
$anzahl = mysql_num_rows($query2);
placing this query nested inside the while query (right after while starting) from above does not work. How to do that?
supplied argument is not a valid MySQL
result resource
thanks
Your query is wrong. Specify a field name:
$query2 = mysql_query("SELECT
SOMETHING FROM mirror3 WHERE userid='".$row['user_id']."'", $link);
You could probably do this in one query:
$query = mysqli_query('SELECT u.last_name, u.first_name, u.user_id, m.PUT_SOMETHING_HERE
FROM users u
LEFT JOIN mirror3 m ON u.user_id = m.userid
WHERE m.PUT_SOMETHING_HERE IS NOT NULL');
But Parkyprg has a point, you need to be selecting something from that second query.