How to total up entries in a database - php

I'm using a MySQL database which has a 'Staff' column. Example:
ID BUSINESS STAFF
1 Business 1 Bob
2 Business 2 Bill
3 Business 3 Paul, Bill
4 Business 4 Bob
I'm aiming to create a pie chart showing how many businesses each member of staff has, using the Google Charts API, and I'm having trouble counting total amounts.
The chart uses the formatting:
var data = google.visualization.arrayToDataTable([
['Staff', 'Business'],
['Bob', 2],
['Bill', 2],
['Paul', 1]
]);
How would I go about echoing a count of these lines? I've spent a fun 40 minutes messing up COUNT queries, with absolutely no joy.

There is a common theme in the comments here and that is normalization. As a rule it is A Bad Thing to represent multiple values as a comma-separated list in a single column.
Here is a working example of an alternate DB design that should get you going in the right direction:
create table staff
(
id int unsigned not null primary key auto_increment,
staffName varchar(250),
unique key `staffUIdx1` (staffName)
) ENGINE=InnoDB;
create table business
(
id int unsigned not null primary key auto_increment,
businessName varchar(250),
unique key `staffUIdx1` (businessName)
) ENGINE=InnoDB;
CREATE TABLE staffBusiness
(
id int unsigned not null primary key auto_increment,
staffId int unsigned not null,
businessId int unsigned not null,
unique key `staffBusinessUIdx1` (staffId,businessId),
CONSTRAINT `fk_staffBusiness_staff1` FOREIGN KEY (`staffId`) REFERENCES `staff` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_staffBusiness_business1` FOREIGN KEY (`businessId`) REFERENCES `business` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
insert into staff (staffName) values ('Bob');
insert into staff (staffName) values ('Bill');
insert into staff (staffName) values ('Paul');
insert into staff (staffName) values ('George');
insert into business (businessName) values ('Business 1');
insert into business (businessName) values ('Business 2');
insert into business (businessName) values ('Business 3');
insert into business (businessName) values ('Business 4');
insert into staffBusiness (staffId,businessId)
select s.id,b.id from staff s join business b
where s.staffName = 'Bob' and b.businessName in ('Business 1','Business 4');
insert into staffBusiness (staffId,businessId)
select s.id,b.id from staff s join business b
where s.staffName = 'Bill' and b.businessName in ('Business 2','Business 3');
insert into staffBusiness (staffId,businessId)
select s.id,b.id from staff s join business b
where s.staffName = 'Paul' and b.businessName in ('Business 3');
...and then the query would look like this:
select staffName as Staff,count(sb.id) as Business
from staff s
left outer join staffBusiness sb on s.id = sb.staffId
group by staffName;
I've included a 4th member of staff called 'George' to show that a normalized approach allows you to have members of staff with no business too.

I develop this code according your question ,you should change according your table and fields also change server configuration server name,user,password,database
$server="server";
$user="user";
$password="password";
$database="database";
$cid=mysql_connect($server,$user,$password);
mysql_select_db($database,$cid);
$query="select * from table";
$rs=mysql_query($query,$conn);
$val=0;
while($row=mysql_fetch_array($rs))
{
$data=$row['business'];
$val=$val+trim(str_replace("Business","", "$data"));
}
$total=$val;
I used this code and i found total ;

Related

Inserting different fields into a table by comparing two other fields from different table

Form built with HTML AND CSS
CREATE TABLE surgery (
surgery_id INT AUTO_INCREMENT PRIMARY KEY,
doc_id INT NOT NULL REFERENCES doctor(doc_id),
nurse_id INT NOT NULL REFERENCES nurse(nurse_id),
surgery_status VARCHAR(8) NOT NULL CHECK (surgery_status IN (`Success`, `Fialled`)),
description NVARCHAR(200) NOT NULL
) ENGINE=INNODB CHARSET=UTF8 COLLATE UTF8_BIN;
The surgery table has patient id and doctor id which is linked to patient table and doctor table respectively. I want to collect the names of the patient and doctor with the form but insert their id rather than their names into the surgery table.
You can use subquery concept for this kind of scenario.
Example:
SELECT *,(SELECT patient_name FROM patient WHERE patient.id = surgery.patient_id) AS _patient_name,
(SELECT doctor_name FROM doctor WHERE doctor.id = surgery.doctor_id) AS _doctor_name FROM surgery

Trigger to update a count based on another table

I am working on a php project for managing employees.
i have two tables employee and department with the department number being a relation between the two. department has an attribute that contains a count of employees based on the deparment number.
So where i'm stuck is that i want the employee count to be automatically inserted, so what do you think i should do
Thanks in advance
If you don't want to use (or have access to) a trigger, but want to abstract the logic, you could use a view (docs).
So assuming the below data, and the idea of having the entire department table and the employee count dynamically calculated, you could have the following query:
CREATE TABLE
`employees`
(
`employeeID` INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(50),
`department_number` INT
);
CREATE TABLE
`departments`
(
`department_number` INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(50)
);
INSERT INTO
`departments`
(`department_number`, `name`)
VALUES
(1, 'Tech Department'),
(2, 'Admin Department');
INSERT INTO
`employees`
(`name`, `department_number`)
VALUES
('John Doe', 1),
('Jane Doe', 1),
('Jimmy Doe', 2);
Then the query:
SELECT
DepartmentTbl.*,
DepartmentEmployeeTbl.employee_count
FROM
`departments` AS DepartmentTbl
LEFT JOIN
(
SELECT
`department_number`,
COUNT(`employeeID`) AS `employee_count`
FROM
`employees`
GROUP BY
`department_number`
) AS DepartmentEmployeeTbl
ON DepartmentTbl.department_number = DepartmentEmployeeTbl.department_number
Gives the result:
department_number | name | employee_count
-------------------------------------------------------
1 | Tech Department | 2
2 | Admin Department | 1
SQLFiddle - http://sqlfiddle.com/#!9/3e0b54/1
So to create this view, you could use:
CREATE OR REPLACE VIEW `departments_employee_count` AS
SELECT
DepartmentTbl.*,
DepartmentEmployeeTbl.employee_count
FROM
`departments` AS DepartmentTbl
LEFT JOIN
(
SELECT
`department_number`,
COUNT(`employeeID`) AS `employee_count`
FROM
`employees`
GROUP BY
`department_number`
) AS DepartmentEmployeeTbl
ON DepartmentTbl.department_number = DepartmentEmployeeTbl.department_number
Then you could call the view as:
SELECT
*
FROM
`departments_employee_count`
Instead of storing and updating the value each time something is changed you should just calculate it when needed.
You can use count to do it.
Example
SELECT department_number, count(*) FROM employee GROUP BY department_number

Adding lists of data to MySQL

I have some data to add to my database, I'm not sure what my table schema should be. I have an id number for each specific user, 4 categories of games, and a possible number of items (0+) each user has for each game. I want to set a table for each game with the categories ->id and ->items, so I can save the list of user id's in the table, with the items they have for that game.
I can't seem to get it to work, I think because of the dynamic number of items for each user. Is it possible for me to achieve my above mentioned table schema? Why not/how?
I have been trying:
foreach ($json->rgDescriptions as $mydata)
{
$sql = $dbh->prepare('INSERT INTO user_items_tf2 (items) VALUES (:item) WHERE steam_id = :steamid');
$sql->bindParam(':item', $mydata->name);
$sql->bindParam(':steamid', $steamprofile['steamid']);
$sql->execute();
}
There are numbers of ways to do this but one which is very flexible and seems to answer your questions would be this.
-- Players
CREATE TABLE player
(`id` int primary key auto_increment, `name` varchar(255))
;
-- Games
CREATE TABLE game
(`id` int primary key auto_increment, `name` varchar(255))
;
-- Items and what game they belong to
CREATE TABLE item
(`id` int primary key auto_increment, `game_id` int, `name` varchar(255))
;
-- What games players are playing
CREATE TABLE player_game
(`player_id` int, `game_id` int)
;
-- What items players have
CREATE TABLE player_item
(`player_id` int, `item_id` int, index(`player_id`))
;
If you never needed to ask the question which users had a given item you could skip the player_item table and stuff the data (as JSON for instance) of their items into a column of the player table with a blob type.
$sql = $dbh->prepare('INSERT INTO user_items_tf2 (items, steam_id) VALUES (:item, :steamid)');

Assign a unique ID to each name in a table where names are repeated

I have a table that contains millions of sales records and looks like this:
CREATE TABLE `sales` (
`dollar_amount` INT NULL,
`transaction_date` DATE NULL,
`company_name` VARCHAR(45) NULL,
`company_id` INT NULL);
The first three columns are populated with data. I would like to insert data into the company_id column that will identify each company with an auto_incremented integer. I plan to use the company_id field as a foreign key referencing another table that will contain each company's details. Many companies have multiple transactions, so the code needs to assign the same company_id to each row in the sales table with a matching company_name.
Is there a way to do this using only MySQL?
First, I'd recommend creating the company table:
CREATE TABLE company (
company_id INT NOT NULL AUTO_INCREMENT,
company_name VARCHAR(45),
PRIMARY KEY(company_id));
Then insert the companies from your sales data:
INSERT INTO company (company_name)
SELECT distinct company_name
FROM sales;
Finally, update your sales table with a join to get the company_id:
UPDATE sales s
JOIN company c ON s.company_name = c.company_name
SET s.company_id = c.company_id;
SQL Fiddle Demo
You should also remove the company_name field from the sales table since this is now stored in the company table.
To define an auto incremented integer, you just use the AUTO_INCREMENT keyword. However, if you define any columns as auto_increment, you must also make that column your primary key. Which, in this case, would make sense in order for it to be a foreign key elsewhere.
Try this:
CREATE TABLE `sales` (
`dollar_amount` INT NULL,
`transaction_date` DATE NULL,
`company_name` VARCHAR(45) NULL,
`company_id` INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(company_id);
SQL Fiddle

Select every alternate days for selecting bus journey direction

I am working on a bus ticket reservation systems . In this,I have made tables for all the routes and within the table I have added fields like bus_number,fare etc . Now our buses travels every alternate days in vice versa direction,ie if a bus travels from X->Y on 21-12-2011,the the same bus will travel Y->X on next date . So how am going to get the direction for a bus ? If I made tables for each bus service provider and add bus numbers add a identifier like 'to' for a date , I think it will be possible to to know the status for all next days . I dont know if its a good idea , so please help me.
Without knowing the precise details of your existing tables it is a little difficult to provide a definitive solution. Anyway, here's a suggestion of how you could hold buses along with their stops and fares:
CREATE TABLE `bus` (
`id` int unsigned not null primary key auto_increment,
`bus_number` varchar(55) not null,
UNIQUE KEY `busUidx1` (`bus_number`)
) ENGINE=InnoDB;
CREATE TABLE `bus_stop` (
`id` int unsigned not null primary key auto_increment,
`stop_description` varchar(250) not null,
UNIQUE KEY `bus_stopUidx1` (`stop_description`)
) ENGINE=InnoDB;
CREATE TABLE `bus_route` (
`id` int unsigned not null primary key auto_increment,
`bus_id` int unsigned not null,
`route_date` date not null,
`bus_start_stop_id` int unsigned not null,
`bus_end_stop_id` int unsigned not null,
`fare` decimal (10,2) not null,
UNIQUE KEY `bus_stopUidx1` (`bus_id`,`route_date`),
CONSTRAINT `fk_bus_route_bus_fk1` FOREIGN KEY (`bus_id`) REFERENCES `bus` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_bus_route_stop_fk1` FOREIGN KEY (`bus_start_stop_id`) REFERENCES `bus_stop` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
CONSTRAINT `fk_bus_route_stop_fk2` FOREIGN KEY (`bus_end_stop_id`) REFERENCES `bus_stop` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB;
Using this model you should be able to store a list of buses (in the bus table), a list of all possible stops (in the bus_stop table) and bus routes for a given date. It will also allow you the flexibility to break the 'bus travels from X > Y and then always travels back from Y > X' rule which, if the buses that I have travelled on in the past are anything to go by, might prove useful ;-)
EDIT
So here is some sample data to try and illustrate my answer further:
insert into bus (bus_number) values ('Red Bus 1');
insert into bus (bus_number) values ('Red Bus 2');
insert into bus (bus_number) values ('Yellow Bus 1');
insert into bus (bus_number) values ('Yellow Bus 2');
insert into bus_stop (stop_description) values ('Stop 1');
insert into bus_stop (stop_description) values ('Stop 2');
insert into bus_stop (stop_description) values ('Stop 3');
insert into bus_stop (stop_description) values ('Stop 4');
insert into bus_route (bus_id,route_date,bus_start_stop_id,bus_end_stop_id,fare)
values (
(select id from bus where bus_number = 'Red Bus 1'),
'2011-12-11',
(select id from bus_stop where stop_description = 'Stop 1'),
(select id from bus_stop where stop_description = 'Stop 2'),
3.45);
insert into bus_route (bus_id,route_date,bus_start_stop_id,bus_end_stop_id,fare)
values (
(select id from bus where bus_number = 'Red Bus 1'),
'2011-12-12',
(select id from bus_stop where stop_description = 'Stop 2'),
(select id from bus_stop where stop_description = 'Stop 1'),
3.45);
insert into bus_route (bus_id,route_date,bus_start_stop_id,bus_end_stop_id,fare)
values (
(select id from bus where bus_number = 'Yellow Bus 1'),
'2011-12-11',
(select id from bus_stop where stop_description = 'Stop 3'),
(select id from bus_stop where stop_description = 'Stop 4'),
1.95);
insert into bus_route (bus_id,route_date,bus_start_stop_id,bus_end_stop_id,fare)
values (
(select id from bus where bus_number = 'Yellow Bus 1'),
'2011-12-12',
(select id from bus_stop where stop_description = 'Stop 4'),
(select id from bus_stop where stop_description = 'Stop 3'),
1.95);
And finally a query to join the tables together:
select b.bus_number,
br.route_date,
bs.stop_description as start,
be.stop_description as end,
br.fare
from bus_route br
inner join bus b on b.id = br.bus_id
inner join bus_stop bs on bs.id = br.bus_start_stop_id
inner join bus_stop be on be.id = br.bus_end_stop_id;

Categories