I have 2 tables in a database. One is for product data, and the other is for the images of the products. I have to set up an slider in the index of my page, and there will go specific images (like products with 50% discount, or sth like that). I'll make a query to my product table in my database, to get the id of the product that are on sale
$query1="SELECT id FROM products WHERE price<'100'";
$query2=mysql_query($query1);
$idSales=mysql_fetch_array($query2);
So, now i have an array with the id's of the products that I'm interested in, and here comes the trouble. How can I deal with that array that mysql_fetch_array returned to me? How can I make the query to the images table (
in that table I have the id of the corresponding product, so I've to match one with the other)
You can join these two tables to get images of the products.
Run this query
SELECT i.`imageName`
FROM products p INNER JOIN images i
ON p.`id`=i.`idProduct`
WHERE p.price<100
You can try running multiple inline queries.For performance considerations I would not suggest doing this but it can get the job done with less number of records:
while($row = mysql_fetch_array($query2)){
$id = $row['id'];
//now create a new query
$img_query = "SELECT * FROM ... where id=".$id;
//run query and process results
$img_result = mysql_fetch_array($img_query)
//work with image related results here
}
You can also create a sql array and run the query after the while loop is finished.
Or you can use subrequest
SELECT * FROM images WHERE product_id IN (SELECT id FROM products WHERE price < '100')
Related
SELECT
products.productID, products.name, products.type, products.price, products.image_url
FROM `products`
JOIN `orders` ON products.productID = orders.productID
WHERE customerID = '$id'
LIMIT 0 , 30 ";
and I looped this through and got a bunch of records. However I have joined two tables and I want to remove the item from the list but not actually delete the item from the table. I am trying to create similar to a shopping cart functionality where you can remove an item without actually deleting the item from the tables. is there any possible way to do it in php?
Thank you very much.
In php you can skip over the records that you don;t want to display before sending the data out to HTML.
In HTML you will need to use JavaScript to remove the items from the list(s).
My old post but a possible solution could be insert the joined result from the query in the question to new table and reference it with customer ID, that way it is safer or, just use javascript to remove that particular block.
I am creating a search box in PHP and using MySQL as the database but when searching there are 3 tables, Colours, Products and Categories, these all have an ID number and can be linked. I have tried to use INNER JOIN, LEFT, RIGHT, everywhere but no luck, the query will sometimes work, spit out multiple items. So I am looking at creating a one-table-fits-all scenario where all the table field names will be in one and I can easily query that table. I have manually created the table but is there anyway of coping the data from the 3 tables into that main one? I do not mind doing it separately if it is a query that only handles one table but I would love not to have to manually type all the data as there is 600+ rows.
Here is the code I am currently trying to use:
SELECT
categories.Product_Type, items_colors.ColourImageurl,
items_list.description, items_list.Description2,
items_list.title, items_list.id, categories.title AS title2,
items_colors.itemID, Colour Name
FROM items_list
LEFT JOIN categories ON categories.Product_Type = items_list.CatID
LEFT JOIN items_colors ON items_list.id = items_colors.itemID
WHERE items_list.visible = 1 AND
Colour Name LIKE '%".$search."%'
Categories defines what type of product you are selecting, items_list has a list of all the sub category names and item_colors has a list of all the colour names that link to the items_list products. When I use this query it outputs 4 copies of one item and I'm not sure why.
If you are getting data from a query, you can use "create table as select" statement to create the new table, with data from old tables.
CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name
[(create_definition,...)]
[table_options]
[partition_options]
select_statement
check here for more info : http://dev.mysql.com/doc/refman/5.1/en/create-table.html
I have this query below.. All of the relationships of the tables are one to one relationships except for ASSOCPRODUCTS table where there are two products per order. Everything seems to work fine, except for that my query returns only one row, and thus, will only return ONE product id when there are in fact two. I understand why it's only pulling one, in that there is only ONE order per orderID, but there are two Associated Products for each contract and I need to get each product id. in the Assocproducts table, each product gets its own row, as it is a one to many wit the contracts table.
Is it possible to get that information using inner joins, or do I need to run another query?
$orderid = $_POST['orderid'];
$res = mysql_query ("
SELECT company.name as cname,
orders.datemade as datemade
orders.p1quantity as p1q,
orders.p2quantity as p2q,
assocproducts.productid as pid,
assocproducts.price as pprice,
inventory.name as pname,
inventory.quantity as pquantity
FROM orders
INNER JOIN contracts ON (contracts.id = orders.contractid)
INNER JOIN company ON (contracts.companyid = company.id)
INNER JOIN assocproducts ON (contracts.id = assocproducts.contractid)
INNER JOIN inventory ON (assocproducts.productid = inventory.id)
WHERE orders.id = " . $orderid);
$order = mysql_fetch_assoc($res);
Please let me know if I need to give more information.
$order isn't in a loop, because I need to display ONLY the order info for this specific order. It's an AJAX trigger on click.
Thanks!
I think you're wrong stating that only one row is returned. I created a fresh schema with only the columns used in your query, populated it with sample data and got out all matching results. I think the problem is with your usage of mysql_fetch_assoc() function. Semantics of this function are clear:
Returns an associative array of strings that corresponds to the fetched row, or FALSE if there are no more rows.
so my guess is you never call mysql_fetch_assoc() again.
Given semantics of INNER JOIN and your data constraints, your query will always produce 0 or 1 rows. If you don't know why - please read SQL JOIN types & behavior. So, you have two options to fetch order details and information about associated products:
Use two separate select statements - one for order details (always 1 row), second for associated products (2 rows). Iterate on results of the second query - you will get information about one product for each row fetched.
Keep your existing query, but change the way you retrieve data from it by iterating over all rows (note that order information will be present in all fetched rows and will be the same for all of them):
$firstRow = true;
while (($order_product = mysql_fetch_assoc($res)) !== FALSE) {
if ($firstRow) {
// do something with order info
// but don't repeat it for consecutive rows
$firstRow = false;
}
// do something with currently fetched associated product info
}
It's a matter of taste, but I'd go with the first option - it looks less hacky.
I have two tables, one contains a lot of product information such as product_name product_id etc and the other contains a list of product_ids and where or not that product is marked as on sale. I would like to be able to create something that I can run regularly through a Chron job which will look at table1.product_discount_id and if the product has anything in that column other than 0 it will update table2.product_on_sale to yes. I am having trouble with understanding how to make sure that I only alter the fields for the products with a discount id of anything other than 0. I have got this far in the php script:
mysql_connect("myhost", "mydb", "mypassword") or die(mysql_error());
mysql_select_db("mydb");
$result = mysql_query("SELECT * FROM jos_vm_product WHERE product_discount_id != '0'");
while($row = mysql_fetch_array($result))
{
echo $row['product_id'];
echo ",";
}
and that will produce a list of the product_ids for the products I wish to change the table2.product_on_sale field to yes. I'd like to then say if the product ids previously retrieved match a product_id in table2.product_on_sale field then change to yes. Any help would be greatly appreciated.
Regards
Ali.
mysql_query("update table1, table2 set table2.product_on_sale=true where table1.product_id=table2.product_id and table1.product_discount_id!=0")
you shouldn't be updating with a cron job but using a join in the select to find what's on sale
I have two tables, one holds the information of contributors to my site and one holds information on photographs contributed.
For the admin side of the site, I want to create a table using php and mysql that displays all contributors but also counts the number of photographs each contributor has available for the site.
I get the list of names using this code
SELECT *
FROM site_con
ORDER BY surn ASC
I have then set up a loop to list all the names but have added a query within that loop to count the number of photographs using this code
$contributor = $row_rsContrib['con_Code'];
mysql_select_db($database_connGrowl, $connGrowl);
$query_rsCounter = "SELECT COUNT(*) AS Count
FROM site_phts
WHERE photter = $contributor";
$rsCounter = mysql_query($query_rsCounter, $connGrowl) or die(mysql_error());
$row_rsCounter = mysql_fetch_assoc($rsCounter);
$totalRows_rsCounter = mysql_num_rows($rsCounter);
The only problem is when '$contributor' is not in the photographs table, it returns an error.
Any ideas?
You can get the list of contributors & the number of photos in a single query:
SELECT sc.*,
COALESCE(x.numPhotos, 0) AS numPht
FROM SITE_CON sc
LEFT JOIN (SELECT sp.photter,
COUNT(*) AS numPhotos
FROM SITE_PHTS sp
GROUP BY sp.photter) x ON x.photter = sc.con_code
ORDER BY ssc.surn
Your query fails because a photographer doesn't necessarily have contributions -- the query above returns the list of photographers, and those without photos associated will have a numPht value of zero. Here's a primer on JOINs, to help explain the OUTER JOIN that's being used.
Actually the best way to do this is by using MSQL to count rather than PHP:
SELECT site_con.*, COUNT( photo_id )
FROM site_con
LEFT JOIN site_phts ON site_con.con_Code = site_phts.photter
GROUP BY site_con.con_Code
ORDER BY site_con.surn
The LEFT JOIN has the special property of creating NULL entries when there is no row in the right table (photos) that matches a contributor row. COUNT will not count these NULL entries. (You need some unique column in the photos table, I used photo_id for that.)
this is the relation between Contributors and photographs:
1 photograph can have a most 1 Contributor
1 Contributor can have a most infinit photograph
Contributor <-(0,n)------(0,1)-> Photograph
so you might wanna add a connexion betweet those two tables, I mean you add the con_id to the photographs table (as a column).
this way you'll be able to retrieve all the informations in one SQL query.
(like OMG Ponies just said)
Do something like this, I believe this should work :
$result = mysql_query("SELECT COUNT(*) AS Count FROM site_phts WHERE photter = '$contributor'"); // put the single quote if $contributor is a string value
//use mysql_fetch_array
if ($row = mysql_fetch_array($result, MYSQL_NUM)) {
printf("ID: %d", $row[0]);
}
Hopefully this works, Good luck mate !