Building my own ecommerce website and within the back-end ive created a form where admins can create certain product filter groups (colours for example).
When im trying to insert the new table into the database im using a foreach loop to make sure no blank entries are inserted (and to prevent these blank entries causing issues).
However I have encountered a syntax issue and i've researched this fully without any success.
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'entry_date DEFAULT CURRENT_TIMESTAMP)' at line 1
My code:
// GROUP NAME PROVIDED
$group_name = $_POST['g_name'];
// FILTER OPTIONS PROVIDED
$filter_1 = $_POST['filter_1'];
$filter_2 = $_POST['filter_2'];
$filter_3 = $_POST['filter_3'];
$filter_4 = $_POST['filter_4'];
$filter_5 = $_POST['filter_5'];
$filter_6 = $_POST['filter_6'];
$filter_7 = $_POST['filter_7'];
$filter_8 = $_POST['filter_8'];
$filter_9 = $_POST['filter_9'];
$filter_10 = $_POST['filter_10'];
$filter_11 = $_POST['filter_11'];
include '../connection.php';
$query = "CREATE TABLE $group_name (
entry_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
product_id VARCHAR(255) NOT NULL,";
$newarray = array($filter_1,$filter_2,$filter_3,$filter_4,$filter_5,$filter_6,$filter_7,$filter_8,$filter_9,$filter_10,$filter_11);
// For each value that is not NULL
foreach ($newarray as $key => $value) {
if (is_null($value) === false) {
$new_array[$key] = $value;
echo $value;
$query = "$value VARCHAR(255) NOT NULL,";
}
}
$query= "entry_date DEFAULT CURRENT_TIMESTAMP)";
// Checking if query was successful or not
if (mysqli_query($connection, $query )) {
echo "Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($connection);
}
mysqli_close($connection);
I've tried different variations to the timestamp insertion but had no luck.
It's worth noting that I have also split my query up so that the foreach loop can be included.
Any help would be appreciated!
P.S I know this code is open to SQL injection, i want to get it functioning before making it secure!
Thanks.
Stan.
Working code:
// GROUP NAME PROVIDED
$group_name = $_POST['g_name'];
// FILTER OPTIONS PROVIDED
$filter_1 = $_POST['filter_1'];
$filter_2 = $_POST['filter_2'];
$filter_3 = $_POST['filter_3'];
$filter_4 = $_POST['filter_4'];
$filter_5 = $_POST['filter_5'];
$filter_6 = $_POST['filter_6'];
$filter_7 = $_POST['filter_7'];
$filter_8 = $_POST['filter_8'];
$filter_9 = $_POST['filter_9'];
$filter_10 = $_POST['filter_10'];
$filter_11 = $_POST['filter_11'];
include '../connection.php';
$query = "CREATE TABLE $group_name (
entry_id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
product_name VARCHAR(255) NOT NULL,
product_id VARCHAR(255) NOT NULL,";
$newarray = array($filter_1,$filter_2,$filter_3,$filter_4,$filter_5,$filter_6,$filter_7,$filter_8,$filter_9,$filter_10,$filter_11);
$filtered_array = array_filter($newarray);
// For each value that is not NULL
foreach ($filtered_array as $key => $value) {
$filtered_array[$key] = $value;
echo $value;
$query .= "$value VARCHAR(255) NOT NULL,";
}
$query .= "entry_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP)";
echo "<br><br>".$query;
// Checking if query was successful or not
if (mysqli_query($connection, $query )) {
echo "Table created successfully";
} else {
echo "Error creating table: " . mysqli_error($connection);
}
mysqli_close($connection);
you are missing the type:
entry_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
or
entry_date DATETIME DEFAULT CURRENT_TIMESTAMP
you overwrite your variable $query
use =. if you want to accumulate data in a string
$query =. "entry_date DEFAULT CURRENT_TIMESTAMP)";
buy the way it's not a really good style to store it like this
Related
This question already has an answer here:
Syntax error due to using a reserved word as a table or column name in MySQL
(1 answer)
Closed 5 years ago.
So, I'm having trouble getting data into this table. I have a similar table setup for memberships. If I change the insert into query to membership from join everything works perfectly, but as soon as I change the table to join it stops working. The table seems to be properly setup since it's basically the same as my membership table, but for some reason data will not insert. I can't think of what could be causing my problem so I'm coming to the experts.
Note that this code all works perfectly when going into a different table. Thanks in advance.
if ( isset($_POST['btn-join']) ) {
// clean user inputs to prevent sql injections
$groupID = trim($_POST['groupID']);
$groupID = strip_tags($groupID);
$groupID = htmlspecialchars($groupID);
$teamname = trim($_POST['teamname']);
$teamname = strip_tags($teamname);
$teamname = htmlspecialchars($teamname);
// Query groups to set group name
$query2 = "SELECT groupName FROM groups WHERE groupID='$groupID'";
$result2 = mysqli_query($con,$query2);
$groupquery = mysqli_fetch_array($result2,MYSQLI_ASSOC);
$groupname = $groupquery['groupName'];
// groupID validation
if (empty($groupID)) {
$error = true;
$groupIDError = "Please enter valid Group ID.";
} else {
// check email exist or not
$query3 = "SELECT groupID FROM groups WHERE groupID='$groupID'";
$result3 = mysqli_query($con,$query3);
$count = mysqli_num_rows($result3);
if($count!=1){
$error = true;
$groupIDError = "Provided Group does not exist.";
}
}
// basic teamname validation
if (empty($teamname)) {
$error = true;
$nameError = "Please enter your Team Name.";
} else if (strlen($teamname) < 3) {
$error = true;
$nameError = "Team Name must have at least 3 characters.";
}
// if there's no error, continue to signup
if( !$error ) {
$query = "INSERT INTO join(groupID,userID,groupName,teamName) VALUES('$groupID','$userID','$groupname','$teamname')";
$membership = mysqli_query($con,$query);
if ($membership) {
$errTyp = "success";
$errMSG = "Account successfully updated";
header("Location: dashboard.php");
} else {
$errTyp = "danger";
$errMSG = "Something went wrong, try again later...";
}
}
}
SQL:
CREATE TABLE IF NOT EXISTS `join` (
`jID` int(11) NOT NULL AUTO_INCREMENT,
`groupID` varchar(32) NOT NULL,
`userID` varchar(32) NOT NULL,
`groupName` varchar(35) NOT NULL,
`teamName` varchar(32) NOT NULL,
`joinDate` datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`jID`),
UNIQUE KEY `groupID` (`groupID`,`userID`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
join is a reserved word in SQL. To avoid these sorts of issues, use backticks around table and column names:
$query = "INSERT INTO `join`(`groupID`,`userID`,`groupName`,`teamName`) VALUES('$groupID','$userID','$groupname','$teamname')";
$membership = mysqli_query($con,$query);
As a side note, you should really rewrite this query to use a prepared statement and then bind the variables to it. This is a SQL injection waiting to happen.
Description: I'm creating the database name automatically consisting of main table name and appending the full name relative to what is selected in dropdown menus.
Code:
if ($leagueSelect === $result['leagueName'] && $divisionSelect === $result['divisionID'] && $tourType === 'robin') {
$tableName = "footleague_".$leagueSelect.$divisionSelect;
/****CREATE TABLE****/
$db = JFactory::getDBO();
$query = $db->getQuery(true);
$query = "CREATE TABLE IF NOT EXISTS `".( $tableName )."` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`round` TEXT NULL,
`logoHome` TEXT NULL,
`home` TEXT NULL,
`usrHome` TEXT NULL,
`scoreHome` INT(11) NULL,
`scoreAway` INT(11) NULL,
`logoAway` TEXT NULL,
`away` TEXT NULL,
`usrAway` TEXT NULL,
`confirm` INT(11),
PRIMARY KEY (`id`)
)";
$db->setQuery($query);
$result = $db->execute();
if ($result == true) {
echo 'Table created successfully!';
}else{
echo "Something went wrong with table creation. Please try again.";
}
}
This works perfectly and it creates a new table and all of the columns.
The problem comes when storing data into this table. I need to be able to take the table name which is stored in a variable and store the data into it. Same as in CREATE TABLE.
I tried it like this:
$query = "INSERT INTO ".$tableName." (round, logoHome, home, usrHome, logoAway, away, usrAway),
VALUES ('".$round."' , '".$logoHome."' , '".$home."' , '".$usrHome."' , '".$logoAway."' , '".$away."' , '".$usrAway."')";
$db->setQuery($query);
$result = $db->execute();
...but it doesn't give me any errors and it doesn't store the data.
I tried also with stdClass object but I don't know how to get the table name in there:
$data = new stdClass();
$data->round = $round;
$data->home = $home;
$data->usrHome = $usrHome;
$data->logoHome = $logoHome;
$data->away = $away;
$data->usrAway = $usrAway;
$data->logoAway = $logoAway;
$db = JFactory::getDBO();
$db->insertObject($tableName, $data);
How can I get this to work?
Thank you.
I solved it like this:
$data = new stdClass();
$data->round = $round;
$data->home = $home;
$data->usrHome = $usrHome;
$data->logoHome = $logoHome;
$data->away = $away;
$data->usrAway = $usrAway;
$data->logoAway = $logoAway;
$db = JFactory::getDBO();
$db->insertObject($tableName, $data);
if ($result == true) {
echo 'Tournament was created successfully!';
}else{
echo 'ERROR!';
}
I have two tables. In Table 1, I have around 400K rows where each row includes a paragraph of text that can be up to 50 sentences. In Table 2 I have a lexicon of 80k words with a score that I need for the coding of each word of each paragraph.
The whole point of my php script is to explode each paragraph of text into as many words as needed, then lookup into the lexicon for each word what the score is, and end up calculating the total score for all of the words for each row.
My strategy so far was to have a script that did the following:
Connect to the database, Table 1
While Loop, one row after another
For the current row, explode the paragraph.
For each word, look up into Table 2 if the word exists and return the score.
Ending up with a total score for the current row.
Updating Table 1 with the total score for the current paragraph.
Going back to point number 2.
My code works but is not efficient. The problem is that the script is so slow that letting it run for an hour just calculates the first 500 rows. That's a problem because I have 400K rows. I will need this script for other projects.
What would you advise me to do to make this process less intense?
<?php
//Include functions
include "functions.php";
ini_set('max_execution_time', 9000000);
echo 'Time Limit = ' . ini_get('max_execution_time');
$db='senate';
//Function to search into the array lexicon
function searchForId($id, $array) {
foreach ($array as $key2 => $val) {
if ($val['word'] === $id) {
return $key2;
}
}
return null;
}
// tags to remove
$remove = array('{J}','{/J}','{N}','{/N}','{V}','{/V}','{RB}','{/RB}');
$x=1;
//Conecting the database
if (!$conn) {
die('Not connected : ' . mysql_error());}
// Choose the current db
mysql_select_db($db);
//Slurps the lexicon into an array
$sql = "SELECT word, score FROM concreteness";
$resultconcreteness = mysql_query($sql) or die(mysql_error());
$array = array();
while($row = mysql_fetch_assoc($resultconcreteness)) {
$array[] = $row;
}
//loop
while($x<=500000) {
$data = mysql_query("SELECT `key`, `tagged` FROM speechesLCMcoded WHERE `key`='$x'") or die(mysql_error());
// puts the "data" info into the $info array
$info = mysql_fetch_array( $data);
$tagged=$info['tagged'];
unset($weight);
unset($count);
$weight=0;
$count=0;
// Print out the contents of the entry
Print "<b>Key:</b> ".$info['key'] . " <br>";
// Explodes the sentence
$speech = explode(" ", $tagged);
// Loop every word
foreach($speech as $word) {
//Check if string contains our tag
if(!preg_match('/({V}|{J}|{N}|{RB})/', $word, $matches)) {} else{
//Removes our tags
$word = str_replace($remove, "", $word);
$id = searchForId($word, $array);
// print "ID: " . $id . "<br>";
// print "Word: " . $array[$id]['word'] . "<br>";
// print "Score: " . $array[$id]['score'] . "<br>";
$weight=$weight+$array[$id]['score'];
$count=$count +1;
// print "Weight: " . $weight . "<br>";
// print "Count: " . $count . "<br>";
}
}
$sql = "UPDATE speechesLCMcoded SET weight='$weight', count='$count' WHERE `key`='$x';" ;
$retval = mysql_query( $sql, $conn );
if(! $retval )
{die('Could not update data: ' . mysql_error());}
echo "Updated data successfully\n";
ob_flush();
flush();
//Increase the loop by one
$x=$x+1;
}?>
Here is the index:
CREATE TABLE `speechesLCMcoded` (
`key` int(11) NOT NULL AUTO_INCREMENT,
`speaker_state` varchar(100) NOT NULL,
`speaker_first` varchar(100) NOT NULL,
`congress` varchar(100) NOT NULL,
`title` varchar(100) NOT NULL,
`origin_url` varchar(100) NOT NULL,
`number` varchar(100) NOT NULL,
`order` varchar(100) NOT NULL,
`volume` varchar(100) NOT NULL,
`chamber` varchar(100) NOT NULL,
`session` varchar(100) NOT NULL,
`id` varchar(100) NOT NULL,
`raw` mediumtext NOT NULL,
`capitolwords_url` varchar(100) NOT NULL,
`speaker_party` varchar(100) NOT NULL,
`date` varchar(100) NOT NULL,
`bills` varchar(100) NOT NULL,
`bioguide_id` varchar(100) NOT NULL,
`pages` varchar(100) NOT NULL,
`speaker_last` varchar(100) NOT NULL,
`speaker_raw` varchar(100) NOT NULL,
`tagged` mediumtext NOT NULL,
`adjectives` varchar(10) NOT NULL,
`verbs` varchar(10) NOT NULL,
`nouns` varchar(10) NOT NULL,
`weight` varchar(50) NOT NULL,
`count` varchar(50) NOT NULL,
PRIMARY KEY (`key`)
) ENGINE=InnoDB AUTO_INCREMENT=408344 DEFAULT CHARSET=latin1
You have a fairly small reference table (your lexicon) and an enormous corpus of text (table 1).
If I were you I would start your program by slurping the entire lexicon from the table into a php array in memory. Even if all your words are 20 characters in length this will only take a dozen or so megabytes of RAM.
Then do your step 4 by looking up the words in memory rather than by using a SQL query. Your inner loop (for each word) will be much faster, and equally as accurate.
Be careful about one thing, though. You'll need to normalize the words in your lexicon by converting them to lower case if you are to replicate the case-insensitive lookup behavior of MySQL.
Edit after seeing your code
Some pro tips:
Indent your code properly so you can see the structure of your loops at a glance.
Remember that passing data to functions takes time.
PHP arrays are associative. You can do $value = $array[$key]. This is fast. You don't have to search an array linearly. You're doing that once per word !!
Prepared statements are good.
Repeating an SQL statement when you could read the next row from its result set is bad.
Streaming result sets is good.
The mysql_ set of function calls are deprecated and despised by their developers, and everybody else, for good reasons.
There's way too much going on in your loops.
What you need is this:
First of all, switch to using mysqli_ from using mysql_ interfaces. Just do it. mysql_ is too slow, old, and crufty.
$db = new mysqli("host", "user", "password", "database");
Second, change the way you are loading your lexicon, to optimize the whole associative-array dealio.
$lookup = array();
//Slurps the lexicon into an array, streaming it row by row
$sql = "SELECT word, score FROM concreteness";
$db->real_query($sql) || die $db->error;
$lkup = $db->use_result();
while ($row = $lkup->fetch_row()) {
$lookup[strtolower($row[0])] = $row[1];
}
$lkup->close();
This gives you an associative array called $lookup. If you have a $word, you can find its weight value this way. This is fast. What you have in your example code is very slow. Notice that the keys are all converted to lower case both when they are created and when words are looked up. Don't put this in a function if you can avoid it, for performance reasons.
if (array_key_exists( strtolower($word), $lookup )) {
$weight += $lookup[strtolower($word)]; /* accumulate weight */
$count ++; /* increment count */
}
else {
/* the word was not found in your lexicon. handle as needed */
}
Finally, you need to optimize your querying of the rows of your text corpus, and its updating. I believe you should do that using prepared statements.
Here's how that will go.
Near the beginning of your program, place this code.
$previouskey = -1;
if (/* you aren't starting at the beginning */) {
$previouskey = /* the last successfully processed row */
}
$get_stmt = $db->prepare('SELECT `key`, `tagged`
FROM speechesLCMcoded
WHERE `key` > ?
ORDER BY `key` LIMIT 1' );
$post_stmt = $db->prepare ('UPDATE speechesLCMcoded
SET weight=?,
count=?
WHERE `key`=?' );
These give you two ready-to-use statements for your processing.
Notice that the $get_stmt retrieves the first key you haven't yet processed. This will work even if you have some missing keys. Always good. This will be decently efficient because you have an index on your key column.
So here's what your loop ends up looking like:
$weight = 0;
$count = 0;
$key = 0;
$tagged = '';
/* bind parameters and results to the get statement */
$get_stmt->bind_result($key, $tagged);
$get_stmt->bind_param('i', $previouskey);
/* bind parameters to the post statement */
$post_stmt->bind_param('iii',$weight, $count, $key);
$done = false;
while ( !$done ) {
$get_stmt->execute();
if ($get_stmt->fetch()) {
/* do everything word - by - word here on the $tagged string */
/* do the post statement to store the results */
$post_stmt->execute();
/* update the previous key prior to next iteration */
$previouskey = $key;
$get_stmt->reset();
$post_stmt->reset();
} /* end if fetch */
else {
/* no result returned! we are done! */
$done = true;
}
} /* end while not done */
This should get you down to subsecond processing per row.
First and obvious optimization is like this:
include "functions.php";
set_time_limit(0); // NOTE: no time limit
if (!$conn)
die('Not connected : ' . mysql_error());
$remove = array('{J}','{/J}','{N}','{/N}','{V}','{/V}','{RB}','{/RB}'); // tags to remove
$db = 'senate';
mysql_select_db($db);
$resultconcreteness = mysql_query('SELECT `word`, `score` FROM `concreteness`') or die(mysql_error());
$array = array(); // NOTE: init score cache
while($row = mysql_fetch_assoc($resultconcreteness))
$array[strtolower($row['word'])] = $row['score']; // NOTE: php array as hashmap
mysql_free_result($resultconcreteness);
$data = mysql_query('SELECT `key`, `tagged` FROM `speechesLCMcoded`') or die(mysql_error()); // NOTE: single query instead of multiple
while ($row = mysql_fetch_assoc($data)) {
$key = $row['key'];
$tagged = $row['tagged'];
$weight = $count = 0;
$speech = explode(' ', $tagged);
foreach ($speech as $word) {
if (preg_match('/({V}|{J}|{N}|{RB})/', $word, $matches)) {
$weight += $array[strtolower(str_replace($remove, '', $word))]; // NOTE: quick access to word's score
$count++;
}
}
mysql_query('UPDATE `speechesLCMcoded` SET `weight`='.$weight.', `count`='.$count.' WHERE `key`='.$key, $conn) or die(mysql_error());
}
mysql_free_result($data);
Check the comments with NOTE:
But for 400K rows it sill will take some time, at least because you have to update each row, this means 400K updates.
Possible future optimizations:
Make this script get arguments like start offset and length (pass them to mysql LIMIT), so you will be able to run several scripts to process different blocks of table at the same time
Instead of updates - generate file with data, then use LOAD DATA INFILE to replace your table, it could be faster neither 400K updates
How can I create a PHP function that will gather all database values and then then return each output as a variable. I have the code to SELECT one value from the database and display it as a variable in PHP. Here is the code:
function GetWebsiteName() {
$sql = "SELECT value FROM configuration WHERE name = 'website_name'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo $row['value'];
}
$GetWebsiteName = "GetWebsiteName";
Basically I wanted to expand it so that instead of SELECT only one value in this case VALUE I want to SELECT * all values from the database and output them one by one. The issue that I am having is that when calling my return data I am not sure how to code it. I have an example of the SELECT. Here is the code:
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(150) NOT NULL,
`value` varchar(150) NOT NULL,
PRIMARY KEY (`id`)
function GetConfigurationData() {
$sql = "SELECT value FROM configuration";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
echo $row['website_name'];
echo $row['website_url'];
echo $row['website_email'];
}
Does anybody know how to select each one and then output the value using PHP?
function getConfigurationData($name) {
$sql = "SELECT `$name` FROM `configuration`";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
return $row[$name];
}
Usage:
echo getConfigurationData('website_name');
Using something like PDO would be better, though.
I have transfered variable values to another page, but now I'm trying to show the database content relevant to this value.
Workflow:
There's a form that I enter a new Company. I have entered Company1. It's in companies database.
There's another form, that I list in an OPTION tag all the recorded companies. In this form, I record the company's employees information, including the chosen companies option.
There's a page that lists all the recorded companies. Each one has a link (company.php?name=$companyName).
The companies' names are passed via GET to another page.
This other page is called "company.php" and need to show the company's information (other fields in database).
It also has to show other table record, like "employees". It must list all the employees that has de same company's name, passed via GET.
The question is: how do I proceed with step 5 and 6? I tried using this select, but didn't work:
$query = mysql_query("SELECT employeeName FROM employeeForm WHERE companyName='$employeeName'") or die(mysql_error());
It's really difficult for me to be clear at this, I'm sorry if it's not understandable. 'Been working around this issue for hours.
I appreciate any help!
EDIT: Used method:
include("connect.php");
$companyName=$_GET['companyName'];
$result = mysql_query("SELECT * FROM employeeList WHERE company = '$companyName'");
while($result = mysql_fetch_array($query))
{
echo '<div class="form">'.$result['employeeName'].'</div>';
}
ANSWER:
your code:
while($result = mysql_fetch_array($query))
{
echo '<div class="form">'.$result['employeeName'].'</div>';
}
should be:
while($res = mysql_fetch_array($result)) //changed to the name of the variable that stores the query (can't store the array in a variable named after the query so i've changed it to $res...)
{
echo '<div class="form">'.$res['employeeName'].'</div>';
}
OLD:
Are you retrieving the result of the query? To return just one result use the mysql_fetch_assoc() function and to return an entire row (or more variables) use mysql_fetch_array().
Example:
$test = mysql_fetch_assoc($query);
$array = mysql_fetch_array($query);
Ps. To Select an array use a syntax similar to :
"SELECT * FROM table WHERE var = condition"
PPs. This was taken from php.net:
This extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
EDIT:
Your code:
$query = mysql_query("SELECT employeeName FROM employeeForm WHERE companyName='$employeeName'") or die(mysql_error());
You treat the variable as text (variable name not content :) )... use:
WHERE '".$employeeName."'
to parse variables into query... (observe the double quotes)
Also... to access the results of the query use something like:
$array['COLUMN NAME'];
..assuming you use : $array = mysql_fetch_array($query);
I'd highly recommend you use PDO, here's a sample using PDO.
<?php
$dsn = 'mysql:dbname=so;host=localhost';
$user = 'root';
$password = '';
// try to connect.
try {
$dbh = new PDO($dsn, $user, $password);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
exit(1);
}
// the sql which gets all employees for this company.
$getEmployeesSQL = '';
$getEmployeesSQL .= ' SELECT c.name AS company_name, e.name AS employee_name, e.salary, c.location ';
$getEmployeesSQL .= ' FROM company c';
$getEmployeesSQL .= ' LEFT JOIN employee e';
$getEmployeesSQL .= ' ON c.id = e.company_id';
$getEmployeesSQL .= ' WHERE c.name = :cname';
// sql to get company data.
$companyDataSQL = "SELECT * FROM company WHERE name = :cname";
// prepare the sql.
$stmtOne = $dbh->prepare($getEmployeesSQL);
$stmtTwo = $dbh->prepare($companyDataSQL);
// execute
$stmtOne->execute(array(':cname' => $_GET['company']));
$stmtTwo->execute(array(':cname' => $_GET['company']));
// print results.
$employees = $stmtOne->fetchAll(PDO::FETCH_ASSOC);
$companyData = $stmtTwo->fetchAll(PDO::FETCH_ASSOC);
/* * ****************************************** */
/* Iterate and print HTML table. */
/* * ****************************************** */
$html = '<table border="1">';
foreach ($companyData as $company) {
foreach ($company as $field => $value) {
$html.= "<tr><td>$field</td><td>$value</td></tr>";
}
}
$html . '</table>';
echo $html;
$html = '<table border="1">';
foreach ($employees as $row) {
$html.= '<tr><td>' . implode('</td><td>', array_values($row)) . '</td></tr>';
}
$html . '</table>';
echo $html;
What this snippet does is that it prints the company data in a table and then gets employee data using company name.
The table structure I'm using is as follows:
CREATE TABLE `company` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`location` varchar(200) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
CREATE TABLE `employee` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`name` varchar(200) NOT NULL,
`salary` bigint(12) DEFAULT NULL,
`company_id` bigint(20) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_company` (`company_id`),
CONSTRAINT `fk_company` FOREIGN KEY (`company_id`) REFERENCES `company` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=latin1
This returns data as follows: (Not pretty, but this'll have to do for now.)
As I understand it you have two tables - one for companies and one for employees, with the obvious possibility that there are multiple employees for each company. If what you're trying to do is produce a list of employees for a given company, you need to use the Company Name (assuming it's unique) in your SQL query.
$companyName = $_GET('companyName');
$result = mysql_query("SELECT * FROM employeeList WHERE company = '$companyName'");
That will give you a list of employees (with all their info) associated with that particular company.
EDIT:
To loop through the query and print out the results, you can use something like to following (along with what's already above):
echo "<table><tbody>";
while ($row = mysql_fetch_assoc($result)) {
echo "<tr><td>" . $row['employee_first_name'] . " " . $row['employee_last_name'] . "</td></tr>";
}
echo "</tbody></table>