Solved

Data from one MySQL table to be used in another table

Posted on 2013-01-06
11
247 Views
Last Modified: 2013-01-07
SUMMARY:
When displaying the data from TABLE2, replace the number in TABLE2's TOPIC field with the associated TOPIC_NAME from TABLE1.

DETAILS:
I have 2 tables in the same MySQL DB. I need help populating the array from TABLE1 to be used by TABLE2 (if I even need to use an array).  If it matters, I'm using PDO.

No UPDATE or INSERT... just display the words instead of the number.

============================
TABLE1 is a list of topics.

TABLE1 Syntax:
ID,TOPIC_NUM,TOPIC_NAME

Sample Record from TABLE1:
1,Topic1
2,Topic2
etc...
============================
TABLE2 is a list of individual people and associated data.

TABLE2 Syntax:
ID,NAME,STATE,TOPIC,YEAR

Sample Record from TABLE2:
1,John Smith,MA,2,2005
2,Jane Doe,AZ,1,2009
etc...
============================

FYI:  In the Sample Record above, the number after the State abbreviation is the TOPIC.

Here's my code:
(*I'm new to PDO.  If you see anything that requires corrections, etc., please let me know.)

<?php 

try {
	$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $db->exec("SET CHARACTER SET utf8");

// TABLE1
$tablename1 = 'topics';
$topics_col1 = 'TOPIC_NUM';
$topics_col2 = 'TOPIC_NAME';

// TABLE2
$tablename2 = 'people';
$items_col1 = 'NAME';
$items_col2 = 'STATE';
$items_col3 = 'TOPIC';
$items_col4 = 'YEAR';

$items_q = "SELECT $items_col1, $items_col2, $items_col3 FROM $tablename2";
$items = $db->query($items_q);

foreach ($items as $items_row) {
?>
<h2><?php 
/*

THIS IS WHERE THE TOPIC_NAME FROM TABLE1 SHOULD DISPLAY

*/
?></h2>
<p>
<?php echo $items_row[$items_col1];?>
<br />
<?php echo $items_row[$items_col2];?>
<br />
<?php echo $items_row[$items_col3];?>
<br />
<?php echo $items_row[$items_col4];?>
</p>

<?php 	
} // end FOREACH
	$db = null; // close the database connection
} // end TRY
catch(PDOException $e) {
	echo '<span class="error">ERROR:</span><br />'.$e->getMessage() . "<br />";
	die();
} // end CATCH
?>

Open in new window

0
Comment
Question by:mar2195
  • 5
  • 4
  • 2
11 Comments
 
LVL 24

Accepted Solution

by:
johanntagle earned 500 total points
ID: 38748202
Learn about SQL joins.  Change your query to:

SELECT $items_col1, $items_col2, $topics_col2
FROM $tablename2 JOIN $tablename1 on ($items_col3 = $topics_col1)

This way the db will already return the topic string instead of number.  Then just adjust your script to display $items_row[$topics_col1] instead of $items_row[$items_col3]
0
 
LVL 5

Expert Comment

by:Imran Saeed
ID: 38750077
Here is a reference from other forum.

http://sqlfiddle.com/?_escaped_fragment_=2/d7be9/1#!2/d7be9/1

simply use INNER JOIN

SELECT  a.ID, a.NAME, a.STATE, b.TOPIC_NAME , a.YEAR
FROM    table2 a
        INNER JOIN table1 b
            ON  a.topic = b.topic_num
0
 

Author Comment

by:mar2195
ID: 38750159
I would welcome input as to which of these solutions is recommended.
0
 
LVL 24

Expert Comment

by:johanntagle
ID: 38750171
We basically gave you the same solution.  If you look closely the two queries presented use the same logic.  I just gave the extra comment that you also need to make changes in your PHP code as well.
0
 

Author Comment

by:mar2195
ID: 38753278
1.  Is xImran's solution supposed to be literal?  Meaning... COPY/PASTE the code (using the "a.xxxx" "b.xxxx") and it will execute correctly or is this an example of the JOIN INNER method?  ... he was simply giving me an example using the "a" "b" ?  I would like to know if using the "dot" method he suggests is another way to code this.


2.  The solution provided by johanntagle works perfectly - except for an error/typo in the actual display of the output.  It should be:

<?php echo 'TOPIC: '.$items_row[$topics_col2];?>

Open in new window

0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 24

Expert Comment

by:johanntagle
ID: 38753294
xImran's solution still needed to be adapted to use your php variables.  But other than that - "a" and "b" are just aliases, which are useful if the names of the tables involved are quite long.  And using a.ID, etc in the select clause is optional unless the tables involved have commonly named columns.  "INNER JOIN" and just "JOIN" are the same.  That's why I said the logic presented by both solutions are the same.
0
 

Author Comment

by:mar2195
ID: 38753316
So ... from my original coding example, I would code this as:

SELECT $tablename1.ID, $tablename1.NAME, $tablename1.STATE, $tablename2.TOPIC_NAME , $tablename1.YEAR

Correct?
0
 
LVL 24

Expert Comment

by:johanntagle
ID: 38753322
Yes
0
 
LVL 5

Expert Comment

by:Imran Saeed
ID: 38753323
Yes it should work. Have your tested it yet?
0
 

Author Comment

by:mar2195
ID: 38753365
For future reference, here is the final version of this script.  I have included a commented section that shows the alternative coding method for the query using the "dot" method.

I have tested this script (using both methods) and it functions perfectly.

As always, thanks for the forums' experts help!


<?php 

try {

	$db = new PDO("mysql:host=$hostname;dbname=$database", $username, $password);
	
	$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $db->exec("SET CHARACTER SET utf8");


// TABLE1
$tablename1 = 'topics';
$topics_col1 = 'TOPIC_NUM';
$topics_col2 = 'TOPIC_NAME';

// TABLE2
$tablename2 = 'people';
$items_col1 = 'NAME';
$items_col2 = 'STATE';
$items_col3 = 'TOPIC';
$items_col4 = 'YEAR';


$items_q = "SELECT $items_col1, $items_col2, $items_col3, $items_col4, $topics_col2 
FROM $tablename2 
JOIN $tablename1 on ($items_col3 = $topics_col1)";

/* ALTERNATE METHOD FOR QUERY

(*No need for all of the vars above using this method.)
$items_q = "SELECT $tablename2.NAME, $tablename2.STATE, $tablename2.TOPIC, $tablename2.YEAR, $tablename1.TOPIC_NAME 
FROM $tablename2 
INNER JOIN $tablename1 on ($tablename2.TOPIC = $tablename1.TOPIC_NUM)";

*/

$items = $db->query($items_q);

foreach ($items as $items_row) {
?>

<h2><?php echo $items_row[$topics_col2];?></h2>

<p>
<?php echo $items_row[$items_col1];?>
<br />
<?php echo $items_row[$items_col2];?>
<br />
<?php echo $items_row[$items_col3];?>
<br />
<?php echo $items_row[$items_col4];?>
</p>

<?php 	
} // end FOREACH

	$db = null; // close the database connection

} // end TRY
catch(PDOException $e) {
	echo '<span class="error">ERROR:</span><br />'.$e->getMessage() . "<br />";
	die();
} // end CATCH

?>

Open in new window

0
 

Author Closing Comment

by:mar2195
ID: 38753369
As you can see by the thread of this topic, johanntagle's help was invaluable!  Thank you.
0

Featured Post

Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
mySql Syntax 7 32
Wordpress update causing pages to crash 1 21
Change password through link 1 12
Datepicker in PHP 9 14
Popularity Can Be Measured Sometimes we deal with questions of popularity, and we need a way to collect opinions from our clients.  This article shows a simple teaching example of how we might elect a favorite color by letting our clients vote for …
Since pre-biblical times, humans have sought ways to keep secrets, and share the secrets selectively.  This article explores the ways PHP can be used to hide and encrypt information.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now