PHP: MYSQL select inside another MYSQL select? - php

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.

Related

PHP Output data from 3 different tables

I'm trying to display a HTML table with information from 3 different tables in my mysql DB. However I am unsure on how to display the information from the third table.
Currently what I am using is:
$SQL = "SELECT members.*, exp.*, lvl.*
FROM members
INNER JOIN exp ON members.id = exp.member_id
INNER JOIN lvl ON members.id = lvl.member_id
ORDER BY lvl.level DESC,
lvl.total DESC, xp.total DESC";
$result = mysql_query($SQL) or die(mysql_error());
$count = 1;
while ($row = mysql_fetch_assoc($result)) {
$level = $row['level'];
$exp = $row['exp.overall'];
}
the $level is from the second table which grabs correctly, and the $exp is what I want to grab from the third table which is "exp" but it doesn't return anything
How can I change this because at the moment it just seems to be focusing on the data from the "lvl" table when using $row[]
Edit: Both the lvl and exp tables have a row in called 'overall' which is why using $row['overall'] doesn't return what I want as it returns the data from lvl table rather than exp.
First off I believe you have a typo in your last order column: should be exp.total DESC.
Secondly, unless you specify the columns to be named with dot notation explicitly they will retain their column names so try changing the last line to:
$exp = $row['overall'];.
Also consider using mysqli or PDO.

WHERE clause doesn't seem to work in PHP

The query SELECT * FROM TABLE WHERE id LIKE '%1% is not working properly, it's not select the id 1.
mysql_connect('localhost', 'root' , '');
mysql_select_db('database');
$sql = ("select * from search WHERE id LIKE '%3%'");
mysql_query($sql);
$my_variable = mysql_query($sql);
$display_data = mysql_fetch_row($my_variable);
while ($list = mysql_fetch_assoc($my_variable)) {
$id = $list['id'];
$title = $list['title'];
$keywords = $list['keywords'];
$img = $list['img'];
$link = $list['link'];
}
If you are looking to SELECT id 1 then use = not LIKE. The way LIKE is being used it will match every id that has a 1 in it and you are not guaranteed to get the first one in order, so instead use:
SELECT * FROM search WHERE id = 1
According to the PHP documentation of mysql_fetch_row it
Returns a numerical array that corresponds to the fetched row and moves the internal data pointer ahead.
Which means that the first result won't show up in the next (mysql_fetch_assoc) procedure. You could try removing the $display_data = mysql_fetch_row($my_variable); line and only use the while($list = mysql_fetch_assoc($my_variable)) { ... } procedure. See if that solves your problem.
$sql = ("select * from search WHERE id ='3'");
The id is an integer use = instead of like . Equal is more accurate.
And first echo your query in your program->
echo $sql;die;
copy that query and run it on your phpmyadmin
and then check is your column id is int type if it is then like will not give you the result. You have to use the where clause here .But if you have the column id is of type varchar then definitely give you the result .
Try to use search tab under your database->table in your phpmyadmin and put the condition there.
You will definitely get your answer there.

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.

Mysql Select Multiple Table Get Value with same Column

Okay that was harsh,
Anyways, I revised my question and made an example of code here.
What I wanted to do is, I need to get the giveaway table's column title value and competition column title value
$query = "SELECT giveaway_table.title, competition.title FROM giveaway_table, competition WHERE giveaway_table.status=competition.status";
$result = db_query($query)->fetchObject();
How do I retrieve the value?
When I used this
echo $result->title;
it only echo the competition's title value.
How do I retrieve the giveaway table's title column value?
I used this
$result->title[0]
it only shows the First letter of the Title of Competition's title value.
Any help would be appreciated. :)
Use different alias:
$query = "SELECT giveaway_table.title as gtitle, competition.title as ctitle FROM giveaway_table, competition WHERE giveaway_table.status=competition.status";
You could use aliases to clear up the ambiguity:
$query = "SELECT giveaway_table.title AS giveaway_title, competition.title AS competition_title FROM giveaway_table, competition WHERE giveaway_table.status=competition.status";
$result = db_query($query)->fetchObject();
Then echo:
echo $result->competition_title;
echo $result->giveaway_title;
Use aliases
SELECT
giveaway_table.title AS GiveAwayTitle,
competition.title AS CompetitionTitle
FROM giveaway_table,
competition
WHERE giveaway_table.status = competition.status
With php
echo $result->GiveAwayTitle;
echo $result->CompetitionTitle;

How to query all fields in a row

I know this is very simple, but I haven't used PHP/MySQL in a while and I have been reading other threads/php website and can't seem to get it.
How can I query a single row from a MySQL Table and print out all of the fields that have data in them? I need to exclude the NULL fields, and only add those that have data to an html list.
To clarify, I would like to display the field data without specifying the field names, just for the reason that I have a lot of fields and will not know which ones will be NULL or not.
What you've outlined requires 4 basic steps:
Connect to the database.
Query for a specific row.
Remove the null values from the result.
Create the html.
Step 1 is quite environment specific, so that we can safely skip here.
Step 2 - SQL
SELECT * from <tablename> WHERE <condition isolating single row>
Step 3 - PHP (assuming that $query represents the executed db query)
//convert the result to an array
$result_array = mysql_fetch_array($query);
//remove null values from the result array
$result_array = array_filter($result_array, 'strlen');
Step 4 - PHP
foreach ($result_array as $key => $value)
{
echo $value \n;
}
Just SELECT * FROM table_name WHERE.... will do the trick.
To grab data from specific fields, it would be SELECT field_1,field_2,field_3....
you have to make a string which represent mysql query. Then there is function in php named mysql_query(). Call this function with above string as parameter. It will return you all results. Here are some examples
You need to do it like this...
First connect to your sql... Reference
Now make a query and assign it to a variable...
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename");
If you want to retrieve a single row use LIMIT 1
$query = mysqli_query($connect, "SELECT column_name1, column_name2 FROM tablename LIMIT 1");
If you want to fetch all the columns just use * instead of column names and if you want to leave some rows where specific column data is blank you can do it like this
$query = mysqli_query($connect, "SELECT * FROM tablename WHERE column_name4 !=''");
Now fetch the array out of it and loop through the array like this..
while($show_rows = mysqli_fetch_array($query)) {
echo $show_rows['column_name1'];
echo $show_rows['column_name2'];
}
If you don't want to include the column names in the while loop, you could do this:
while($show_rows = mysqli_fetch_array($query)) {
foreach( $show_rows as $key => $val )
{
echo $show_rows[$key];
}
}

Categories