phpMyAdmin creating - php

I attached a screen shot from my phpMyadmin and the code for my table.
I can't lunch the code below without getting : #1146 - Table 'patlaza2_Premiere.customer' doesn't exist
What can be the problem and any idea how to fix it please?
SELECT CUSTOMER_NUM, CUSTOMER_NAME, BALANCE, CREDIT_LIMIT
FROM customer
https://gyazo.com/edd75cc3b02659525fb0bbe27fdd4f1c
CREATE TABLE Rep
(RepNum CHAR(2) PRIMARY KEY,
LastName CHAR(15),
FirstName CHAR(15),
Street CHAR(15),
City CHAR(15),
State CHAR(2),
Zip CHAR(5),
Commission DECIMAL(7,2),
Rate DECIMAL(3,2) );
CREATE TABLE Customer
(CustomerNum CHAR(3) PRIMARY KEY,
CustomerName CHAR(35) NOT NULL,
Street CHAR(15),
City CHAR(15),
State CHAR(2),
Zip CHAR(5),
Balance DECIMAL(8,2),
CreditLimit DECIMAL(8,2),
RepNum CHAR(2) );
CREATE TABLE Orders
(OrderNum CHAR(5) PRIMARY KEY,
OrderDate DATE,
CustomerNum CHAR(3) );
CREATE TABLE Part
(PartNum CHAR(4) PRIMARY KEY,
Description CHAR(15),
OnHand DECIMAL(4,0),
Class CHAR(2),
Warehouse CHAR(1),
Price DECIMAL(6,2) );
CREATE TABLE OrderLine
(OrderNum CHAR(5),
PartNum CHAR(4),
NumOrdered DECIMAL(3,0),
QuotedPrice DECIMAL(6,2),
PRIMARY KEY (OrderNum, PartNum) );
INSERT INTO Rep
VALUES
('20','Kaiser','Valerie','624 Randall','Grove','FL','33321',20542.50,0.05);
INSERT INTO Rep
VALUES
('35','Hull','Richard','532 Jackson','Sheldon','FL','33553',39216.00,0.07);
INSERT INTO Rep
VALUES
('65','Perez','Juan','1626 Taylor','Fillmore','FL','33336',23487.00,0.05);
INSERT INTO Customer
VALUES
('148','Al''s Appliance and Sport','2837 Greenway','Fillmore','FL','33336',6550.00,7500.00,'20');
INSERT INTO Customer
VALUES
('282','Brookings Direct','3827 Devon','Grove','FL','33321',431.50,10000.00,'35');
INSERT INTO Customer
VALUES
('356','Ferguson''s','382 Wildwood','Northfield','FL','33146',5785.00,7500.00,'65');
INSERT INTO Customer
VALUES
('408','The Everything Shop','1828 Raven','Crystal','FL','33503',5285.25,5000.00,'35');
INSERT INTO Customer
VALUES
('462','Bargains Galore','3829 Central','Grove','FL','33321',3412.00,10000.00,'65');
INSERT INTO Customer
VALUES
('524','Kline''s','838 Ridgeland','Fillmore','FL','33336',12762.00,15000.00,'20');
INSERT INTO Customer
VALUES
('608','Johnson''s Department Store','372 Oxford','Sheldon','FL','33553',2106.00,10000.00,'65');
INSERT INTO Customer
VALUES
('687','Lee''s Sport and Appliance','282 Evergreen','Altonville','FL','32543',2851.00,5000.00,'35');
INSERT INTO Customer
VALUES
('725','Deerfield''s Four Seasons','282 Columbia','Sheldon','FL','33553',248.00,7500.00,'35');
INSERT INTO Customer
VALUES
('842','All Season','28 Lakeview','Grove','FL','33321',8221.00,7500.00,'20');
INSERT INTO Orders
VALUES
('21608','2013-10-20','148');
INSERT INTO Orders
VALUES
('21610','2013-10-20','356');
INSERT INTO Orders
VALUES
('21613','2013-10-21','408');
INSERT INTO Orders
VALUES
('21614','2013-10-21','282');
INSERT INTO Orders
VALUES
('21617','2013-10-23','608');
INSERT INTO Orders
VALUES
('21619','2013-10-23','148');
INSERT INTO Orders
VALUES
('21623','2013-10-23','608');
INSERT INTO Part
VALUES
('AT94','Iron',50,'HW','3',24.95);
INSERT INTO Part
VALUES
('BV06','Home Gym',45,'SG','2',794.95);
INSERT INTO Part
VALUES
('CD52','Microwave Oven',32,'AP','1',165.00);
INSERT INTO Part
VALUES
('DL71','Cordless Drill',21,'HW','3',129.95);
INSERT INTO Part
VALUES
('DR93','Gas Range',8,'AP','2',495.00);
INSERT INTO Part
VALUES
('DW11','Washer',12,'AP','3',399.99);
INSERT INTO Part
VALUES
('FD21','Stand Mixer',22,'HW','3',159.95);
INSERT INTO Part
VALUES
('KL62','Dryer',12,'AP','1',349.95);
INSERT INTO Part
VALUES
('KT03','Dishwasher',8,'AP','3',595.00);
INSERT INTO Part
VALUES
('KV29','Treadmill',9,'SG','2',1390.00);
INSERT INTO OrderLine
VALUES
('21608','AT94',11,21.95);
INSERT INTO OrderLine
VALUES
('21610','DR93',1,495.00);
INSERT INTO OrderLine
VALUES
('21610','DW11',1,399.99);
INSERT INTO OrderLine
VALUES
('21613','KL62',4,329.95);
INSERT INTO OrderLine
VALUES
('21614','KT03',2,595.00);
INSERT INTO OrderLine
VALUES
('21617','BV06',2,794.95);
INSERT INTO OrderLine
VALUES
('21617','CD52',4,150.00);
INSERT INTO OrderLine
VALUES
('21619','DR93',1,495.00);
INSERT INTO OrderLine
VALUES
('21623','KV29',2,1290.00);

The only table that exists in the patlaza2_Premiere database is TABLE 1. Before running your create table statements, run this: use patlaza2_Premiere; to explicitly tell mysql which database you want to use.
Alternatively, if you click on the patlaza2_Premiere database link in the sidebar menu of phpmyadmin, that will automatically issue the use patlaza2_Premiere command and you can then run your create table statements.

Related

mysql how to create table and insert record in another table query

I wrote a query to put records in a table and at the same time create another. The table is created but the data is not entered. Where am I wrong? This is my code:
$sql = "INSERT INTO progetti
(data, ora, nome_progetto, anagrafica_id, preventivo, budget, eurora, scadenza, scontoaggiuntivo, ref1, tel_ref1, mail_ref1, contenuto, stato_id)
VALUES
('".$_POST["data"]."',
'".$_POST["ora"]."',
'".$_POST["nome_progetto"]."',
'".$_POST["anagrafica_id"]."',
'".$_POST["preventivo"]."',
'".$_POST["budget"]."',
'".$_POST["eurora"]."',
'".$_POST["scadenza"]."',
'".$_POST["scontoaggiuntivo"]."',
'".$_POST["ref1"]."',
'".$_POST["tel_ref1"]."',
'".$_POST["mail_ref1"]."',
'".$_POST["contenuto"]."',
'".$_POST["stato_id"]."'
)";
"CREATE TABLE $_POST[nome_progetto] (
id INT(11) AUTO_INCREMENT PRIMARY KEY,
data date,
intervento varchar(30),
descrizione varchar(70),
ore int(2)
)";

Inserting data into temporary mysql table with case

Consider the following example table:
CREATE TABLE items
(`id` int, `productName` varchar(7), `price_new` decimal(10,2), `price_used` varchar(55))
;
INSERT INTO items
(`id`, `productName`, `price_new`, `price_used`)
VALUES
(1, 'cup', 10.50, 5.50),
(2, 'plate', 9.50, 4.50),
(3, 'mug', 8.50, 3.50)
;
For an application I wish to create a temporary table based on what the user has.
The user would have say a 'cup' with condition of 'new'. (stored in a php array)
My desired temporary table would be something like:
CREATE TEMPORARY TABLE IF NOT EXISTS tempTable (
`id` INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(7) NULL,
`itemCondition` varchar(7) NULL,
`price` decimal(10,2) NULL
);
My question is this:
If I create this temporary table how could I insert 'cup' and 'new' with MySQL selecting the price from the items table based on the itemCondition?
psuedocode:
Insert:
(1, 'cup', (
if itemCondition == 'new'
(select Items.price_new where items.productName = 'cup')
ELSE
(select Items.price_used where items.productName = 'cup')
Thank you for your assistance.
The problem is that until you insert the data into the temptable, sql will not know the value of the imtemCondition field. The value 'new' is supplied in the insert statement itself as a fixed value.
You will need either stored procedure that selects the price based on a parameter value and then insert that price into the temporary table, or you can implement the same logic using php.
Steps:
Provide user id, name, and item condition.
Select the price based on the item condition.
Insert all data to the temporary table.

Insert row into a table with foreign key inside PHP

I am creating a PHP website that use Apache web server (PHPmyAdmin)
I have 3 tables :
brand
brand_id (PRIMARY KEY) AUTO INCREMENT
brand_name
item
item_id (PRIMARY KEY) AUTO INCREMENT
item_category
model
model_id (PRIMARY KEY) AUTO INCREMENT
item_model
brand_id (FOREIGN KEY for brand.brand_id)
brand_name (FOREIGN KEY for item.item_id)
quantity
price
I have a problem when I want to insert new value into model table.
this is PHP Code that I use for inserting
if (isset($_POST['brand_id']));
$brand = ($_POST['brand_id']);
if (isset($_POST['item_id']));
$cat = ($_POST['item_id']);
if (isset($_POST['model']));
$model = ($_POST['model']);
if (isset($_POST['quantity']))
$quantity = ($_POST['quantity']);
if (isset($_POST['price']))
$price = ($_POST['price']);
$sql = "INSERT INTO model (item_model, brand_id, item_id, quantity, price)
VALUES ('$model', '$brand', '$cat', '$quantity', '$price')";
Note that I did not insert any value into the model_id because I think it will automatically increased for it is AUTO increment. I dont know whether I am right or wrong.
the isset values are passed from another PHP file. so this PHP basically just catch the thrown values from previous PHP file.
I had tried to insert value directly from the PHPmyAdmin using SQL statement and it yielded this error :
Cannot add or update a child row: a foreign key
constraint fails (`stock`.`model`, CONSTRAINT `fk_item_brand`
FOREIGN KEY (`brand_id`) REFERENCES `brand` (`brand_id`) ON UPDATE CASCADE)
and if I tried to put in a id value into one of the column, it will yield an error:
SQL query:
INSERT INTO `model`(`model_id`, `item_model`, `brand_id`, `item_id`, `quantity`, `price`)
VALUES (1,'a','1','1','a','a')
MySQL said: Documentation
#1062 - Duplicate entry '1' for key 'PRIMARY'
How do I insert a row into a table with foreign key inside PHP?
$sql = "INSERT INTO model (model_id,item_model, brand_id, item_id, quantity, price)
VALUES (null,'$model', '$brand', '$cat', '$quantity', '$price')";
Try this.
Add auto increment field and pass value null

How to test PHP and MySQL memory when it is running?

I have the following simple script which will create a database with several tables, and populate them with all the zipcodes in the USA. I've included the script and sql file, however, I am not asking anyone to review the scripts, but included it for reference.
It used to take about 90 seconds to run on my remote VPS and it still takes about 90 seconds on my development box at home.
All of a sudden, it now takes virtually forever on my VPS.
The two servers have almost identical configuration except the VPS is running mysql5.1.71 and the home box is running mysql5.5.
How can I see how much memory is being used real-time by PHP and MySQL?
EDIT. Top screenshot is attached:
error_reporting(E_ALL);
date_default_timezone_set('America/Los_Angeles');
set_time_limit(2000);
$conn = new PDO("mysql:host=localhost;dbname=test_database;charset=utf8",'xxx','xxx',array(PDO::ATTR_EMULATE_PREPARES=>false,PDO::MYSQL_ATTR_USE_BUFFERED_QUERY=>true,PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC));
syslog(LOG_INFO,'Start');
$time1=microtime(true);
shell_exec("mysql -xxx-xxx-hlocalhost -Dtest_database < test_database.sql");
$time2=microtime(true);
$time=$time2-$time1;
echo($time.'<br>');
syslog(LOG_INFO,'Database Built: '.$time);
$file = fopen('zipcodes.csv', "r");
$sql ='INSERT INTO cities (id, name, states_id) VALUES (NULL,?,?)';
$stmt_cities = $conn->prepare($sql);
$sql ='INSERT INTO counties (id, name) VALUES (NULL,?)';
$stmt_counties = $conn->prepare($sql);
$sql ='INSERT INTO zipcodes (id, latitude, longitude, zipcode_types_id, timezones_id, counties_id) VALUES (?,?,?,?,?,?)';
$stmt_zipcodes = $conn->prepare($sql);
$sql ='INSERT INTO cities_has_zipcodes (cities_id, zipcodes_id) VALUES (?,?)';
$stmt_zipcodes_cross = $conn->prepare($sql);
$sql ='SELECT co.id FROM counties AS co INNER JOIN zipcodes AS z ON co.id=z.counties_id INNER JOIN cities_has_zipcodes AS chz ON chz.zipcodes_id=z.id INNER JOIN cities AS c ON c.id=chz.cities_id WHERE co.name=? AND c.states_id=?';
$stmt_check_county = $conn->prepare($sql);
$sql ='SELECT id FROM cities WHERE name=? AND states_id=?';
$stmt_check_city = $conn->prepare($sql);
while (($data = fgetcsv($file, 100000, ",")) !== FALSE)
{
//See if a county of a given name has already been inserted for given state
$stmt_check_county->execute(array($data[5],$data[4]));
if(!$county_id=$stmt_check_county->fetchColumn())
{
$stmt_counties->execute(array($data[5]));
$county_id=$conn->lastInsertId();
}
//See if a city of a given name has already been inserted for given state
$stmt_check_city->execute(array($data[3],$data[4]));
if(!$cities_id=$stmt_check_city->fetchColumn())
{
$stmt_cities->execute(array($data[3],$data[4]));
$cities_id=$conn->lastInsertId();
}
$stmt_zipcodes->execute(array(sprintf("%05d",$data[0]),$data[1],$data[2],$data[6],$data[7],$county_id));
$stmt_zipcodes_cross->execute(array($cities_id,sprintf("%05d",$data[0])));
}
fclose($file);
$time3=microtime(true);
$time=$time3-$time2;
echo($time.'<br>');
syslog(LOG_INFO,'Done: '.$time);
test_database.sql
DROP DATABASE IF EXISTS test_database; CREATE DATABASE test_database; USE test_database;
CREATE TABLE IF NOT EXISTS states ( id CHAR(2) NOT NULL , name VARCHAR(45) NULL , PRIMARY KEY (id) ) ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS cities ( id INT UNSIGNED NOT NULL AUTO_INCREMENT , name VARCHAR(45) NOT NULL , states_id CHAR(2) NOT NULL , PRIMARY KEY (id) , INDEX fk_zipcodes_states1_idx (states_id ASC) , UNIQUE INDEX makeUnique (states_id ASC, name ASC) , CONSTRAINT fk_zipcodes_states1
FOREIGN KEY (states_id )
REFERENCES states (id )
ON DELETE NO ACTION
ON UPDATE NO ACTION) ENGINE = InnoDB PACK_KEYS = 0 ROW_FORMAT = DEFAULT;
CREATE TABLE IF NOT EXISTS zipcode_types ( id INT UNSIGNED NOT NULL AUTO_INCREMENT , name VARCHAR(45) NULL , PRIMARY KEY (id) ) ENGINE
= InnoDB PACK_KEYS = 0 ROW_FORMAT = DEFAULT;
CREATE TABLE IF NOT EXISTS counties ( id INT UNSIGNED NOT NULL AUTO_INCREMENT , name VARCHAR(45) NOT NULL , PRIMARY KEY (id) ) ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS timezones ( id CHAR(4) NOT NULL , name VARCHAR(45) NOT NULL , PRIMARY KEY (id) ) ENGINE = InnoDB PACK_KEYS
= 0 ROW_FORMAT = DEFAULT;
CREATE TABLE IF NOT EXISTS zipcodes ( id CHAR(5) NOT NULL , longitude DECIMAL(9,6) NOT NULL , latitude DECIMAL(9,6) NOT NULL , zipcode_types_id INT UNSIGNED NOT NULL , counties_id INT UNSIGNED NOT NULL , timezones_id CHAR(4) NOT NULL , PRIMARY KEY (id) , INDEX fk_zipcodes_zipcode_types1_idx (zipcode_types_id ASC) , INDEX fk_zipcodes_counties1_idx (counties_id ASC) , INDEX fk_zipcodes_timezones1_idx (timezones_id ASC) , CONSTRAINT fk_zipcodes_zipcode_types1
FOREIGN KEY (zipcode_types_id )
REFERENCES zipcode_types (id )
ON DELETE NO ACTION
ON UPDATE NO ACTION, CONSTRAINT fk_zipcodes_counties1
FOREIGN KEY (counties_id )
REFERENCES counties (id )
ON DELETE NO ACTION
ON UPDATE NO ACTION, CONSTRAINT fk_zipcodes_timezones1
FOREIGN KEY (timezones_id )
REFERENCES timezones (id )
ON DELETE NO ACTION
ON UPDATE NO ACTION) ENGINE = InnoDB;
CREATE TABLE IF NOT EXISTS cities_has_zipcodes ( cities_id INT UNSIGNED NOT NULL , zipcodes_id CHAR(5) NOT NULL , PRIMARY KEY (cities_id, zipcodes_id) , INDEX fk_cities_has_zipcodes_zipcodes1_idx (zipcodes_id ASC) , INDEX fk_cities_has_zipcodes_cities1_idx (cities_id ASC) , CONSTRAINT fk_cities_has_zipcodes_cities1
FOREIGN KEY (cities_id )
REFERENCES cities (id )
ON DELETE NO ACTION
ON UPDATE NO ACTION, CONSTRAINT fk_cities_has_zipcodes_zipcodes1
FOREIGN KEY (zipcodes_id )
REFERENCES zipcodes (id )
ON DELETE NO ACTION
ON UPDATE NO ACTION) ENGINE = InnoDB;
INSERT INTO zipcode_types (id, name) VALUES (1,'Standard'); INSERT INTO zipcode_types (id, name) VALUES (2,'PO Box Only'); INSERT INTO zipcode_types (id, name) VALUES (3,'Military'); INSERT INTO zipcode_types (id, name) VALUES (4,'Unique');
INSERT INTO timezones (id, name) VALUES ('HAST','Hawaii-Aleutian Standard Time'); INSERT INTO timezones (id, name) VALUES ('AKST','Alaska Standard Time'); INSERT INTO timezones (id, name) VALUES ('PST','Pacific Standard Time'); INSERT INTO timezones (id, name) VALUES ('MST','Mountain Standard Time'); INSERT INTO timezones (id, name) VALUES ('CST','Central Standard Time'); INSERT INTO timezones (id, name) VALUES ('EST','Eastern Standard Time'); INSERT INTO timezones (id, name) VALUES ('AST','Atlantic Standard Time'); INSERT INTO timezones (id, name) VALUES ('XXX','Unknown');
INSERT INTO states (id,name) VALUES ('AL','ALABAMA'); INSERT INTO states (id,name) VALUES ('AK','ALASKA'); INSERT INTO states (id,name) VALUES ('AS','AMERICAN SAMOA'); INSERT INTO states (id,name) VALUES ('AZ','ARIZONA'); INSERT INTO states (id,name) VALUES ('AR','ARKANSAS'); INSERT INTO states (id,name) VALUES ('CA','CALIFORNIA'); INSERT INTO states (id,name) VALUES ('CO','COLORADO'); INSERT INTO states (id,name) VALUES ('CT','CONNECTICUT'); INSERT INTO states (id,name) VALUES ('DE','DELAWARE'); INSERT INTO states (id,name) VALUES ('DC','DISTRICT OF COLUMBIA'); INSERT INTO states (id,name) VALUES ('FM','FEDERATED STATES OF MICRONESIA'); INSERT INTO states (id,name) VALUES ('FL','FLORIDA'); INSERT INTO states (id,name) VALUES ('GA','GEORGIA'); INSERT INTO states (id,name) VALUES ('GU','GUAM'); INSERT INTO states (id,name) VALUES ('HI','HAWAII'); INSERT INTO states (id,name) VALUES ('ID','IDAHO'); INSERT INTO states (id,name) VALUES ('IL','ILLINOIS'); INSERT INTO states (id,name) VALUES ('IN','INDIANA'); INSERT INTO states (id,name) VALUES ('IA','IOWA'); INSERT INTO states (id,name) VALUES ('KS','KANSAS'); INSERT INTO states (id,name) VALUES ('KY','KENTUCKY'); INSERT INTO states (id,name) VALUES ('LA','LOUISIANA'); INSERT INTO states (id,name) VALUES ('ME','MAINE'); INSERT INTO states (id,name) VALUES ('MH','MARSHALL ISLANDS'); INSERT INTO states (id,name) VALUES ('MD','MARYLAND'); INSERT INTO states (id,name) VALUES ('MA','MASSACHUSETTS'); INSERT INTO states (id,name) VALUES ('MI','MICHIGAN'); INSERT INTO states (id,name) VALUES ('MN','MINNESOTA'); INSERT INTO states (id,name) VALUES ('MS','MISSISSIPPI'); INSERT INTO states (id,name) VALUES ('MO','MISSOURI'); INSERT INTO states (id,name) VALUES ('MT','MONTANA'); INSERT INTO states (id,name) VALUES ('NE','NEBRASKA'); INSERT INTO states (id,name) VALUES ('NV','NEVADA'); INSERT INTO states (id,name) VALUES ('NH','NEW HAMPSHIRE'); INSERT INTO states (id,name) VALUES ('NJ','NEW JERSEY'); INSERT INTO states (id,name) VALUES ('NM','NEW MEXICO'); INSERT INTO states (id,name) VALUES ('NY','NEW YORK'); INSERT INTO states (id,name) VALUES ('NC','NORTH CAROLINA'); INSERT INTO states (id,name) VALUES ('ND','NORTH DAKOTA'); INSERT INTO states (id,name) VALUES ('MP','NORTHERN MARIANA ISLANDS'); INSERT INTO states (id,name) VALUES ('OH','OHIO'); INSERT INTO states (id,name) VALUES ('OK','OKLAHOMA'); INSERT INTO states (id,name) VALUES ('OR','OREGON'); INSERT INTO states (id,name) VALUES ('PW','PALAU'); INSERT INTO states (id,name) VALUES ('PA','PENNSYLVANIA'); INSERT INTO states (id,name) VALUES ('PR','PUERTO RICO'); INSERT INTO states (id,name) VALUES ('RI','RHODE ISLAND'); INSERT INTO states (id,name) VALUES ('SC','SOUTH CAROLINA'); INSERT INTO states (id,name) VALUES ('SD','SOUTH DAKOTA'); INSERT INTO states (id,name) VALUES ('TN','TENNESSEE'); INSERT INTO states (id,name) VALUES ('TX','TEXAS'); INSERT INTO states (id,name) VALUES ('UT','UTAH'); INSERT INTO states (id,name) VALUES ('VT','VERMONT'); INSERT INTO states (id,name) VALUES ('VI','VIRGIN ISLANDS'); INSERT INTO states (id,name) VALUES ('VA','VIRGINIA'); INSERT INTO states (id,name) VALUES ('WA','WASHINGTON'); INSERT INTO states (id,name) VALUES ('WV','WEST VIRGINIA'); INSERT INTO states (id,name) VALUES ('WI','WISCONSIN'); INSERT INTO states (id,name) VALUES ('WY','WYOMING'); INSERT INTO states (id,name) VALUES ('AA','AA UNKNOWN'); INSERT INTO states (id,name) VALUES ('AE','AE UNKNOWN'); INSERT INTO states (id,name) VALUES ('AP','AP UNKNOWN');

How to total up entries in a database

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 ;

Categories