How to test PHP and MySQL memory when it is running? - php
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');
Related
How to automatical add data to a table with a foreign key php [MariaDB]
How can I use php to add data to the foreign such that the IDs match: In this example, I have a table for a 'member' and a separate table for 'emails'. A member can have multiple emails and therefore a separate table is created that stores emails with the member ID as a foreign key. How can I write code that inserts data into both tables when fields have been submitted? My most recent (unsuccessful) attempt: PHP block: $query= "INSERT INTO Members(FIRST_NAME, LAST_NAME, TITLE, INSTITUTION) VALUES ('$first_name', '$last_name','$title','$institution'); INSERT INTO EMAIL(Members_ID, EMAIL) VALUES (LAST_INSERT_ID(), '$email'); INSERT INTO WEBSITE(Members_ID, WEBSITE) VALUES (LAST_INSERT_ID(), '$website');"; mysqli_query($connection,$query) or die(mysqli_error($connection)); SQL Block: CREATE TABLE Members( ID INT UNSIGNED NOT NULL AUTO_INCREMENT UNIQUE, FIRST_NAME TEXT(16), LAST_NAME TEXT(16, TITLE TEXT(7), /** 7 CHARS for 'Student'*/ INSTITUTION VARCHAR(2048), PRIMARY KEY(ID) ); CREATE TABLE EMAIL( Members_ID INT UNSIGNED NOT NULL UNIQUE, EMAIL VARCHAR(2048), FOREIGN KEY (Members_ID) REFERENCES Members(ID) ); CREATE TABLE WEBSITE( Members_ID INT UNSIGNED NOT NULL UNIQUE, WEBSITE VARCHAR(2048), FOREIGN KEY (Members_ID) REFERENCES Members(ID) );
You could use, for example mysqli_multi_query, after having retrieved the ID assigned to the first insertion (I wouldn't rely too much on the LAST_INSERT_ID() in this case): $conn = mysqli_connect(...); $query = "INSERT INTO Members (FIRST_NAME,LAST_NAME,TITLE,INSTITUTION) VALUES ('$first_name','$last_name','$title','$institution')"; mysqli_query($conn, $query); $lid = mysqli_insert_id($conn); $query = "INSERT INTO EMAIL (Members_ID,EMAIL) VALUES ($lid,'$email');"; $query .= "INSERT INTO WEBSITE (Members_ID,WEBSITE) VALUES ($lid,'$website');"; mysqli_multi_query($conn, $query);
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) )";
phpMyAdmin creating
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.
Query consult doctrine composite key
Hello I am try to take data with dictrine 2.5 from a table but I do not know how to do it. SQL FILE DROP DATABASE composite_key; CREATE DATABASE composite_key; USE composite_key; CREATE TABLE company ( id_company INT NOT NULL AUTO_INCREMENT, name VARCHAR(200) NULL, PRIMARY KEY (id_company) ); CREATE TABLE users ( id_user INT NOT NULL AUTO_INCREMENT, name VARCHAR(200) null, PRIMARY KEY (id_user) ); CREATE TABLE reference ( id_company INT NOT NULL, id_user INT NOT NULL, createat TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id_company), FOREIGN KEY (id_company) REFERENCES company(id_company), FOREIGN KEY (id_user) REFERENCES users(id_user) ); INSERT INTO users (`name`) VALUES ('test1'); INSERT INTO users (`name`) VALUES ('test2'); INSERT INTO users (`name`) VALUES ('test3'); INSERT INTO company (`name`) VALUES ('company1'); INSERT INTO company (`name`) VALUES ('company2'); INSERT INTO company (`name`) VALUES ('company3'); INSERT INTO reference (`id_company`,`id_user`) VALUES (1,1); INSERT INTO reference (`id_company`,`id_user`) VALUES (2,2); INSERT INTO reference (`id_company`,`id_user`) VALUES (3,3); QUERY WHICH I HAVE TRIED $dql = "SELECT r FROM CompositeBundle:Reference r JOIN CompositeBundle:Company c JOIN CompositeBundle:Users u WHERE c.idCompany = 1 AND u.idUser = 1 "; $dql = "SELECT r FROM CompositeBundle:Reference r JOIN r.idUser JOIN r.idCompany WHERE r.idCompany = 1 AND r.idUser = 1 "; If somone know to do these dql please sat It.
multi to multi relational database not working
I am studying relational databases on my own and after reading some articles I am having trouble implementing them. Due to my lack of experience with relational databases I believe that my error can be in any of the following 3 (if not in all 3) steps: Table Creaton Value Insertion Query call I should point out that there aren't any syntax errors or something like that. We are talking about an error in my understanding so I will approach the problem in detail. The tables: For the abstraction I have chosen to have people and the drinks which they like (1 person can like many drinks, one drink can be liked by many people. Here is the code for the table People (It has 2 names, and a primary key): CREATE TABLE `People` ( `PeopleID` INT NOT NULL AUTO_INCREMENT, `FirstName` VARCHAR(25), `LastName` VARCHAR(25) NOT NULL, PRIMARY KEY (`PeopleID`) ) Here is the table Drinks (Name of drink, some number in menu or something like that for example and the primary key) CREATE TABLE `Drinks` ( `DrinksID` INT NOT NULL AUTO_INCREMENT, `Code` VARCHAR(10) CHARACTER SET ascii COLLATE ascii_general_ci NOT NULL, `Name` VARCHAR(100) NOT NULL, PRIMARY KEY (`DrinksID`) ) And lastly the table PeopleDrinks: CREATE TABLE `PeopleDrinks` ( `DrinksID` INT NOT NULL default 1, `PeopleID` INT NOT NULL default 1, PRIMARY KEY (`DrinksID`,`PeopleID`) ) Note: from here I saw the example given for the third table and pretty much copied it. Value insertion: People input: INSERT INTO People (FirstName, LastName) VALUES ('John', 'Smith') INSERT INTO People (FirstName, LastName) VALUES ('Sam', 'Johnson') INSERT INTO People (FirstName, LastName) VALUES ('Michael', 'Morgan') Drinks input: INSERT INTO Drinks (Code, Name)VALUES ('#543', 'Beer') INSERT INTO Drinks (Code, Name) VALUES ('#132', 'Vodka') INSERT INTO Drinks (Code, Name) VALUES ('#123', 'Wine') PeopleDrinks input: Note: The id of the drinks are 4, 5 and 6. Not 1, 2, 3. INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (1, 4) INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (2, 5) INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (3, 6) Above we give as favorite one drink to every person. Below we will make one person like all the drinks: INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (1, 5) INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (1, 6) And finally the query call: //Consider $link an established, working connection to the database $result = mysqli_query($link, "SELECT `People`.* FROM `People` JOIN `PeopleDrinks` ON `People`.`PeopleID` = `PeopleDrinks`.`PeopleID` WHERE `PeopleDrinks`.`DrinksID` = 5"); while($row = mysqli_fetch_array($result)) { echo $row['FirstName'] . " " . $row['LastName']; echo "<br/>"; } The above code, should print the name of anyone who likes the drink with id 5. I don't get an error, but I don't get any output.
You said the id of the drinks are 4,5,6 In the INsert you have used INSERT INTO PeopleDrinks (DrinksID, PeopleID)VALUES (1, 4) INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (2, 5) INSERT INTO PeopleDrinks (DrinksID, PeopleID) VALUES (3, 6) The drink ids(first number) are 1,2,3 instead of 4,5,6 or something like that. I think your order is wrong.
Your many to many table needs foreigns key : CREATE TABLE `PeopleDrinks` ( `DrinksID` INT NOT NULL, `PeopleID` INT NOT NULL, PRIMARY KEY (`DrinksID`,`PeopleID`), FOREIGN KEY (`DrinksID`) REFERENCES `Drinks`(`DrinksID`), FOREIGN KEY (`PeopleID`) REFERENCES `People`(`PeopleID`) ) Remove the default values of DrinksID and PeopleID, this make no sense. Then when you do your insert, you will be sure that the data you are trying to insert are right. I think that your insert are false. When you say that your IDs are what they are, you are wrong. This is particulary true if your are doing a lot of inserts and deletes. Autoincrement will keep going forever, and you can't be sure. With Foreign Keys, the RDBMS will tell you if there is something wrong with your relations. Anyway, your query looks great, so no problem for that.