Relational tables: a 3rd table with relations - php

I'm building a php page that will show an specific banner when the user enters his/her phone number in a form field.
So here's my logic for the database:
Table phones with fields: id, name of user and phone number.
Table banners with fields: id, banner's name/title and banner (path to the image).
Table relation with fields: here's where the phone number should be related to a banner and where I need your help :)
And here's my logic for the php page:
-form gets the phone number
-I query the data base
-I show the banner related to the phone number entered in the form.
Below is the code for the table creation so far .. as you'll see don't know how to advance.
Thanks a million
CREATE TABLE phones(
id_phone INT NOT NULL AUTO_INCREMENT,
nombre VARCHAR(30),
number INT (9),
PRIMARY KEY (id_phone)
) TYPE = INNODB;
CREATE TABLE banners (
id_banners INT NOT NULL AUTO_INCREMENT,
id_phone INT NOT NULL,
name VARCHAR(250),
banner VARCHAR(250),
PRIMARY KEY(id_phone),
INDEX (id_phone),
FOREIGN KEY (id_phone) REFERENCES clientes(id_phone)
) TYPE = INNODB;

From your question, it seems that each phone number has only one banner associated with it. Therefore, delete the banners.id_banners field and add a phones.id_banners
Then to select the data, you can do a JOIN:
SELECT phones.id_phone, phones.nombre, phones.number,
banners.id_banners, banners.name, banners.banner
JOIN banners ON phones.id_banners = banners.id_banners
WHERE phone = '123-456-789'

First of all what's the question?
What can I mention at this step is, does the relation between this entities is one to one? If so, you'd better put all this data into one single table.
++
CREATE TABLE phones(
phone_id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(30),
number INT (9),
PRIMARY KEY (id_phone)
) TYPE = INNODB;
CREATE TABLE banners (
banner_id INT NOT NULL AUTO_INCREMENT,
phone_id INT NOT NULL,
name VARCHAR(250),
banner VARCHAR(250),
PRIMARY KEY(id_phone),
INDEX (id_phone),
FOREIGN KEY (phone_id) REFERENCES clientes(phone_id)
) TYPE = INNODB;
and the query would be:
$query = "SELECT * FROM clients LEFT JOIN banners USING(phone_id) WHERE clients.number='.$number.'";

Related

How to store list of strings in php/sql table

say I have object user that has a name and a list of emails of limitless lenght. Right now I have 3 tables in my database.
CREATE TABLE NAME (
name TINYTEXT primary key not null
)
CREATE TABLE EMAILS (
id int primary key not null,
email varchar(30)
)
CREATE TABLE USERS (
users_name int references NAME(ID),
users_email int references EMAILS(id),
constraint pk_USERS primary key (users_name, users_email)
)
I feel that there is some error in the making of my tables.
And here is how I am trying to insert the name and email into my database.
protected function setUser($name,$email){ $stmt = $this->estabConnect()->prepare("INSERT INTO USERS(users_email, users_name) VALUES (?,?)");
if(!$stmt->execute(array($email, $name))){ $stmt= null;
header('location: ../index.php?error=stmtfailed');
exit();
}
$stmt=null;
The SQL statement fails
I think the problem is with the sql statment
you must ask your self can users share an email address
yes your design is sorrect as you have a n:m relationship ehivh i represente dby the bridge table
no, your design is wrong and you need to show that a user can have any email adresses
The design would wlook like
CREATE TABLE USER(
id BIGint primary key not null,
name TINYTEXT
)
CREATE TABLE EMAILS (
user_idBIGint primary key not null,
email varchar(30)
)
But normally you want only one email adress per users or maybe a second for office, so that you have a 1:! relationship which is only a part of the user table
a more extended version has not an email table but instead a table that is linked to the user(id) and where you can have many adresses with phone and location in short a 1:n relationship
For your question
CREATE TABLE NAME (
ID int primary key not null,
name TINYTEXT not null
);
CREATE TABLE EMAILS (
id int primary key not null,
email varchar(30)
);
CREATE TABLE USERS (
users_name int references NAME(ID),
users_email int references EMAILS(id),
constraint pk_USERS primary key (users_name, users_email)
);
INSERT INTO USERS(users_name,users_email) VALUES (1,1)
SELECT * FROM USERS
users_name | users_email
---------: | ----------:
1 | 1
db<>fiddle here
To get that to work i changed your design, to corresond with your brisge table.
so as long as you don't enter the actual anme and email adress every should work

proper query in php

I had some help with this code:
SELECT *, IF(newcost - cost > 500, newcost - cost, 0) as raiseby FROM
(
SELECT bp.*, b.company,(IF(bp.cost*1.2 < ls.maximumbid, bp.cost*1.2, bp.cost)) as newcost
FROM `windows_brands_products` bp
LEFT JOIN `windows_brands` b
ON bp.brand_id = b.id
JOIN Windows_last_submissions ls
JOIN windows_materials dm
WHERE ls.username = '$current_user->user_login'
AND bp.width = ROUND(ls.width)
AND bp.height = ROUND(ls.height)
AND bp.material IN (dm.name)
AND bp.type = ls.type
AND IF (ls.minimumbid != '0.00',bp.cost BETWEEN ls.minimumbid AND ls.maximumbid,bp.cost <= ls.maximumbid)
ORDER BY b.company ASC
) as temptable
The goal is to display a line stating that the user missed a (or some) companies by $500 and state how much the user needs to increase their max. bid (ls.maximum) in order to come within parameters of the query. It looks to me like it will look something like:
echo 'If you increase your maximum bid by '.$row->raiseby.',. $row->temptable.'can perform your installation';
I don't seem to get a positive response by using that statement...My assumptions could also be off about the way to reference each "row".
Am I wrong to assume that when you use "AS" parameter in sql the word to the right becomes the new row name?
Anyone have any idea as to how I could word this query to achieve my results?
Thanks
EDIT* I'm having a problem with sqlfiddle showing an error I can't figure out. it states 'incorrect integer value: column 'id' row 1':
CREATE TABLE windows_brands
(
id int(11),
company varchar(255)
);
INSERT INTO windows_brands
VALUES ('1','Anderson');
CREATE TABLE windows_brands_products
(
id int(11) AUTO_INCREMENT,
brand_id int(11),
width decimal(12,2),
height decimal(12,2),
material varchar(30),
type varchar(30),
cost decimal(12,2),
PRIMARY KEY (id)
);
INSERT INTO windows_brands_products
VALUES ('','2','30','36','wood','double hung','1500.00');
CREATE TABLE Windows_submissions
(
id int(11) AUTO_INCREMENT,
name varchar(30),
username varchar(12),
width decimal(12,2),
height decimal(12,2),
chosenmaterial varchar(30),
type varchar(30),
minimumbid decimal(12,2),
maximumbid decimal(12,2),
PRIMARY KEY (id)
);
INSERT INTO Windows_submissions
VALUES ('','Casey','caseys','30','36','wood','double hung','1000.00','1700.00');
CREATE TABLE windows_materials
(
id int(11) AUTO_INCREMENT,
name varchar(30),
PRIMARY KEY (id)
);
INSERT INTO windows_materials
VALUES ('','wood');
Can you see what the problem is - I've been looking it over for a while and can't see it.
This query works fine: http://sqlfiddle.com/#!9/22a74/1
In the query I'm trying to get to work...If, say, I make a maximumbid of $300 (for example) more than what the company charges, I should be able to echo something in a loop like, the nearest company is ____ and is $300 more than your maximumbid. I just don't know how to reference the aliases like 'raiseby' and 'temptable'. If I put that query into sqlfiddle 0 results show...which I want the same results like the company and the newcost to show- but also I want to let the user know how much they missed the target if, say, no results show.

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

Relative MySQL Database

I have a MySQL database table which is built as follows.
The numbers below the classes denote a "level" for the class, such as high, medium, or low, with 0 being does not attend that class.
I need to build another table to save homework assignments for each class, but I'm a bit lost as to how I'd build that table, specifically denoting what the exact columns of the rows have to be, since each class does not have something specific that denotes it.
A properly normalized structure would have a separate table for courses, giving each an id, and another table placing students into courses by including a student id, course id, and level.
CREATE TABLE students (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(64) NOT NULL,
password VARCHAR(64),
email VARCHAR(...)
UNIQUE KEY (username)
);
CREATE TABLE courses (
id INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(64) NOT NULL
);
/* If a record doesn't exist for a course and student,
the student isn't enrolled in that course. Otherwise,
the level is defined here */
CREATE TABLE enrollments (
id INT NOT NULL PRIMARY KEY,
student_id INT NOT NULL,
course_id INT NOT NULL,
level INT NOT NULL,
/* Each student may be enrolled only once per course */
UNIQUE KEY (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students (id),
FOREIGN KEY (course_id) REFERENCES courses (id)
);
Finally then, you can create a table for assignments assigned in each course:
CREATE TABLE assignments (
id INT NOT NULL PRIMARY KEY,
course_id INT NOT NULL,
description TEXT
/*... other columns related to the assignment as necessary*/
);
And for students to complete assignments if necessary:
CREATE TABLE student_assignments (
student_id INT NOT NULL,
assignment_id INT NOT NULL,
assignment_body TEXT, /* or whatever... */
/* Or to track when completed */
submitted_timestamp TIMESTAMP,
PRIMARY KEY (student_id, assignment_id),
FOREIGN KEY (assignment_id) REFERENCES assignments (id),
FOREIGN KEY (student_id) REFERENCES students (id)
);

wordpress plugin sql setup

I have set up four additional tables for my plugin to use what I am trying to do is take a name and assign it a ID then use this data to populate drop down menus with a name and the same for class and position I am unsure as to how to do this correctly this is what i have so far.
$sql = "CREATE TABLE $tableName (
recordID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(recordID),
driverID int,
driverName varchar(30),
classID int,
driverClass varchar(20),
posID,
driverPosition varchar(6),
trackName varchar(30),
raceDate date
);";
$sql = "CREATE TABLE $driverTableName (
driverID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(driverID),
driverName varchar(30)
);";
$sql = "CREATE TABLE $classTableName (
classID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(classID),
className varchar (20)
);";
$sql = "CREATE TABLE $posTableName (
posID int NOT NULL AUTO_INCREMENT,
PRIMARY KEY(posID),
posName varchar(6)
);";
The bottom three tables will store the data I want to populate the drop down boxes to create a record with I am unsure as to how to link them to the top table where this record will be stored.
This is pretty much a indexing issue. If you are going to access the database separately to the standard calls that Wordpress provides, you should at the very least use http://codex.wordpress.org/Class_Reference/wpdb as it will save you some coding time.
The rest of it is a MySQL question. (Assuming you are using MySQL) In how to properly index the data together and then parsing the data as it comes in.

Categories