I need help from you guys here.
The problem is I have to display download link from a table that connected from other tables, there are three (3) tables.
**First Table:**
file_id | file_title | file_name | file_dir
-------------------------------------------
| | |
**Second Table:**
file_id | books_id
-------------------
**Third Table:**
books_id | books_title | books_author | books_publisher
-----------------------------------------------------------
I just want to create a button that can download the file from the first table, the files was stored in a folder. I was little bit confused, why the developer staff before me that built this scripts (now the person was quit and I cannot contact him) add to three tables for uploaded files. And if I was changed the upload field, I have to changed everything.
Any clue?or link that can help me perhaps?to solve my confusedness.
Thank you for the helps from you guys here.
Sorry for my English. :)
I believe the query you're looking for is:
SELECT t1.file_title, t1.file_name, t1.file_dir,
t3.books_title, t3.books_author, t3.books_publisher
FROM first_table t1, second_table t2, third_table t3
WHERE t1.file_id=t2.file_id AND
t2.books_id=t3.books_id
This assumes the names of your tables are first_table, second_table, and third_table. Feel free to modify accordingly.
To use this result in PHP, you could do something like this:
$sql = "SELECT t1.file_title, t1.file_name, t1.file_dir, " .
" t3.books_title, t3.books_author, t3.books_publisher " .
"FROM first_table t1, second_table t2, third_table t3 " .
"WHERE t1.file_id=t2.file_id AND " .
" t2.books_id=t3.books_id";
$query_result = mysqli_query($sql);
$data = array();
while ($row = mysqli_fetch_assoc($query_result)) {
$row_data = array();
foreach ($row as $key => $value) {
$row_data[$key] = $value;
}
array_push($data, $row_data);
}
foreach($data as $item) {
$path_to_file = $item['file_dir'] . '/' . $item['file_name'];
print "<a href='$path_to_file'>" .
$item['books_title'] .
' (Author: ' . $item['books_author'] . ', ' .
' Publisher: ' . $item['books_publisher'] . ')</a>';
print '<br>';
}
Of course, the outputting of HTML is entirely for demonstration purposes - I don't know exactly what kind of formatting you need. The critical pieces to understand are:
piece the $path_to_file together based on the $item['file_dir'] and $item['file_name']
make your link (or your button, or whatever you choose to use) point to that $path_to_file.
SELECT FirstTable.file_name, FirstTable.file_dir, ThirdTable.books_title, ThirdTable.books_author, ThirdTable.books_publisher INNER JOIN SecondTable ON FirstTable.file_id = SecondTable.file_id INNER JOIN ThirdTable ON SecondTable.books_id = ThirdTable.books_id
INNER JOIN may not necessarily be the JOIN type you want to use, but this would be the general idea for grabbing data from 2 tables corresponding to a third (SecondTable) which links them.
$link = $row['file_dir'] . $row['file_name'];
Related
First loop table
user_id | fname | lname
1 | first | emp
2 | second| emp
3 | third | emp
Second loop table
shift_id | employee_id
1 | 1
2 | 2
3 | 2
if($employees)
{
foreach ($employees as $employee)
{
if($employee['user_id'] == $shift['employee_id'])
{
echo ucwords($employee['fname']. ' ' .$employee['lname']);
}
}
}
I am getting the right result but I think there is some better way of writing this.
You can use joins in table. Left join means that the user line has to exists (because: LEFT) and the shifts enty is optional.
SELECT user.user_id, user.fname, user.lname, shifts.shift_id
FROM yourUserTable AS user
LEFT JOIN yourShiftsTable AS shifts ON(user.user_id = shifts.employee_id)
Now you get it in your initial array, as if you'd select it as one row from a table and no longer need to do tricks in PHP to combine information. If you can, always try to get the database to manage data, it does that way faster than PHP can.
Please note, the query could be a little off, I just wrote this out of the top of my head.
Just some test code I whipped up to test this from the information provided for this "Demonstration Code".
Note: I have used the mysqli class for the database (instantiating $db ) and have excluded the SQL Table setup.
What you would have had is something along the lines of this...
Case 1 - The original
$db = new mysqli('localhost', 'root', 'test', 'phptutorials_st26');
echo '<h2>Create $employees </h2>';
$query = "SELECT * FROM users";
$result = $db->query($query);
$employees = $result->fetch_all(MYSQL_ASSOC);
var_dump($employees);
echo '<h2>Create $shifts </h2>';
$query = "SELECT * FROM shifts";
$result = $db->query($query);
$shifts = $result->fetch_all(MYSQL_ASSOC);
var_dump($shifts);
echo '<h2>Using foreach on $employees and $shifts</h2>';
if ($employees) {
foreach ($employees as $employee) {
foreach ($shifts as $shift) {
if ($employee['user_id'] == $shift['employee_id']) {
echo ucwords($employee['fname'] . ' ' . $employee['lname']);
echo '<br>';
}
}
}
}
The Result from the above is
First Emp
Second Emp
Second Emp
Case 2 - Using a Join
Well using a join, as everyone has already stated, is the way to go...
$sql = "SELECT u.user_id, u.fname, u.lname, s.shift_id
FROM users AS u
JOIN shifts AS s ON(u.user_id = s.employee_id)
";
$result = $db->query($sql);
$employees = $result->fetch_all(MYSQL_ASSOC);
// To see what comes out because we always check things.
var_dump($joined_result);
(Don't ask me why I love using very abbreviated aliases for the table names! It's just "a thing".)
Then your "loop" simply becomes...
echo '<h2>Using foreach on join</h2>';
foreach ($employees as $employee) {
echo ucwords($employee['fname'] . ' ' . $employee['lname']);
echo '<br>';
}
And the result is...
First Emp
Second Emp
Second Emp
Case 2 - has reduced the code and only requires 1 Trip to the Database.
Does that help you any?
You could do it this way also. Its a little shorter.
SELECT TABLE1.FNAME, TABLE1.LNAME, TABLE2.EMPLOYEE_ID
FROM TABLE1, TABLE2
WHERE TABLE1.USER_ID = TABLE2.EMPLOYEE_ID;
I am working on a webpage that displays list of shops. I have 2 tables, shops and shops_sched.
+-shops-+
| id | title |
+-------------shops_sched-------------+
| id | shops_id | start_date | end_date |
Basically, the program displays the list of shops from the shops table, but if a value from shops.id is found # shops_sched.shops_id the page must output shops.title + 'coming soon'.
I understand this will be easy if I just place the date fields inside the table shops but due to programming restrictions I can't. I'm working on an existing project and I'm trying to minimize changes to existing functions. I can create new PHP functions if necessary though.
In addition, I need to get all the entries from the shops table. The Program needs to return all shops.title but for those shops whose id is found # shops_sched.shops_id, the program will have to return shops.title + "Coming Soon".
must output shops.title + 'coming soon'.
So do it like this:
$shops.title = "Donut-John";
echo $shops.title." coming soon";
To join the shops and shops_sched table
$query = SELECT `title` FROM `shops` JOIN `shops_sched` ON `shops`.`id` = `shops_sched`.`shops_id` WHERE `shops_sched`.`shop_id` = 5;
$result = mysql_query($query);
while($row = mysql_fetch_array($result) {
echo $row['title'] . 'coming soon';
}
For more about join you also can refer the following link
https://dev.mysql.com/doc/refman/5.0/en/join.html
http://www.tutorialspoint.com/mysql/mysql-using-joins.htm
Join the two tables :
SELECT shops.title
FROM shops INNER JOIN shops_sched ON shops.id = shops_sched.shops_id
The query should return only the the shops inside shops_sched
EDIT :
If I understood your question, try this :
SELECT shops.title, shops_sched.id
FROM shops LEFT JOIN shops_sched ON shops.id = shops_sched.shops_id
This will return all the titles, and the shops_sched.shops_id if shops.id = shops_sched.shops_id. In the other case, the hops_sched.shops_id will be null
Then you fetch the rows and if the second row is not null, print title + coming soon
Sample code : (Something like this)
$query = "SELECT `title`, 'shops_id' FROM `shops` LEFT JOIN `shops_sched` ON `shops`.`id` = `shops_sched`.`shops_id` WHERE `shops_sched`.`shop_id`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result) {
if($row['shops_id'] != "")
{
echo $row['title'] . ' coming soon';
}
else
{
echo $row['title'];
}
}
I have three tables, "food","member" and "member_food". I'm trying to make an update user page where a collection of tags are prepopulated by the data in "member_food".
I have debugged the ID sending from the previous page which allows me to select the entry I wish to query, ID:4.
$query = "SELECT * FROM `food` left join `member_food` on food.entityid = member_food.food_id WHERE member_id = '$id'";
//Breakfast
$breakfastresult1 = $mysqli->query($query);
echo '<select name="breakfast1">';
while($BreakfastData1 = mysqli_fetch_array($breakfastresult1, MYSQL_ASSOC))
{
echo '<p><option value="' . htmlspecialchars($BreakfastData1['member_food.food_id']) . '">'
. htmlspecialchars($BreakfastData1['member_food.food_name'])
. '</option>'
. '</p>';
}
echo '</select>';
However, the select fields appear to be empty. I think it's not pulling the correct values from my leftjoin table.
Here is an example of my member_food table:
food table:
edit this, first you have a typo (space missing in left + join) second you need to tell from which of the table member_id belong
$query = "SELECT * FROM `food` as f left join `member_food` as mf on f.entityid = mf.food_id WHERE mf.member_id = '$id'";
You can use this to plan your joins correctly. And, as Abdul pointed out, typos are bad ;)
It's common to use ID and parent to store the categories tree. In my case, a knowledge base, in article table every record(article) belong to a category(with a field catid), in categories table every record has a ID and parent to save the tree structure.
article table
id | catid | date | subject | content
categories table
id | name | parent
The problem is when export article to csv or excel,
id | category | date | subject | content
how to keep the whole categories tree, just like when a article belong to son category, I want the category like
grandpa/father/son/, or grandpa : father : son
then can open the csv in excel, menu -> data -> text to column, seperate by ":", you will get a whole tree category not only current category.
work code sample:
$query = 'SELECT `a`.`id` AS `ID`, concat(CASE WHEN ISNULL(`f`.`name`) THEN "" ELSE concat(`f`.`name`,":") END,CASE WHEN ISNULL(`e`.`name`) THEN "" ELSE concat(`e`.`name`,":") END,CASE WHEN ISNULL(`d`.`name`) THEN "" ELSE concat(`d`.`name`,":") END,CASE WHEN ISNULL(`c`.`name`) THEN "" ELSE concat(`c`.`name`,":") END,CASE WHEN ISNULL(`b`.`name`) THEN "" ELSE `b`.`name` END) AS `Category`, `a`.`subject` AS `Subject`,`a`.`content` AS `Content`,`a`.`dt` AS `Date Created`,
FROM articles as a
LEFT JOIN categories as b ON a.catid = b.id
LEFT JOIN categories as c ON b.parent = c.id
LEFT JOIN categories as d ON c.parent = d.id
LEFT JOIN categories as e ON d.parent = e.id
LEFT JOIN categories as f ON e.parent = f.id
WHERE (DATE(`dt`) BETWEEN \'' . $date_from . '\' AND \'' . $date_to . '\') order by id asc';
hope it help for others which want to export tree structure fields.
You have to parse the result after querying the database:
$query = 'query code here';
$result = mysql_query($query);
while( $row = mysql_fetch_array($result) ) {
// do something with that row
}
Besides, mysql_x functions are deprecated. Use PDO or mysqli instead.
<?php
$conn = mysql_connect("localhost","YOUR DB USER NAME","YOUR DB PASSWORD");
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("YOUR DB NAME", $conn);
$result = mysql_query("YOUR QUERY HERE");
while($row = mysql_fetch_array($result)) {
echo $row['ID'];
-----
-----
}
mysql_close($conn);
I assume, you would like to execute the SQL code in PHP, that you designed in phpMyAdmin - which works well. The most common problems are with the quotes. Learn about String quotes here
As I see you use ' to frame the query code, but you use it inside the query as well. That must have produced an awful series of syntax errors. You may use " to frame the query code while setting it to a variable.
If you get nothing, than maybe the SQL command could have executed, but the result was empty. You can test this with the var_dump() function. Also check that you have all the error reporting switched on. Learn about error reporting here
Also, I'd suggest you to examine and use the PDO class instead of the mysql functions, which would throw you handsome exceptions you could catch and deal with the errors elegantly. The PDO
will also secure your code in some way.
I am trying to write a PHP script that will create an HTML form using the “field_definitions” table as a source for input fields and set the default values of each field based on previously stored results from the “user_data” table. (based on the currently logged in user… I have an auth system setup and running using session variables.)
My tables are like so...
users TABLE
user_id user_email user_firstname user_lastname user_password
1 johndoe#mail.com John Doe password
field_definitions TABLE
field_id field_type field_length field_name field_desc field_section
1 text 40 color What is your favorite color? 1
user_data TABLE
response_id user_id field_id user_response
1 1 1 Blue
I’ve created a block of code that returns the rows from my “field_definitions” table and stores them in an array. I’m able to use a foreach loop to generate the form based on each row in the array, but I can’t figure out how to pull-in the second set of information from the other table for the default values.
$dbc = mysqli_connect(sqlhost, sqluser, sqlsecret, sqldb);
$field_definitions_query = "SELECT * FROM field_definitions WHERE field_section = '1'";
$field_definitions_data = mysqli_query($dbc, $field_definitions_query);
$field_definitions = array();
while ($row = mysqli_fetch_array($field_definitions_data)) {
array_push($field_definitions, $row);
}
echo '<form enctype="multipart/form-data" method="post" action="' . $_SERVER['PHP_SELF'] . '">';
foreach ($field_definitions as $row) {
echo '<label for="' . $row[field_name] . '">' . $row[field_desc] . ':</label>';
echo '<input type="' . $row[field_type] . '" id="' . $row[field_name] . '" name="' . $row[field_name]. '" value="temp" /><br />';
}
echo '<input type="submit" value="Save" name="submit" /></form>';
Do I need to create a second array of the other table data, then merge the two in someway?
Is my general approach feasible, or is there a better way?
I am a beginner in PHP and programming in general and would rather not try and conquer any of the frameworks out there; I’m trying to pull this off with my own code for the sake of learning.
Consider using SQL JOIN construction. In case of MySQL it would be something like this:
select t1.*, t2.user_response from field_definitions t1 left join user_data t2 using (field_id) where t2.user_id = %USER_ID% or t2.user_id is null. Then you can fetch data row-by-row to a single array/hash/whatever. See your SQL manual for more details on JOINs.
In short. We are joining tables t1 and t2 by field x. N is NULL (non-existent) record. Ljn is LEFT JOIN, Rjn is RIGHT JOIN, Ijn is INNER JOIN (INNER keyword is frequently ommited) and Fjn is FULL JOIN
t1.x: 1 2 3 4 5 N N
t2.x: N N N 4 5 6 7
Ljn : ^_______^----
Rjn : -----^______^
Ijn : -----^__^----
Fjn : ^___________^
You can check if record is non-existing one by t1.x IS NULL or t1.x IS NOT NULL in where clause.
Hope it will help.