how to print data horizontally and vertically in table - php

I am trying to create table with usernames and data assigned to each username.
I have projects and inside each project there are several processes. So want I want to to is to print table with usernames and projects displayed, and then assign each process to the username. Something like this:
username| project TMNT | project LEON | project MAT |
--------+--------------------+----------------+---------------+
barikan | ANM BLD, BGD CUP | N/A | N/A |
beny | N/A | N/A | BGD CUP |
bob | N/A | ANM BLD | N/A |
Where ANM BLD, BGD CUP are the processes from each project.
What I am able to do is to print projects as headers horizontally and usernames vertically:
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<?php
$result = getRecord();
$count = 0;
if (mysqli_num_rows($result) > 0)
while($row = mysqli_fetch_array($result))
{
$projectNo = $row['projectNo'];
$title = $row['title'];
$code = $row['code'];
echo "<th>".$projectNo." ".$title." ".$code."</th>";
$count++;
}
?>
</tr>
</thead>
<tbody>
<?php
$result3 = getLeader();
if (mysqli_num_rows($result3) > 0)
while($row = mysqli_fetch_array($result3))
{
$username = $row['username'];
echo "<tr>
<td>".$username."</td>";
}
?>
</tbody>
And how my database tables look like:
user table
uid| username| salary|
---+---------+-------+
1 | bob | 0 |
2 | barikan | 0 |
3 | beny | 0 |
4 | adam | 0 |
project table
projectNo| title|
---------+------+
1610004 | TMNT |
1610005 | LEON |
1610006 | MAT |
process table(where person is assigned to a process)
projectNo| process | proc_leader|
---------+---------+------------+
1610004 | ANM BLD | barikan |
1610004 | BGD CUP | barikan |
1610005 | ANM BLD | bob |
1610006 | BGD CUP | beny |
I know i can use group_concat function to concat all processes in for same project in one row but how can i print accordingly to each project?
Sql query i am using to concat processes:
"SELECT proc_leader.projectNo, group_concat(proc_leader.process) AS processes, username
FROM user
LEFT OUTER JOIN proc_leader ON user.username=proc_leader.proc_leader
GROUP BY username, proc_leader.projectNo";
EDIT
so what if I have two tables:
process table(where person is assigned to a process)
projectNo| process | proc_leader|
---------+---------+------------+
1610004 | ANM BLD | barikan |
1610004 | BGD CUP | barikan |
1610005 | ANM BLD | bob |
1610006 | BGD CUP | beny |
proc_checker table(where person is assigned to a process in different role)
projectNo| process | proc_checker|
---------+---------+-------------+
1610004 | ANM BLD | adam |
1610004 | BGD CUP | barikan |
1610005 | ANM BLD | barikan |
1610006 | BGD CUP | beny |
So in the final result it should be smth like this(leaders, checkers together):
username| project TMNT | project LEON | project MAT |
--------+------------------------------------------+----------------+---------------------------------+
adam | ANM BLD(chk) | N/A | N/A | |
barikan | ANM BLD(ld), BGD CUP(ld), BGD CUP(chk) | ANM BLD(chk) | N/A |
beny | N/A | N/A | BGD CUP(ld), BGD CUP(chk) |
bob | N/A | ANM BLD(ld) | N/A |
Where ld= leader;
chk=checker
Should I LEFT JOIN both tables? Thanks for help

Assume you have table structure like this (sqlfiddle):
CREATE TABLE `user` (
`uid` INT(11) UNSIGNED NOT NULL PRIMARY KEY,
username VARCHAR(255) NOT NULL UNIQUE,
salary INT(11) UNSIGNED NOT NULL DEFAULT 0
);
CREATE TABLE project (
projectNo INT(11) UNSIGNED NOT NULL PRIMARY KEY,
title VARCHAR(255) NOT NULL UNIQUE
);
CREATE TABLE process (
projectNo INT(11) UNSIGNED NOT NULL,
process VARCHAR(255) NOT NULL,
proc_leader VARCHAR(255) NOT NULL,
FOREIGN KEY(projectNo) REFERENCES project(projectNo),
FOREIGN KEY(proc_leader) REFERENCES `user`(username)
);
CREATE TABLE proc_checker (
projectNo INT(11) UNSIGNED NOT NULL,
process VARCHAR(255) NOT NULL,
proc_checker VARCHAR(255) NOT NULL,
FOREIGN KEY(projectNo) REFERENCES project(projectNo),
FOREIGN KEY(proc_checker) REFERENCES `user`(username)
);
INSERT INTO `user`(uid, username, salary)
VALUES
(1, "bob", 0),
(2, "barikan", 0),
(3, "beny", 0),
(4, "adam", 0);
INSERT INTO project(projectNo, title)
VALUES
(1610004, "TMNT"),
(1610005, "LEON"),
(1610006, "MAT");
INSERT INTO process(projectNo, process, proc_leader)
VALUES
(1610004, "ANM BLD", "barikan"),
(1610004, "BGD CUP", "barikan"),
(1610005, "ANM BLD", "bob"),
(1610006, "BGD CUP", "beny");
INSERT INTO proc_checker(projectNo, process, proc_checker)
VALUES
(1610004, "ANM BLD", "adam"),
(1610004, "BGD CUP", "barikan"),
(1610005, "ANM BLD", "barikan"),
(1610006, "BGD CUP", "beny");
Result snippet with some commets is below:
<?php
// root root :)
$conn = mysqli_connect('127.0.0.1', 'root', 'root', 'test3');
// 1.Get data
// data for final table
// format is [username][projectNo] => [process1, process2, ..., processN]
$result = [];
// map project no to its title
$projectNoToTitle = [];
$sql = '
SELECT uid, username
FROM `user`
ORDER BY username
';
$query = mysqli_query($conn, $sql);
// for each user
while ($data = mysqli_fetch_assoc($query)) {
$sql = '
SELECT a.* FROM
(
(
-- select pairs project - leader
SELECT p.projectNo, p.title, CONCAT(pr.process, "(ld)") AS process
FROM project p
LEFT JOIN process pr ON p.projectNo = pr.projectNo
AND pr.proc_leader = "' . mysqli_real_escape_string($conn, $data['username']) . '"
)
-- union all means we union result of queries, which have structure
-- and don\'t remove duplicates (it\'s faster than UNION and
-- more logical because in our sittuation it won\'t be any duplicates)
UNION ALL
(
-- select pairs project - checker
SELECT p.projectNo, p.title, CONCAT(pch.process, "(chk)") AS process
FROM project p
LEFT JOIN proc_checker pch ON p.projectNo = pch.projectNo
AND pch.proc_checker = "' . mysqli_real_escape_string($conn, $data['username']) . '"
)
) AS a
ORDER BY a.projectNo
';
$query2 = mysqli_query($conn, $sql);
// for each project => process pair of user
while ($data2 = mysqli_fetch_assoc($query2)) {
$username = $data['username'];
$projectNo = $data2['projectNo'];
$projectTitle = $data2['title'];
$process = $data2['process'];
$projectNoToTitle[$projectNo] = $projectTitle;
if (!isset($result[$username])) {
$result[$username] = [];
}
if (!isset($result[$username][$projectNo])) {
$result[$username][$projectNo] = [];
}
if ($process) {
$result[$username][$projectNo][] = $process;
}
}
}
// \1.Get data
// 2. Output table
// create table header
// it's columns should contain all projects
if ($result) {
$header =
'<th>username</th>' .
array_reduce(array_values($projectNoToTitle), function ($p, $n) {
return $p . '<th>project ' . htmlspecialchars($n) . '</th>';
});
// output body
$body = '';
foreach ($result as $username => $usernameData) {
$row = '<td>' . htmlspecialchars($username) . '</td>';
foreach ($projectNoToTitle as $projectNo => $projectTitle) {
$r = (isset($usernameData[$projectNo]) && $usernameData[$projectNo])
? implode(', ', $usernameData[$projectNo])
: 'N/A';
$row .= '<td>' . htmlspecialchars($r) . '</td>';
}
$body .= "<tr>$row</tr>";
}
echo "<table><thead>$header</thead><tbody>$body</tbody></table>";
}
// \2. Output table
Feel free to modify if you found some bugs :)

Related

fetching all sub-list items under each row using foreach loop inside while loop

I have 2 tables in my product database:
product_list(id, Product_ID, Product_Name, Supplier),
product_option (id, Product_ID, Color, Size). both 'id's are primary keys with auto_increment.
I want to print all Color and Size values under each Product_Name (without repetition) that is from product_list table. I've been trying to figure out how to properly use foreach loop within while loop but now I'm out of related search result.
How my tables look:
product_list table:
|id | Product_ID | Product_Name | Supplier |
| -- | ---------- | ------------ | -------- |
| 1 |A1 | product1 | company1 |
| 2 |A2 | product2 | company2 |
| 3 |A3 | product3 | company3 |
| 4 |A4 | product4 | company4 |
product_option table:
|id |Product_ID | Color | Size |
| -- | --------- | ----- | ---- |
| 1 |A1 | red | S |
| 2 |A1 | red | M |
| 3 |A1 | black | S |
| 4 |A1 | black | M |
...
My expected output is:
| Product_ID | Product_Name | Supplier |
|:----------:|:------------:|:-----------:|
| A1 | Product1 | companyname |
| | red S | |
| | red M | |
| | black S | |
| | black M | |
| A2 | Product2 | companyname |
| | Large | |
Color and Size from product_option table with the same Product_ID will display under Product_Name row and Product_Name from product_list will only display once (instead of 4 times in the case of A1).
These are my code so far: (didn't write any table or styling for clean view)
include_once 'includes/dbh.inc.php';
$sql = "
SELECT
pl.Product_ID pid,
po.Product_ID poid,
pl.Product_Name,
po.Color color,
po.Size size,
pl.Supplier
FROM
product_list pl
LEFT JOIN
product_option po ON pl.Product_ID = po.Product_ID
ORDER BY
pl.Product_ID;";
$result = mysqli_query($conn, $sql) or die(mysqli_error());
if ($result -> num_rows > 0){
while ($row = $result -> fetch_assoc()) {
echo $row['pid'] . " " . $row['Product_Name'] . " " . $row['Supplier'] . "<br><br>";
if (!empty($row['color'] || $row['size'])) {
foreach ($row as $data) {
echo $data['color'] . ' /' . $data['size'] . '<br><br>';
}
}
}
}
Connection file: I use Xampp - phpmyadmin.
$dbServername = "localhost";
$dbUsername = "root";
$dbPassword = "";
$dbName = "product";
// Create Connection
$conn = new mysqli ($dbServername, $dbUsername, $dbPassword, $dbName);
// Check Connection
if ($conn -> connect_error) {
die("Connection Failed: " . $conn -> connect_error);
}
I'm ashamed to admit that the second 'if' and the foreach doesn't seem to work, and I don't know where to include the Product_ID match condition..
So far the output of this code is just 'A1 product1 company1', only the first result of the while loop.
From comment:
If it's ok for you to change how the data is being showed in the field, I suggest to make it horizontal with a query like this:
SELECT
pl.Product_ID pid,
po.Product_ID poid,
pl.Product_Name,
group_concat(concat(color,' ',size) separator ', ') AS Product_Name,
pl.supplier
FROM
product_list pl
LEFT JOIN
product_option po ON pl.Product_ID = po.Product_ID
GROUP BY pl.Product_ID, po.Product_ID,pl.Product_Name, pl.supplier
ORDER BY
pl.Product_ID;
Returns value like following:
+-----+------+---------------+---------------------------------+----------+
| pid | poid | Product_Name | Product_Name | supplier |
+-----+------+---------------+---------------------------------+----------+
| A1 | A1 | product1 | black M, black S, red M, red S | company1 |
.....
A fiddle of the tests
if ($result -> num_rows > 0)
mysqli_num_rows() This is a function so it is being ignored, it will always be "Zero" 0 so you will only get the indexed result which begins with '0'.. e.g [ 0,1,3]

update a column so duplicated values becomes unique

Column title has a lot of duplicated values, more than once.
I need to update the column so, for example if 'gold' is duplicated - it becomes 'gold 1', 'gold 2', etc.
Something like this:
$st = $db->query("select id, title from arts order by title asc");
$st->execute();
$x = 0;
while($row = $st->fetch()){
$title = $row['title'];
//if($title.is duplicated){
$x++;
$title .= ' ' . $x;
$stb = $db->query("update arts set title = '" . $title . "' where id = " . $row['id']);
$stb->execute();
}
}
Any help?
It would be more efficient to do this in pure SQL rather than using PHP. Here is an approach that uses window functions, available in MySQL 8.0.
You can use a subquery to count how many title duplicates exists for each record, and assign a rank to each record within groups of records having the same title. Then, you can JOIN the subquery with the table to update. Where more than one record exists, you can append the row number to every record in the group.
Query:
UPDATE arts a
INNER JOIN (
SELECT
id,
title,
COUNT(*) OVER(PARTITION BY title) cnt,
ROW_NUMBER() OVER(PARTITION BY title ORDER BY id) rn
FROM arts
) b ON a.id = b.id
SET a.title = CONCAT(a.title, b.rn)
WHERE cnt > 1;
Demo on DB Fiddle
Sample data:
| id | title |
| --- | ------ |
| 10 | silver |
| 20 | gold |
| 30 | gold |
| 40 | bronze |
| 50 | gold |
| 60 | bronze |
Results after running the update query:
| id | title |
| --- | ------- |
| 10 | silver |
| 20 | gold1 |
| 30 | gold2 |
| 40 | bronze1 |
| 50 | gold3 |
| 60 | bronze2 |
Please see below code that working for me
// Create connection
$conn = new mysqli($servername, $username, $password,$dbname);
// get all row
$sql = "select id, title from arts order by title asc";
$result = $conn->query($sql);
while ($row=$result->fetch_assoc()) {
$title=$row['title'];
// select where title is same
$sql = "select * from arts where title='".$title."'";
$result2 = $conn->query($sql);
// if number of row is greater then one
if ($result2->num_rows > 1){
$x=0;
while ($row2=$result2->fetch_assoc()) {
$id=$row2['id'];
// skip first row
if($x>0){
$newTitle=$title.' '.$x;
$uquery = "update arts set title='".$newTitle."' where title='".$title."' and id=$id";
$update = $conn->query($uquery);
}
$x++;
}
}
}
and after query run
This works in MySql 5.7:
update arts a inner join (
select * from (
select t.id,
(
select count(*) + 1 from arts
where id < t.id and title = t.title
) counter
from arts t
) t
) t on t.id = a.id
set a.title = concat(a.title, ' ', t.counter)
where a.title in (
select h.title from (
select title from arts
group by title
having count(*) > 1
) h
);
See the demo.
For data:
| id | title |
| --- | -------- |
| 1 | silver |
| 2 | gold |
| 3 | diamond |
| 4 | bronze |
| 5 | gold |
| 6 | bronze |
| 7 | gold |
the result is
| id | title |
| --- | -------- |
| 1 | silver |
| 2 | gold 1 |
| 3 | diamond |
| 4 | bronze 1 |
| 5 | gold 2 |
| 6 | bronze 2 |
| 7 | gold 3 |
I think It would be more efficient to do this in SQL too, but you may can do a function to validate the duplicate, something like this:
function isDuplicated( $title, $db ){
$dp = $db->query("SELECT * FROM arts WHERE title = $title");
if ( $dp->num_rows > 1)
return true;
return false;
}
$st = $db->query("select id, title from arts order by title asc");
$st->execute();
$x = 0;
while($row = $st->fetch()){
$title = $row['title'];
if( isDuplicated( $title, $db ) ){
$x++;
$title .= ' ' . $x;
$stb = $db->query("update arts set title = '" . $title . "' where id = " . $row['id']);
$stb->execute();
}
}

Duplicate entries in dropdown from mySQL

Okay so I'm new to mySQL. I'm sorry this is a very novice question. Essentially I have two tables, Associates, and keys.
The content is as follows:
associates:
id,
department,
associate,
date_added
keys:
id,
key_name,
date_added,
my code to make my dropdown is as follows:
<?php
mysql_connect('hostname', 'user', 'Password');
mysql_select_db('log');
$key_fetch = "SELECT `associates`.`department`,`associates`.`associate`,`keys`.`key_name` FROM associates , `keys` ORDER BY `key_name` DESC";
$results = mysql_query($key_fetch);
echo "<select name='key_name' size='5'>";
while ($row = mysql_fetch_array($results)) {
echo "<option value='" . $row['key_name'] . "'>" . $row['key_name'] . "</option>";
}
echo "</select>";
?>
The problem is I only have 5 keys and I have ten associates, and this creates duplicates in my dropdown and I can't fix it with SELECT DISTINCT, and I'm not too sure what else to try.
To visualize cartesian product based on above Q comments.
create table t1
( id int auto_increment primary key,
stuff1 varchar(50) not null
);
insert t1 (stuff1) values ('111.1'),('111.2'),('111.3');
create table t2
( id int auto_increment primary key,
stuff2 varchar(50) not null
);
insert t2 (stuff2) values ('222.1'),('222.2'),('222.3');
A: an explicit Join
select t1.id,t1.stuff1,t2.stuff2
from t1
join t2
on t2.id=t1.id;
+----+--------+--------+
| id | stuff1 | stuff2 |
+----+--------+--------+
| 1 | 111.1 | 222.1 |
| 2 | 111.2 | 222.2 |
| 3 | 111.3 | 222.3 |
+----+--------+--------+
B: An old-style cartesian product
select t1.id,t1.stuff1,t2.stuff2
from t1,t2;
+----+--------+--------+
| id | stuff1 | stuff2 |
+----+--------+--------+
| 1 | 111.1 | 222.1 |
| 2 | 111.2 | 222.1 |
| 3 | 111.3 | 222.1 |
| 1 | 111.1 | 222.2 |
| 2 | 111.2 | 222.2 |
| 3 | 111.3 | 222.2 |
| 1 | 111.1 | 222.3 |
| 2 | 111.2 | 222.3 |
| 3 | 111.3 | 222.3 |
+----+--------+--------+
9 rows in set (0.00 sec)
C: Cross join, same output as B:
select t1.id,t1.stuff1,t2.stuff2
from t1 cross join t2
So, your output, as I see it, is like B, 50 rows.

Query two tables to obtain a result in mysql + php query

I have two tables.
Table 1 contains fields :
| Ensemble_ID | varchar(50) | NO | PRI | | |
| Target | text | YES | | NULL | |
| Gene_Length | int(5) | YES | | NULL | |
| miRNA | varchar(50) | NO | PRI | | |
| position | int(4) | YES | | NULL | |
| Prediction | text | YES | | NULL | |
and my table 2 contains fields :
|Ensemble_ID | varchar(50) | NO | PRI | | |
| miRNA | varchar(50) | NO | PRI | | |
| miRNA_Length | int(2) | YES | | NULL | |
| mfe | decimal(2,0) | YES | | NULL | |
| pvalue | decimal(4,0) | YES | | NULL | |
| no_of_seeds | int(1) | YES | | NULL | |
I need a result like
|Ensemble_ID |Gene Length|miRNA|miRNA Length|mfe|P-value|Position|Prediction|No of Seeds|
I am newbie in mysql . Can anyone help me in writing a query out of it.
Help appreciated.
Here is my php attachment .. I could not obtain result since its showing query error
<?php
$a = $_REQUEST["miRNA"];
$b = $_REQUEST["target"];
// $result = db::table("`table`") -> pluck("*") -> where("miRNA",$a) -> select() -> get();
$mysqli = new mysqli("localhost", "root", "password", "mysql");
$a = $mysqli -> escape_string($a);
$b = $mysqli -> escape_string($b);
$a = $mysqli->query("SELECT * FROM bio3 WHERE miRNA = '$a' AND Target LIKE '%$b' INNER JOIN bio4 on bio3.ensemble_id = bio4.ensemble_id ORDER BY bio4.pvalue ASC;");
// $result = $a -> fetch_assoc();
$i = 0;
while ($row = $a -> fetch_assoc()) {
$result[$i] = $row;
$i++;
}
$mysqli->close();
for($a=0;$a<sizeof($result);$a++){
print '<tr>
<td>'.htmlentities($result[$a]["Target"]).'</td>
<td>'.htmlentities($result[$a]["Gene Length"]).'</td>
<td>'.htmlentities($result[$a]["miRNA"]).'</td>
<td>'.htmlentities($result[$a]["miRNA Length"]).'</td>
<td>'.htmlentities($result[$a]["mfe"]).'</td>
<td>'.htmlentities($result[$a]["pvalue"]).'</td>
<td>'.htmlentities($result[$a]["position"]).'</td>
<td>'.htmlentities($result[$a]["Prediction"]).'</td>
<td>'.htmlentities($result[$a]["No of Seeds"]).'</td>
</tr>';
}
?>
Join two tables like:
SELECT t1.Ensemble_ID, t1.Gene_Length, t1.miRNA, t2.miRNA_Length, t2.mfe, t2.pvalue, t1.position, t1.Prediction, t2.no_of_seeds
FROM table1 t1 INNER JOIN table2 t2
ON t1.Ensemble_ID = t2.Ensemble_ID
WHERE t1.miRNA = 'abc'
AND t1.target LIKE '%xyz'
ORDER BY t2.pvalue ASC;
Use Join to get your desired result. See below:
SELECT
A.Ensemble_ID,
Gene_Length,
A.miRNA,
miRNA_Length,
mfe,
Pvalue,
Position,
Prediction,
No_of_Seeds,
FROM Table1 A
JOIN
Table2 A ON A.Ensemble_ID=B.Ensemble_ID
You can have your query like this...
SELECT
A.Ensemble_ID,
Gene_Length,
A.miRNA,
B.miRNA_Length,
B.mfe,
B.Pvalue,
Position,
Prediction,
No_of_Seeds,
FROM Table1 A
JOIN
Table2 B ON A.miRNA=B.miRNA

PHP mysql LEFT JOIN output

I have php-script running on top of apache. Every time when user goes to specific URL, he/she will get csv-file.
Column names are fetched like this (thanks to Daniel Figueroa :)
$csv_output .= "\n";
// get the column name from the first DB (ins.data)
mysql_select_db($db, $link) or die("Can not connect to DB1.");
$result = mysql_query("SHOW COLUMNS FROM ".$table." WHERE Field NOT IN
('ID','Key','Text')");
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
// get the column names from the second DB (Cu.data)
mysql_select_db($db2, $link) or die("Can not connect to DB2.");
$result = mysql_query("SHOW COLUMNS FROM ".$table2." ");
;
$i = 0;
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field']."; ";
$i++;
}
}
$csv_output .= "\n";
Actual query on PHP-script goes like this:
$values = mysql_query(" SELECT ins.data.`Date`, ins.data.`Number`,
ins.data.`Email`, ins.data.`TargetId`, ins.data.`CSW`,
ins.data.`TSW`, ins.data.`CType`,
Cu.data.`Cus`, Cu.data.`Co`,Cu.data.`Ci`,
Cu.data.`SID`, Cu.data.`SType`
FROM ins.data
LEFT JOIN Cu.data ON (ins.data.TargetId = Cu.data.TargetID)
ORDER BY ins.data.ID DESC");
Output of 'desc':
mysql> desc ins.data;
+-------------------+------------------+------+-----+---------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------------+------------------+------+-----+---------------------+----------------+
| ID | int(10) unsigned | NO | PRI | NULL | auto_increment |
| Date | timestamp | NO | | 0000-00-00 00:00:00 | |
| Number | text | NO | | NULL | |
| Text | text | NO | | NULL | |
| Email | text | NO | | NULL | |
| TargetId | varchar(20) | NO | | NULL | |
| CSW | text | NO | | NULL | |
| TSW | text | NO | | NULL | |
| Key | text | NO | | NULL | |
| CType | text | NO | | NULL | |
+-------------------+------------------+------+-----+---------------------+----------------+
10 rows in set (0.00 sec)
mysql> desc Cu.data;
+----------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------------+------+-----+---------+-------+
| Title | decimal(15,0) | NO | | NULL | |
| Cu | text | NO | | NULL | |
| Co | text | NO | | NULL | |
| Ci | text | NO | | NULL | |
| SID | text | NO | | NULL | |
| TargetID | varchar(20) | NO | MUL | NULL | |
| SType | text | NO | | NULL | |
| empty1 | int(11) | NO | | NULL | |
| empty2 | int(11) | NO | | NULL | |
| empty3 | int(11) | NO | | NULL | |
| empty4 | int(11) | NO | | NULL | |
| empty5 | int(11) | NO | | NULL | |
| empty6 | int(11) | NO | | NULL | |
| empty7 | int(11) | NO | | NULL | |
+----------+---------------+------+-----+---------+-------+
12 rows in set (0.00 sec)
UPDATE 3:
This is no more NATURAL LEFT JOIN-issue. Replaced with LEFT JOIN.
Added fields empty1-5 to ins.data to get data to csv-file. Without fields empty1-5, only data from first db (ins.data) was on csv.file.
Now i have data on all fields but field (or column names on excel) names on csv are on wrong order and not wanted fields (columns) are visible like Title and empty1-5.
Any ideas how to fix this? Some other way to get Field names to csv-file without "SHOW COLUMNS"?
I could write with 'echo' in the beginning of csv-file values what i want. ie
"Date; Number; Email; TargetID, CSW; TSW; CType; Cu; SID; Co; Ci; SType;" but i am so newbie with PHP that i don't know how :(
Another issue is that if field ID is first column on excel, excel cannot handle that and it must be excluded from SHOW COLUMNS output.
UPDATE4: Added more empty-fields to DB2 (Cu.data) and reordered SQL-query, now all values are visible and on right order.
EDIT
First of all, your table naming schema is weird and unusual... but assuming I understand it correctly then this query should work (if it does not then rename your tables without the dots (periods) to make things less confusing:
mysql_query('SELECT ins.data.Date, ins.data.Number, ins.data.Email, ins.data.TID, ins.data.CSW, ins.data.TSW, ins.data.CType, CU.data.SID, cu.data.SType, cu.data.CU, cu.data.CO, cu.data.Ci, FROM ins.data, cu.data ORDER BY ins.data.ID DESC');
According to to the mysql_query function reference, data should not end with a semicolon when using mysql_query in PHP... i never put the semicolon in there so I don't ever have a problem, that's what I initially noticed with your script (as I said i've never tried it so I don't know if thats the issue). Should be:
$values = mysql_query("SELECT Date, Number, Email, TID, CSW, TSW, CType, SID, SType, Cu, Co, Ci FROM ins.data NATURAL LEFT JOIN Cu.data ORDER BY ID DESC");
Also, when doing JOINS, usually you specify what column belongs to what table... like in the standard mysql example here:
<?php
// Make a MySQL Connection
// Construct our join query
$query = "SELECT family.Position, food.Meal ".
"FROM family LEFT JOIN food ".
"ON family.Position = food.Position";
$result = mysql_query($query) or die(mysql_error());
// Print out the contents of each row into a table
while($row = mysql_fetch_array($result)){
echo $row['Position']. " - ". $row['Meal'];
echo "<br />";
}
?>
I don't always use the JOIN commands either... you can use an alternative syntax like so:
mysql_query('SELECT ... FROM t1, t2, t3 WHERE t1.b = t2.b AND t2.c = t3.c AND t1.a = t3.a');
Try putting aliases on table names. It will make the query more readable, too:
SELECT
i.`Date`, i.Number, i.Email, i.TID, i.CSW, i.TSW, i.CType,
c.Cu, c.Co, c.Ci, c.SID, c.TID, c.SType
FROM
ins.data AS i
LEFT JOIN
Cu.data AS c
ON i.TID = c.TID
ORDER BY
i.ID DESC ;

Categories