How to call one cell of a database? - php

I am very new to using PHP so I am asking for some help. I have this code which works fine (I got it online from somewhere).
$data = mysql_query("SELECT * FROM products")
or die(mysql_error());
print "<table border cellpadding=3>";
while($info = mysql_fetch_array( $data ))
{
print "<tr>";
print "<th>title:</th> <td>".$info['title'] . "</td> ";
print "<th>info:</th> <td>".$info['information'] . " </td></tr>";
}
print "</table>";
But what PHP would I use to pull just one cell? For example, I have 9 items in my db with productIDs how could I call just the name or price or description for that particular product?
Thanks in advance.

It sounds like you want a particular row, in which, case you would just changes your query to filter for some specific value that identifies the row. THis might look something like this:
SELECT * FROM products WHERE product_id = ?
Where ? is the known product_id value that you want to receive the full record for.
Also, since you are just learning, I should point out that you should not learn to use mysql_* functions. They are deprecated. Learn mysqli or PDO for interacting with MySQL.

To obtain just one cell try the following:
SELECT CellName FROM TableName Where productId = x
So to get the price you would do:
SELECT price FROM products WHERE productid=x
Where productid equals the specific product you talked about.

if you want to understand a bit more mysql I advise you to go to PhpMyAdmin and try those and think about the result:
SELECT * FROM products;
SELECT title, information AS lol FROM products;
SELECT title, count(*) AS count FROM products;
SELECT * FROM products WHERE title = 'XXXX';
SELECT *, count(*), CHAR_LENGTH(title) FROM products;
SELECT title AS lol FROM products;
you will understand better the query language i thinks.

please read this chapter http://dev.mysql.com/doc/refman/5.0/en/examples.html. it'll really help you.
I just want to say, you can retrieve any columns(s) in any condition column
SELECT column_name(s) FROM products WHERE colmnm_name = ?

Related

PHP: MYSQL select inside another MYSQL select?

I'm trying to place one mysql select inside another one and combine the results to be displayed.
this is my code:
$allattrs = "";
$sql69 = "SELECT * FROM product_details";
$query69 = mysqli_query($db_conx, $sql69);
$login_check69 = mysqli_num_rows($query69);
if($login_check69 > 0){
while($row69 = mysqli_fetch_array($query69, MYSQLI_ASSOC)){
$FID = $row69["id"];
$sql2s = "SELECT * FROM ATTRIBUTES WHERE id='$FID'";
$query2s = mysqli_query($db_conx, $sql2s);
$login_check2s = mysqli_num_rows($query2s);
if($login_check2s > 0){
while($row2s = mysqli_fetch_array($query2s, MYSQLI_ASSOC)){
// Get member ID into a session variable
$Sid = $row2s["id"];
$attr = $row2s["attr"];
$allattrs .= ''.$attr.', ';
}
}
$product_list .= '<tr>
<td>'.$allattrs.'</td>
</tr>';
}
}
The problem i'm having is that the $allattrs returns the values but it will put everthing together.
for example:
if one attr column in mysql database has apples, and another one has oranges, when i see the results of $allattrs on my PHP page i see this:
id 1 - apples
id 2 - apples, oranges
id 3 - apples, oranges, apples, oranges
etc etc
this is in fact wrong as each attribute value needs to stay true to their own id and product_details id field!
I'm not sure what I am doing wrong to cause this.
could someone please advise on this issue?
any help would be appreciated.
The right way to write your query is using JOIN, EXISTS, or IN. I think you would find this most natural:
SELECT a.id, GROUP_CONCAT(a.attr) as attrs
FROM ATTRIBUTES a
WHERE a.id IN (SELECT id FROM product_details)
GROUP BY a.id;
This replaces a bunch of your code.
Looks like you are only interested in the the attributes then try this out instead of the first sql:
SELECT * FROM ATTRIBUTES where id IN (SELECT id FROM product_details)
You need to set $allattrs to an empty string inside your first while loop, instead of only once before.
Apart from that, you should look into the following two topics: Normalization and JOINs.

Improve PHP Array to use on AJAX

I created a PHP file to populate a page, using AJAX, but I can't find a solution to my problem.
Here's my PHP and its Outputs:
$result = mysql_query("SELECT id, product, picture FROM table1 ORDER BY id DESC");
$products = array();
while($product = mysql_fetch_array($result, MYSQL_ASSOC)) {
$products[] = ($product);
}
$json = json_encode($products);
$output = isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json;
echo $output;
This will print:
[{"id":"5","product":"product5","picture":"picture5.jpg"},
{"id":"4","product":"product4","picture":"picture4.jpg"},
{"id":"3","product":"product3","picture":"picture3.jpg"},
{"id":"2","product":"product2","picture":"picture2.jpg"},
{"id":"1","product":"product1","picture":"picture1.jpg"}]
I want to add the field "In_Stock" on this Output using a another query to output something like this:
[{"id":"5","product":"product5","picture":"picture5.jpg","in_stock":"yes"},
{"id":"4","product":"product4","picture":"picture4.jpg","in_stock":"no"},
{"id":"3","product":"product3","picture":"picture3.jpg","in_stock":"yes"},
{"id":"2","product":"product2","picture":"picture2.jpg","in_stock":"yes"},
{"id":"1","product":"product1","picture":"picture1.jpg","in_stock":"no"}]
My question is: Its possible to use the value of the array (Inside the first While) to do a search in another table, add this value to products array and keep the same "layout" on the output above?
EDIT:
These are my tables:
TABLE1
id
product
picture
And the second one
TABLE2
id
user
product_id
in_stock
The same product may have different stocks depending on the User...
Yes, you could do another query, but it probably makes more sense to just alter the first query to include all the data you need, which would look something like this:
mysql_query("SELECT table1.id, table1.product, table1.picture, table2.in_stock
FROM table1
LEFT JOIN table2 ON (table1.id = table2.product_id
AND table2.user = " . intval($_SESSION['user']) . ")
ORDER BY table1.id DESC");
Edit: Added in the user from session per your comment. I used intval because I am assuming you are using an integer for the id of the user, and I don't know how the $_SESSION value got set - if it is from user input then it should be escaped.
As a side note, mysql_query is deprecated, you should look into mysqli and prepared statements.

How to count if value of a variable is repeated?

I am learning how to work with MySQL, and at the moment I succeed to show data from my table, using:
while($objResult2 = mysqli_fetch_assoc($objQuery_product)) {
Results are shown by using this variable $objResult2["id_product"]; this way i can take from DB any field I want like: $objResult2["name"]; $objResult2["email"]; etc.
But what i do if i have in the table more rows with the same id_product?
I want to write a if statment, which counts if id_product repeats. How to do that? If it is a lot of work, atleast please give me an idea of the right tutorial that I must read. Because i am trying second day to fix this, and searched google but i didnt find what i need, or maybe i coulndt understand it....
This is my query
$sql_product = "SELECT * FROM ps_product AS prod";
$join_product = " LEFT JOIN ps_product_lang AS lang ON lang.id_product = prod.id_product";
$join2_product = " LEFT JOIN ps_stock_available AS stok ON stok.id_product = prod.id_product";
$where_product =" WHERE prod.id_category_default = $idp AND lang.id_lang = 8";
$sql_product = $sql_product.$join_product.$join2_product.$where_product;
$objQuery_product = mysqli_query($objConnect, $sql_product) or die ("Error Query [".$sql_product."]");
You can simple remove the same id_product using DISTINCT keyword in your query. Such as:
SELECT DISTINCT id_product FROM my_table
This will give you results with different ids only.
The second way of doing it is taking the output values inside an array.
In your while loop:
$my_array[] = $objResult2["id_product"];
Then using array_filter remove all the duplicates inside the array.
YOu can also use array_count_values() if you want to count the duplicate values.
Ok here we go. For example you are fetching data with this query.
select id_product, name from PRODUCTS;
Suppose above query gives you 5 records.
id_product name
1 bat
2 hockey
2 hockey
3 shoes
4 gloves
Now you got 2,2 and hockey, hockey. Instead of thinking this way that you have to introduce an if statement to filter repeating records or same name or id_product records.
Rewrite your sql query like this.
select distinct id_product, name from PRODUCTS;
Or if you need count of each then my friend you will write your query something like this...
Graham Ritchie, if Andrei needs count of each repeating record then we will do something like this in our query.
SELECT PRODUCT_ID,
COUNT(PRODUCT_ID) AS Num_Of_Occurrences
FROM PRODUCTS
GROUP BY PRODUCT_ID
HAVING ( COUNT(PRODUCT_ID) > 1 );
SELECT id_product,COUNT(*) AS count
FROM tablename
GROUP BY id_product;
This query will then return you two items in your query
$objResult2["id_product"] //and
$objResult2["count"]
The if statement is then just
if($objResult2["count"] > 1){
//Do whatever you want to do with items with more than 1 occurence.
//for this example we will echo out all of the `product_id` that occur more than once.
echo $objResult2["id_product"] . " occurs more than once in the database<br/>";
}

How to get the current VM product_id to use in my query

I need to display the product information from the product table. I also have another table, manufacturer.
I have a query to display the product manufacturer by joining the two tables.
How to get the current id of the product in the WHERE expression? Please see my query below
$query = "SELECT vmm.mf_name,vmm.mf_desc"
. "FROM xxx_virtuemart_manufacturers_fr_fr AS vmm,
xxx_virtuemart_product_manufacturers as vmp"
. "WHERE vmm.virtuemart_manufacturer_id=vmp.virtuemart_manufacturer_id
AND vmp.virtuemart_product_id=1 LIMIT 0, 30";
From the above query the product_id is 1. But I want a dynamic variable for the virtuemart_product_id.
Is there any solution? Please help me
just bind it to a variable like
$result = mysql_fetch_assoc($query);
$id = $result['id'];
Although you should be using mysqli or PDO, hope this helps.
You can use a php array for that variable and loop the array running the query on each value.
If you know the possible all values, you can use vmp.virtuemart_product_id IN ('1', '2', '3', ...)
You can also do a sub query such as vmp.virtuemart_product_id = (SELECT value FROM ...)
I am sorry. I answered as much as I can from what I understood from your question.

Select * distinct one column

I have mysql table tmp with columns pid,city,state,country. I write queries so i can find matching city,state or country, and pid is field that helps me load another table.
The thing is, there is always two rows with same pid, and sometimes (when WHERE find matching city state or country in both), i display data from additional table twice unnecessarily.
So i need to select something like:
SELECT * FROM tmp DISTINCT pid WHERE city='test'
I have no idea how to search solution (i searched here on stackoverflow, but no luck).
Also, there will be a lot of searching in this table, so if there is multiple solutions i would prefer one that is faster.
Thanks
Please try the following SQL statement:
SELECT DISTINCT pid FROM tmp WHERE city='test'
try this
SELECT DISTINCT pid,field1,field2 FROM tmp WHERE city='test'
$keyword="0";
$query = "SELECT DISTINCT titel,id FROM xyz ORDER BY titel ASC ";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result))
{
if($keyword!==$row["titel"])
{
$keyword=$row["titel"];
echo $keyword;
}
}

Categories