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>
Related
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
i' ve created a database using mysql and i'm using php (along with html of course) to retrieve/insert data to it.
i want to know how to create a form-list, which displayed options will change* according to a table in my database.
for example let's say i have this table:
CREATE TABLE COMPANY (
comp_id INT NOT NULL AUTO_INCREMENT,
comp_name varchar(30) NOT NULL,
PRIMARY KEY(comp_id) );
i want the list to have all the different company names for options, so the user can pick which company he wants.
*the company names are not standard, in the company table can happen changes, one day i may have comp1 and comp2 and the next comp3, comp4 and comp5.
so i cannot have a fixed code for that, i need the page to "read" the values from the table and create the form according to them.
hope you understand what i mean :P
thanks in advance!
Just fetch all the records from company table then populate select element from that data. To change company name, Just change it in table.
$mysqli = new mysqli('127.0.0.1','root','','dbname');
if($mysqli->connect_errno){
echo $mysqli->connect_errno;
} else {
$sql = 'SELECT * FROM COMPANY';
$result = $mysqli->query($sql);
if(!$result){
echo "Query Failed. ".$mysqli->error;
} else {
if($result->num_rows > 0){
$html = "<select>";
while($current_row = $result->fetch_assoc()){
$html .= '<option value="'.$current_row['comp_id'].'">'.$current_row['comp_name'].'</option>';
}
$html .= "</select>";
$result->free();//free the resultset memory
echo $html;
} else {
echo "No Record Exists";
}
}
}
Some semi-pseudo code based roughly on mysqli - connection assumed to be $db
This ought to give an idea how you can accomplish what you want.
$sql='select * from `company`';
$res=$db->query( $sql );
if( $res ){
$html=array('<select name="company">');
while( $rs=$rs->fetch_object() )$html[]="<option value='{$rs->comp_id}'>{$rs->comp_name}";
$html[]='</select>';
printf('%s',implode( PHP_EOL, $html ) );
}
Some may know my script Basic Announce, I am trying to get the latest news entry that has been sent through so only the last know entry is called up.
In this code block is the news caller that I originally created but this decides to call all of the entries but thats for the Admin to see, but I need the last entry to be called in this file: news.php
<?php
// Connects to your Database
mysql_connect("$server","$usr","$pswd") or die(mysql_error());
mysql_select_db("$db") or die(mysql_error());
$data = mysql_query("SELECT * FROM announcements")
or die(mysql_error());
while($info = mysql_fetch_array( $data ))
{
Print "<tr>";
Print "<th>Announcement:</th><td>".$info['Announcement'] . "</td> ";
Print "<br>";
Print "<th>Submitted By:</th> <td>".$info['Submitted'] . "</td> ";
}
;
?>
How would I go about select the last know entry I also include my database tables sql code.
Here is the Basic Announce.sql code
CREATE TABLE IF NOT EXISTS `announcements` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`Announcement` text NOT NULL,
`Submitted` text NOT NULL,
`Date_time` date NOT NULL,
PRIMARY KEY (`id`)
);
Is it possible to pull the last record using my Primary Key "id"?
Any help on this troubling matter would be greatly appreciated as I am still learn PHP via self-taught and inspiration.
Many Thanks
Order it by the id descending:
$data = mysql_query("SELECT * FROM announcements ORDER BY id DESC LIMIT 1");
I also added LIMIT 1 because you only want to retrieve the first row in the set. Given you only want a single row, you don't need the while loop, just make a single call to fetch:
$data = mysql_query("SELECT * FROM announcements ORDER BY id DESC LIMIT 1");
if($data && mysql_num_rows($data) == 1) // check for success and a row found
{
$info = mysql_fetch_array( $data );
Print "<tr>";
Print "<th>Announcement:</th><td>".$info['Announcement'] . "</td> ";
Print "<br>";
Print "<th>Submitted By:</th> <td>".$info['Submitted'] . "</td> ";
}
else
{
// no rows or an error occurred
}
Side notes:
The mysql_* library is deprecated. For new code you should consider upgrading to PDO or MySQLi.
.. or die(mysql_error()) should be avoided. A better option is trigger_error(mysql_error()).
try out this.
SELECT Top 1 * FROM announcements order by id desc
I have a database that is designed for Football players and so have the table with the following fields:
Person_ID
First_Name
Surname
NicName
Address_Line_1
Contact_Number
Date_of_birth
Postcode
I need to extract the Person_ID for a player without actually entering the ID number as players will not know their individual number and is designed to be used just by the system.
I have the My sql code for selecting a player when certain values are entered:
SELECT `Person_ID` FROM `person` WHERE `First_Name` = 'A Name' and `Surname` = 'Another Name'
This does not however return very well within php when placed into a function. The function I currently have is shown below (php)
function showid($fname, $sname, $d) {
$sql = "SELECT `Person_ID` FROM `person` WHERE `First_Name` = '$fname' and `Surname` = '$sname'";
$result = mysqli_query($d, $sql);
if (!$result)
print ("$sql failed".mysqli_error($d));
else {
print ("$fname $sname is selected<br>");
}
}
$name and $sname are values which will be entered by the user and they will then be able to transfer to a different team or update their account etc but I need to have the ID selected so that further functions and queries can work fully.
If you want to fetch the ID of the selected player, use the fetch_array function
http://php.net/manual/en/mysqli-result.fetch-array.php
function showid($fname, $sname, $d) {
$sql = "SELECT `Person_ID` FROM `person` WHERE `First_Name` = '$fname' and `Surname` = '$sname'";
$result = mysqli_query($d, $sql);
if (!$result)
print ("$sql failed".mysqli_error($d));
else {
print ("$fname $sname is selected<br>");
}
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "Your ID is" . $row['Person_ID'];
}
This of course assumes there is only one result (otherwise we would have to loop) so you might want to check $result->num_rows is equal to 1 and return an error if it isnt (assuming you arent using UNIQUE in your database)
Please assist me on this one. I have two DB's, one keeps track of user and system activities and the other keeps track of only user activities. The purpose of the codes below is to first of all retreive all tables from the second DB. These tables have the following columns:
(id |date |debit |credit |number |description |accounttype |company_id)
The idea is to retrieve all tables and only their |debit|credit| columns. Already these fields (|debit|credit|) have some values in them. After retrieval, I should be able to update or if possible do a new insertion to any or all the tables that have been retrieved from the DB.
Below are the codes I've written. It retrieves alright but can't do an insertion or update. Please assist me
The same page calls itself.
//Connection and Extraction from DB
//DB Connection exists
//SQL Query
$sql = "show tables from $companyname";
$results = mysql_query($sql) or die(mysql_error());
$count = 1;
while($row = mysql_fetch_array($results))
{
$results2 = mysql_query("SELECT * FROM `$row[0]` LIMIT 1") or die('Error'.mysql_error());
while($row2 = mysql_fetch_array($results2))
{
$debit = $row2['debit'];
$credit = $row2['credit'];
echo "<tr><td>$count. </td><td width='30%'>".ucwords($row[0])."</td><td width='30%'>
<input type='text' name='debit' value='$debit' align='right'></td>
<td width='30%'><input type='text' name='credit' value='$credit' align='right'></td></tr>";
}
$count++;
}
//Insertion into DB
if(isset($_POST['submit'])) {
//SQL Query
$sql3 = "show tables from $companyname";
$results3 = mysql_query($sql3) or die(mysql_error());
$count = 1;
while($row3 = mysql_fetch_array($results3))
{
$results4 = mysql_query("SELECT * FROM `$row3[0]` LIMIT 1") or die('Error '.mysql_error());
$debit = $_POST['debit'];
$credit = $_POST['credit'];
while($row4 = mysql_fetch_array($results4))
{
$query = mysql_query("UPDATE `$row3[0]` SET `debit`= '$row4[debit]' , `credit`= '$row4[credit]' WHERE `id`=`$row4[id]`");
echo "UPDATE `$row3[0]` SET `debit`= '$row4[debit]' , `credit`= '$row4[credit]' WHERE `id`=`$row4[id]` <br>";
echo $num;
}
$count++;
}
}
your database design is bad
I should have keepd all data in one schema,
keeping a seperate auto_increment by company by using a dubbel field primary key
CREATE TABLE company_transaktions (
company_name VARCHAR(50) NOT NULL,
id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT,
date DATE NOT NULL,
debit FLOAT NOT NULL,
credit FLOAT NOT NULL,
number MENIUMINT NOT NULL,
description TINYTEXT NOT NULL,
accounttype TINYTEXT NOT NULL,
company_id MEDIUMINT UNSIGNED NOT NULL,
PRIMARY KEY (company_name,id)
);
or if company_id is what i think it is, you should use PRIMARY KEY (company_id,id)
the php problem
you store your 2 postdata in 2 variables
$debit = $_POST['debit'];
$credit = $_POST['credit'];
but you never use them, they are always going to be the value of the last row, as they all have the same name.
so first thing you need to do is to rename your inputs:
echo "<tr>\n";
echo "<td>$count. </td>\n";
echo "<td width='30%'>".ucwords($row[0])."</td>\n";
echo "<td width='30%'><input type='text' name='{$row[0]}[debit]' value='$debit' align='right'></td>\n";
echo "<td width='30%'><input type='text' name='{$row[0]}[credit]' value='$credit' align='right'>\n";
echo "</td>\n";
echo "</tr>";
then you can fetch the right one on each loop:
$debit = mysql_real_escape_string($_POST[$row3[0]]['debit']);
$credit = mysql_real_escape_string($_POST[$row3[0]]['credit']);
and then use them in your query
$result = mysql_query("UPDATE `$row3[0]` SET `debit`= '$debit' , `credit`= '$credit' WHERE `id`=`$row4[id]`");