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)
)";
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.
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
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');
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 ;