PHP - SQL Join Query - php

I have this MySQL Structure:
CREATE TABLE Fields (
ID INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ForUser VARCHAR(255) NOT NULL,
ForCategory VARCHAR(100) NOT NULL,
FieldName VARCHAR(100) NOT NULL
);
CREATE TABLE Content (
ID INT(10) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
ForUser VARCHAR(255) NOT NULL,
ForCategory VARCHAR(100) NOT NULL,
ForField VARCHAR(100) NOT NULL,
FieldContent VARCHAR(255) NOT NULL
);
Now I want to make SQL Query that list results in HTML Table. As Head Table I want to list FieldName from Fields, and as Table Body I want to list FieldContent from Content. Also in WHERE clause must be ForUser AND ForCategory... to list Content for each field. I'm tried with SQL Join, but I'm spend 3 hours without success. Can, please, someone write me an example how to display this.

If I understand this request correctly (you're a little light on detail), you will need a use a few components to achieve your goal:
Two sql queries (one for the table header and one for the table body)
Some php or another scripting language to display your results as html.
Your first query will just bring back the field names, filtered by user and category:
select ID, FieldName from Fields where ForUser = 'some_user' and ForCategory = 'some_category' order by ID;
IN your php or other code, you need to iterate through the results and display each result wrapped in the html tags, eg:
echo '<table><tr>';
$fields = # mysql_query ("select ID, FieldName from Fields where ForUser = 'some_user' and ForCategory = 'some_category' order by ID;", $connection);
while ($fields_result = mysql_fetch_assoc($fields)) {
echo '<th>' . $fields_result['FieldName'] . '</th>;
}
echo '</tr>';
Then run a second sql query to bring back the contents:
select
FieldContent
from
Content c join
Fields f on
c.ForField = f.FieldName and
c.ForUser = f.ForUser and
c.ForCategory = f.For Category
where
f.ForUser = 'some_user' and
f.ForCategory = 'some_category'
order by ID;
And in a similar fashion, iterate through the results in php to build the content rows in the table.
Note that I'm ordering on the PK in the Fields table to ensure that the content comes back in the same order as the fields. This approach might not suffice, you may need to add a "sequence" field if you need a specific field order.
Also note my prevous comment that you would do well to revise your database structure. You don't need to repeat all the fields in the Content table, you can just add a foreign key referencing the ID of the Field record

Table join query:
SELECT
a.ID,
a.ForUser,
b.ForUser,
a.ForCategory,
b.ForCategory,
a.FieldName,
b.ForField,
b.FieldContent
FROM
Fields a,
Content b
WHERE
a.ForUser = '' AND b.ForCategory = ''

Related

Auto primary key insert custom table $wpdb

I need to insert to custom table that has primary key 'id' by number, but I got this problem for example
I have 5605 rows (start with id = 1) in my table,so I have to set current id = 5606 to insert.
1/I set $data['id'] = 5606 by hand to insert it, it works fine. current row with id 5606 is inserted.
but I want it automatically get the right id to insert so I do
2/select * to returns the current number of rows in table, it returns 5604 (always lesser by 1 when I check database has 5605). so I + 2 then do insert.
It ends up insert 3 times like 5606 5607 5608 in my table.
Please help me here is my code
$data = array(
'name' => 'naomi',
'ability' => 'walk',
);
$wpdb->get_results("SELECT * FROM contest");
$numid = $wpdb->num_rows;
$numid +=2;
$data['id'] = $numid;
$wpdb->insert('contest', $data);
The given number is for example, my problem is in that format.
Just declare column id (or whatever you use as primary key) as AUTO_INCREMENT (in MySQL) or SERIAL (in PostgreSQL) and insert all other columns but your primary key.
Example:
CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
);
INSERT INTO persons (LastName,FirstName,Address,City) VALUES (
'Sample','Person','Sample-street','Sample-city'
);
More than! You should not use any manual inserts for primary keys, because it can make you a lot of problems with handling unsuccessfull queries etc.
SECOND PART. To return number of rows in your table just use
SELECT COUNT(id) FROM persons;

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.

what's wrong with this SQL statement causing column count doesn't match value count at row 1?

Mysql table (migration_terms) fields are as follows
oldterm count newterm seed
I used the following create table statment.
CREATE TABLE `migration_terms`
(
`oldterm` varchar(255) DEFAULT NULL,
`count` smallint(6) DEFAULT '0',
`newterm` varchar(255) DEFAULT NULL,
`seed` int(11) NOT NULL AUTO_INCREMENT, PRIMARY KEY (`seed`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
And It works, no problems there.
but then when I used the following insert into statement to populate it;
"INSERT INTO migration_terms
SELECT looseterm as oldterm,
COUNT(seed) AS count
FROM looseterms
GROUP BY looseterm
ORDER BY count DESC "
I get this error;
Column count doesn't match value count at row 1
I cannot figure out why?
If you need the table structure of the looseterms table, it was created by the following create table statement.
CREATE TABLE looseterms
(
`seed` INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
`looseterm` varchar(255)
)
You need to specify the columns if your select statement has fewer columns than the table
"INSERT INTO migration_terms
(oldterm,
count)
SELECT looseterm AS oldterm,
Count(seed) AS count
FROM looseterms
GROUP BY looseterm
ORDER BY count DESC "
From MySql docs on Insert Syntax
If you do not specify a list of column names for INSERT ... VALUES or
INSERT ... SELECT, values for every column in the table must be
provided by the VALUES list or the SELECT statement. If you do not
know the order of the columns in the table, use DESCRIBE tbl_name to
find out.
Your insert is adding 2 columns of data, whereas your table's definition has 4 columns

PHP: How to get data from 2 tables

If I log in with my email and password in table 'students', how can I get the data from the table 'data' where the emailadresses match?
CREATE TABLE `students` (
`email` varchar(150) NOT NULL,
`password` varchar(150) NOT NULL
)
CREATE TABLE `data` (
`student_id` varchar(50) NOT NULL,
`studygroup_id` varchar(50) NOT NULL,
`applied_courses` varchar(50) NOT NULL,
`study_results` varchar(50) NOT NULL,
`email` varchar(150) NOT NULL
)
Well, the easy answer would just be to execute a query like
SELECT * FROM data WHERE email = '$emailAddress'
Where $emailAddress is the email address that has been used to log in.
But you should really think about your schema design. Perhaps go and read some books/tutorials on the basics and there are a number of possible issues with what you have. You should probably have a numeric primary key on your "students" table and reference this as a foreign key in your other table. You should also think about renaming the second table. "Data" doesn't really describe what it does; everything (or very nearly) in a database is data! Plus all your id columns are varchars. Unless you have alphanumeric ids you should make these columns the correct type for the data they hold.
Please clarify question. Where's the password coming from? A script in PHP?
SELECT * FROM data WHERE student.email = "$my_email" AND student.password = "$my_password"
Students table should also contain the student_id
alter table student add column student_id int auto_increment primary key
then the query
select a.email, a.password,b.studentgroup_id, b.applied_course,b.student_result
from student a inner join
data b
on a.student_id=b.student_id
If you want to confirm login and get data in one query, use a LEFT JOIN, which in the following example will give you a result from the students table, even if there is nothing in the data table for that email address.
$query = "SELECT * FROM `students`
LEFT JOIN `data` ON `students`.`email` = `data`.`email`
WHERE `students`.`password` = '" . $password . "'
AND `students`.`email` = '" . $email. "'";
Note: if there are multiple rows in the data table for the email address, each row will be returned and will contain identical student.password and student.email values.

PHP/MySQL Search code and logic for relational database schema

I have created this database schema and with help from several users on here, I have a database which takes user submitted business entries stored in the business table, which are additionally grouped under one or several of about 10 catagories from the catagories table, in the tbl_works_catagories table by matching the bus_id to the catagory id.
For example, bus_id 21 could be associated with catagory_id 1, 2, 5, 7, 8.
CREATE TABLE `business` (
`bus_id` INT NOT NULL AUTO_INCREMENT,
`bus_name` VARCHAR(50) NOT NULL,
`bus_dscpn` TEXT NOT NULL,
`bus_url` VARCHAR(255) NOT NULL,
PRIMARY KEY (`bus_id`)
)
CREATE TABLE `categories` (
`category_id` INT NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`category_id`)
)
CREATE TABLE `tbl_works_categories` (
`bus_id` INT NOT NULL,
`category_id` INT NOT NULL
)
Now, what i want to do next is a search function which will return businesses based on the catagory. For example, say one of the businesses entered into the business table is a bakers and when it was entered, it was catagorised under Food (catagory_id 1) and take-away (catagory_id 2).
So a visitor searches for businesses listed under the Food catagory, and is returned our friendly neighbourhood baker.
As with all PHP/MySQL, i just can't (initially anyway) get my head around the logic, never mind the code!
You should setup foreign keys in your tables to link them together.
CREATE TABLE `business` (
`bus_id` INT NOT NULL AUTO_INCREMENT,
`bus_name` VARCHAR(50) NOT NULL,
`bus_dscpn` TEXT NOT NULL,
`bus_url` VARCHAR(255) NOT NULL,
PRIMARY KEY (`bus_id`)
)
CREATE TABLE `categories` (
`category_id` INT NOT NULL AUTO_INCREMENT,
`category_name` VARCHAR(20) NOT NULL,
PRIMARY KEY (`category_id`)
)
CREATE TABLE `tbl_works_categories` (
`bus_id` INT NOT NULL,
`category_id` INT NOT NULL,
FOREIGN KEY (`bus_id`) REFERENCES business(`bus_id`),
FOREIGN KEY (`category_id`) REFERENCES categories(`category_id`)
)
Then your search query would be something like:
SELECT b.*
FROM business b, categories c, tbl_works_categories t
WHERE
b.bus_id = t.bus_id AND
c.category_id = t.category_id AND
c.category_id = *SOME SEARCH VALUE*
which using JOIN would be written as:
SELECT b.*
FROM business b
JOIN tbl_works_categories t
ON b.bus_id = t.bus_id
JOIN categories c
ON c.category_id = t.category_id
WHERE c.category_id = *SOME SEARCH VALUE*
Maybe you want something like this:
SELECT `bus_id` FROM `tbl_works_categories` WHERE `category_id` = *some id from the search*
AND `category_id` = *some other id from the search*;
Although you'd need those ids- there are a few ways to do this, I'll describe probably the most straight forward...
You get categories from $_POST, so let's just say you have 2 of them entered. (Food, and take-away). Parse these however you want, there are multiple ways, but the point is they're coming from $_POST.
execute this sort of thing for each one you find:
SELECT `category_id` FROM `categories` WHERE `category_name` LIKE '%*the name from $_POST*%';
Store these results in an array...based on how many you have there you can build an applicable query similar to the one I describe first. (Keep in mind you don't need and AND there, that's something you have to detect if you return > 1 category_id from the second query here)
I'm not going over things like security..always be careful when executing queries that contain user submitted data.
An alternate solution might involve a join, not too sure what that'd look like off the top of my head.
Good luck.
If you want all businesses that are related to the given category-id, your SQL-statement would look something like this:
SELECT `business`.`bus_name`
FROM `business`
WHERE `business`.`bus_id` = `tbl_works_categories`.`bus_id`
AND `categories`.`category_id` = `tbl_works_categories`.`category_id`
AND `categories`.`category_id` = 1;
Where 1 in this case is your food-category, but could be your PHP variable where the ID of the category the user selected is stored.
And one hint: Be sure to name your tables either in plurar or in singular. You are mixing both and could get confused.

Categories