Is it possible to do this??
table1 has a column name 'id'
table2 has a column name 'id' too.
because table2 accepts multiple value from selected checkbox, and I want to relate it with table1. table1 contains the firstname lastname and etc. while table2 contains selected value from the checkbox (1 or more selected).
table1
id | firstname | lastname
1 | John | Conner
table2
id | sports
1 | basketball
2 | volleyball
3 | tennis
john selected 3 values from the checkboxes...
how can I relate or make it that the first inserted data will own the 3 values or will be displayed like this:
id | firstname | lastname | sports
1 | John | Conner | basketball
| volleyball -------->
| tennis------------->
thanks in advance...
sorry for the illustrations.
To do that, you'll need a Many to Many relationship.
You'll need a third table that keeps the relationships between the other two.
You need 3rd table that connects users to sports.
connections
--------------------------
id | users_id | sports_id
1 | 1 | 1
2 | 1 | 2
3 | 2 | 1
--------------------------
The above table would connect user #1 to sports #1 and #2, user #2 to sport #1. (I renamed the tables from your question to make my example more readable: table1 -> users and table2 -> sports)
To combine the records using this method, you can call
SELECT users.firstname, users.lastname, sports.sports
FROM connections
JOIN users ON connections.users_id = users.id
JOIN sports ON connections.sports_id = sports.id
This also ables you to show users that have selected specific sport from the list. This way you can also edit sports name once to affect all results at the same time.
Good examples of JOIN, OUTER JOIN and LEFT JOIN on w3schools
Working example using PHP/MySQLi
$db = new mysqli('localhost', 'user', 'pass', 'database'); // Database connection
if ($db->connect_errno > 0) { // Do we have a connection?
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Set the sql query
$sql = "SELECT users.firstname, users.lastname, sports.sports
FROM connections
JOIN users ON connections.users_id = users.id
JOIN sports ON connections.sports_id = sports.id";
if (! ($result = $db->query($sql))) { // Run the query, get results to $result, if errors die
die('There was an error running the query [' . $db->error . ']');
}
while (($row = $result->fetch_assoc())) { // Loop through the results and echo
echo $row['firstname'] . ' ' . $row['lastname'] . ' likes ' . $row['sports'] . '<br />';
// To see all $row variables in nice format we can do: echo '<pre>' . print_r($row, true) . '</pre>';
}
I added Kyle Reese as user id #2, so the output from my query results would be:
John Conner likes basketball
John Conner likes volleyball
Kyle Reese likes basketball
Read more about MySQLi (php.net)
Example adapted from 'MySQLi for Beginners' (codular.com)
Related
i have two tables "employees" and "dependents",
Employees
|employee_No| Employee_name |
|1558 | Bean |
|1557 | Juliet |
|1556 | Zeke |
Dependents
|employee_No| dependent_name | relationship|
|1558 | Kelvin | Son |
|1558 | Mary | Daughter |
|1556 | Janet | Spouse |
is there a way i could get this data in one MySQL statement and display using php i.e. loop employees and dependent under that employee then move to the next employee.
current php code is
$employees = select_all_employees()
foreach ($employees as $covered){
echo $covered['Employee_name'].'<br/>';
$get_dependent = $select_dependent($covered["employee_No "]);
if($get_dependent != 0){
foreach($get_dependent as $details){
echo $details['dependent_name '].' '.$details['relationship'].'<br/>';
}
}
}
this takes too much time to load when there are thousand employees and dependents
expected outcome
|employee_No| dependent_name | relationship|
--------------------------------------------
|1558 | Bean | principal |
|1558 | Kelvin | Son |
|1558 | Mary | Daughter |
|1557 | Juliet | principal |
|1556 | Zeke | principal |
|1556 | Janet | Spouse |
The easiest way to get the results you want is with a UNION of the rows of the Employees table with the JOIN of the Employees with their Dependents. We do this UNION as a derived table so that we can then order the results by employee_No and also place the principal first for each employee_No. By doing it this way your PHP code becomes a simple loop over all the results.
SELECT employee_No, Employee_name AS dependent_name, 'principal' AS relationship
FROM Employees
UNION ALL
SELECT e.employee_No, d.dependent_name, d.relationship
FROM Employees e
JOIN Dependents d on d.employee_No = e.employee_No
ORDER BY employee_No DESC, relationship = 'principal' DESC
Output:
employee_No dependent_name relationship
1558 Bean principal
1558 Mary Daughter
1558 Kelvin Son
1557 Juliet principal
1556 Zeke principal
1556 Janet Spouse
Demo on dbfiddle
How about this query:
SELECT a.*, "principal" as 'relationship' FROM Employees a
UNION SELECT b.* FROM Dependents b ORDER BY employee_no DESC
DBFIDDLE here
You can use join or Map the columns. Check the index in both the tables for your slowness of query. Index should be employee_No in both the tables. And then loop your query output.
<?php
$qryOutput = array();
$query = "SELECT A.*, B.* FROM Employees A LEFT JOIN Dependents B ON A.employee_No=B.employee_No" // query
$qryOutput = execute_Query($query); // Check this syntax. For Execute query
// Loop through your Query Output
foreach ($qryOutput as $key => $value)
{ echo $value["employee_No"]." ".$value["dependent_name"]." ".$value["relationship"]; }
?>
You can use either INNER JOIN or LEFT JOIN to actualize it.
Try something like this. Though I have not tested the code.
Your table need to be created with foreign key references for it to work. see sample below. I have tested it.
create table Employees(employee_No int primary key,Employee_name varchar(100));
create table Dependents(employee_No int primary key,dependent_name varchar(100), relationship varchar(100)
foreign key (employee_No) references Employees(employee_No));
Insert for testing
insert into Employees(employee_No,Employee_name) values(1558,'Bean');
insert into Employees(employee_No,Employee_name) values(1557,'Juliet');
insert into Dependents(employee_No,dependent_name,relationship) values(1558,'kevin','son');
code
<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "your-db"; /* Database name */
$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$query = 'SELECT Employees.employee_No, Employees.Employee_name, Dependents.employee_No, Dependents.dependent_name,
Dependents.relationship FROM Employees
LEFT JOIN Dependents ON Employees.employee_No = Dependents.employee_No
ORDER BY Employees.Employee_name';
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_assoc($result)){
$empno = $row['employee_No'];
$empname = $row['Employee_name'];
$relation = $row['relationship'];
$dependant_name = $row['dependent_name'];
//you can now echo
echo $dependant_name.' '.$relation.'<br/>';
}
?>
I have a dance contest site and each user can login and add dance moments,
in my html table with all moments from all users i have all the data but i want in a html column to add "number of dancers for each moment added by the logged user id".
I have this:
$c = mysql_query("SELECT * FROM moments");
$dancers = 0;
while($rows = mysql_fetch_array($c)){
for($i = 1; $i <= 24; $i++){
$dan_id = 'dancer'.$i;
if($rows[$dan_id] != "" || $rows[$dan_id] != null )
$dancers++;
}
}
echo "<th class="tg-amwm">NR of dancers</th>";
echo "<td class='tg-yw4l'>$dancers</td>";
phpMyAdmin moments table: has id, clubname, category, discipline, section, and this:
But this process is count all the dancers names from all users moments.
Example for this process: You have a total of 200 dancers !
I want the process to count for me all dancers names for each moment added in the form not a total of all entire users moments, something like this: if user john has two moments added: Moment 1: 5 dancers - moment 2: 10 dancers, and so on for each user.
Let me try to put you in the right way (it seems a long post but I think it's worth the beginners to read it!).
You have been told in the comments to normalize your database, and if I were you and if you want your project to work well for a long time... I'd do it.
There are many MySQL normalization tutorials, and you can google it your self if you are interested... I'm just going to help you with your particular example and I'm sure you will understand it.
Basically, you have to create different tables to store "different concepts", and then join it when you query the database.
In this case, I would create these tables:
categories, dance_clubs, users and dancers store "basic" data.
moments and moment_dancers store foreign keys to create relations between the data.
Let's see the content to understand it better.
mysql> select * from categories;
+----+---------------+
| id | name |
+----+---------------+
| 1 | Hip-hop/dance |
+----+---------------+
mysql> select * from dance_clubs;
+----+---------------+
| id | name |
+----+---------------+
| 1 | dance academy |
+----+---------------+
mysql> select * from users;
+----+-------+
| id | name |
+----+-------+
| 1 | alex |
+----+-------+
mysql> select * from dancers;
+----+-------+
| id | name |
+----+-------+
| 1 | alex |
| 2 | dan |
| 3 | mihai |
+----+-------+
mysql> select * from moments;
+----+--------------+---------------+-------------------+
| id | main_user_id | dance_club_id | dance_category_id |
+----+--------------+---------------+-------------------+
| 1 | 1 | 1 | 1 |
+----+--------------+---------------+-------------------+
(user alex) (dance acad..) (Hip-hop/dance)
mysql> select * from moment_dancers;
+----+-----------+-----------+
| id | moment_id | dancer_id |
+----+-----------+-----------+
| 1 | 1 | 1 | (moment 1, dancer alex)
| 2 | 1 | 2 | (moment 1, dancer dan)
| 3 | 1 | 3 | (moment 1, dancer mihai)
+----+-----------+-----------+
Ok! Now we want to make some queries from PHP.
We will use prepared statements instead of mysql_* queries as they said in the comments aswell.
The concept of prepared statement can be a bit hard to understand at first. Just read closely the code and look for some tutorials again ;)
Easy example to list the dancers (just to understand it):
// Your connection settings
$connData = ["localhost", "user", "pass", "dancers"];
$conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]);
$conn->set_charset("utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Here we explain MySQL which will be the query
$stmt = $conn->prepare("select * from dancers");
// Here we explain PHP which variables will store the values of the two columns (row by row)
$stmt->bind_result($dancerId, $dancerName);
// Here we execute the query and store the result
$stmt->execute();
$stmt->store_result();
// Here we store the results of each row in our two PHP variables
while($stmt->fetch()){
// Now we can do whatever we want (store in array, echo, etc)
echo "<p>$dancerId - $dancerName</p>";
}
$stmt->close();
$conn->close();
Result in the browser:
Good! Now something a bit harder! List the moments:
// Your connection settings
$connData = ["localhost", "user", "pass", "dancers"];
$conn = new mysqli($connData[0], $connData[1], $connData[2], $connData[3]);
$conn->set_charset("utf8");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to read the "moments", but we have their main user and dancers in other tables
$stmtMoments = $conn->prepare("
select
moments.id,
(select name from users where users.id = moments.main_user_id) as main_user,
(select name from dance_clubs where dance_clubs.id = moments.dance_club_id) as dance_club,
(select name from categories where categories.id = moments.dance_category_id) as dance_category,
(select count(*) from moment_dancers where moment_dancers.moment_id = moments.id) as number_of_dancers
from moments
");
// Five columns, five variables... you know ;)
$stmtMoments->bind_result($momentId, $momentMainUser, $momentDanceClub, $momentDanceCategory, $momentNumberOfDancers);
// Query to read the dancers of the "moment" with id $momentId
$stmtDancers = $conn->prepare("
select
dancers.name as dancer_name
from
dancers join moment_dancers on dancers.id = moment_dancers.dancer_id
where
moment_dancers.moment_id = ?
");
$stmtDancers->bind_param("i", $momentId);
$stmtDancers->bind_result($momentDancerName);
// Executing the "moments" query
$stmtMoments->execute();
$stmtMoments->store_result();
// We will enter once to the while because we have only one "moment" right now
while($stmtMoments->fetch()){
// Do whatever you want with $momentId, $momentMainUser, $momentDanceClub, $momentDanceCategory, $momentNumberOfDancers
// For example:
echo "<h3>Moment $momentId</h3>";
echo "<p>Main user: $momentMainUser</p>";
echo "<p>Dance club: $momentDanceClub</p>";
echo "<p>Category: $momentDanceCategory</p>";
echo "<p>Number of dancers: $momentNumberOfDancers</p>";
echo "<p><strong>Dancers</strong>: ";
// Now, for this moment, we look for its dancers
$stmtDancers->execute();
$stmtDancers->store_result();
while($stmtDancers->fetch()){
// Do whatever you want with each $momentDancerName
// For example, echo it:
echo $momentDancerName . " ";
}
echo "</p>";
echo "<hr>";
}
$stmtUsers->close();
$stmtMoments->close();
$conn->close();
Result in browser:
And that's all! Please ask me if you have any question!
(I could post the DDL code to create the database of the example with the content data if you want)
Edited: added dancers table. Renamed moment_users to moment_dancers. Changed functionality to adapt the script to new tables and names.
Right now, I have two database tables. Table history_2014 has a column(member) that says whether or not a member is active (Y or N). I have another table called history_overall that contains all of the contact information for these members. I need a table that will only show the rows of history_overall for active members. Right now, I have this PHP:
<?php
$con=mysqli_connect("localhost","myusername","mypassword","mydatabase");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM history_overall");
echo "<table border='1'>
<tr>
<th>Address 1</th>
<th>Last Name</th>
</tr>";
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['address1'] . "</td>";
echo "<td>" . $row['last_name'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
The current code will allow me to display all rows, but I need to be able to display certain rows based on the other table.
what column ties the two tables together?
A JOIN will accomplish this if there is a relationship.
Example:
SELECT history_overall.* FROM members
JOIN history_overall
ON history_overall.member_id = members.id
WHERE members.active = 'Y';
----Edit/Comment----
Since I'm not able to add the table structure layout in a comment I will comment here.
It is more valuable when wanting to retrieve specific records from the database to provide us with the table schema as opposed to the actual table names. As well as an example of the resulting data you want as a result.
All you really provided to us with is table history_2014 with columns (member = Y|N), table history_overall with columns (address1, last_name) which doesn't allow us to build a relationship between the two (or more) tables.
Here is an example assuming both tables have a memberid column:
----------------------- -------------------------------------
| table1 | | table2 |
----------------------- -------------------------------------
| member | memberid | | address1 | full_name | memberid |
----------------------- -------------------------------------
| Y | 1 | | 123 street | jon doe | 1 |
----------------------- -------------------------------------
| N | 2 | | 789 court | jane doe | 2 |
----------------------- -------------------------------------
| Y | 3 | | 456 road | foo bar | 3 |
----------------------- -------------------------------------
Question: How can I retrieve records from table2 where the member in table1 is 'Y'?
This is my desired result of the records:
-------------------------------------
| recordset |
-------------------------------------
| address1 | full_name | memberid |
-------------------------------------
| 123 street | jon doe | 1 |
-------------------------------------
| 456 road | foo bar | 3 |
-------------------------------------
Answer query:
SELECT table2.*
FROM table1
JOIN table2
ON table1.memberid = table2.memberid
WHERE table1.member = 'Y'
Explained:
Retrieve all columns in table2 that the memberid column in table1 is the same as the memberid column in table2 from the rows in table1 that the member column contains Y as a value with no ordering or limit on the amount of records returned.
I guess you have some kind of Id of the user in both tables, you could make a query creating a join between the two tables where id matches and selecting only the rows where member = 'Y'
Simply use this method
select * from history_overall,members where members.status='active'
You will get all the active members results including history also.
Use a table join (MySQL doc: http://dev.mysql.com/doc/refman/5.7/en/join.html).
In short, something like:
SELECT ho.*
FROM history_overall AS ho
RIGHT JOIN history_2014 AS h ON ho.memberId = h.memberId
WHERE h.isActive = 'Y';
Obviously your field names are probably different...
this is going to be a bit complicated. But I'll try to explain what I'm trying to do.
I've got a table in a database as follows:
Table - Entries
ID | User | Address | Workflow | Audit Date |
1 | Tim | 123 | 10 p/w | 22/2/2013 |
2 | Bob | 222 | 20 p/w | 22/2/2013 |
Now in a corresponding table i have pictures:
Table - Pictures
ID | JobNo | User | ImagePath | ImageName |
52 | 1 | Tim | /1.jpg | /2.jpg |
53 | 1 | Tim | /3.jpg | /4.jpg |
Now Pictures.Jobno corresponds to Entries.ID
Alright so what I'm after, is to list all entries from table Entries when the related jobNo has more than 2 image entries. if it has 1 or less, I want to ignore the listing.
So at the moment I can call entries like this through php:
function getAllEntries() {
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
if (!($query = $mysqli->prepare("SELECT * FROM Entries
ORDER BY Date DESC"))) {
echo "Prepare failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
if (!$query->execute()) {
echo "Execute failed: (" . $query->errno . ") " . $query->error;
}
$query->bind_result($ID, $User, $Address, $Workflow, $Audit);
while ($query->fetch()) {
//Echo each entry here
}
$query->close();
$mysqli->close();
}
My issue is, how do I then incorporate what I want to do? I want to say:
Select all entries, where in table Pictures there are 2 or more images corresponding to the job number/id comparison in the Entries table.
I'm sure this doable. But I can't think of the sql statement or how to bind it in a prepared statement correctly
SELECT * FROM Entries, Pictures, Where Pictures.Jobno = ID.Entries AND (row amount in pictures) >= 2.
Or something? Is this just an SQL problem? Or do I need an if statement and to run a separate SQL query.
I'm self taught with php and sql I'm afraid - so I don't quite know how to resolve this myself.
The way to handle this is typically by joining against a subquery which retrieves the number of Pictures per JobNo and filtering those >= 2 in the HAVING clause:
SELECT
entries.*,
numpics
FROM entries
LEFT JOIN (
/* Subquery joined returns aggregate COUNT() in pictures per JobNo */
SELECT JobNo, COUNT(*) AS numpics FROM pictures GROUP BY JobNo
) pcounts ON entries.ID = pcounts.JobNo
HAVING numpics >= 2
http://sqlfiddle.com/#!2/347f4/8
Because of MySQL's lenient treatment of the GROUP BY, you can probably get away with just a LEFT JOIN, against pictures without the subquery:
/* MySQL Only */
SELECT entries.*
FROM
entries
LEFT JOIN pictures ON entries.ID = Pictures.JobNo
GROUP BY entries.ID
HAVING COUNT(pictures.JobNo) >= 2
I have 2 tables in my database and I wanted a PHP output of the following:
Dogs 5
Cats 2
Birds 4
how can I do this?
The above is listing of categories with a count of how many dogs, cats and birds are in each category.
I have 2 tables in MySQL laid out like this:
Pets (MySql Table name)
AnimalNAME | AnimalCAT | AnimalDES
Bolt | 1 | Smelly dog
Minx | 2 | Snobby cat
Twit | 3 | Cherpy bird
Rony | 1 | Sneaky dog
Categories (MySql Table name)
AnimalCAT | Name
1 | Dogs
2 | Cats
3 | Birds
Here's the query:
SELECT
Categories.Name,
COUNT(Pets.AnimalCAT)
FROM
Categories
LEFT OUTER JOIN
Pets
ON
Categories.AnimalCAT = Pets.AnimalCAT
GROUP BY
Categories.AnimalCAT
PHP example:
mysql_connect('localhost', 'username', 'password');
mysql_select_db('dbname');
$sql = "
SELECT
Categories.Name AS `category`,
COUNT(Pets.AnimalCAT) AS `count`
FROM
Categories
LEFT OUTER JOIN
Pets
ON
Categories.AnimalCAT = Pets.AnimalCAT
GROUP BY
Categories.AnimalCAT
";
$result = mysql_query($sql) or die("Error in SQL: " . mysql_error());
while ($row = mysql_fetch_array($result)) {
echo $row['category'] . ' ' . $row['count'] . '<br />';
}