displaying data from inner join - php

i need help displaying this in two different lists
$domains_sql = mysql_query("SELECT domains_id, domains_url, keywords_id, keywords_word, domains_comments_comment
FROM
(
SELECT domains_id,domains_url
FROM domains
ORDER BY RAND()
LIMIT 1
) as d
INNER JOIN domains_comments
ON domains_comments_domain = domains_id
INNER JOIN domains_keywords
ON domains_keywords_website = domains_id
INNER JOIN keywords
ON domains_keywords_keyword = keywords_id
ORDER BY keywords_word ASC") or die (mysql_error());
$num = mysql_num_rows($domains_sql);
$current_price = "";
for($i=0;$i<$num;$i++){
$domains_result = mysql_fetch_array($domains_sql);
$domains_id = $domains_result['domains_id'];
$domains_url = $domains_result['domains_url'];
$domains_name = preg_replace('#^https?://www.#', '', $domains_url);
$keywords_id = $domains_result['keywords_id'];
$keywords_word = $domains_result['keywords_word'];
$domains_comments = $domains_result['domains_comments_comment'];
if($domains_url != $current_price) {
echo $domains_name."<br /><br />";
$current_price = $domains_url;
}
echo $keywords_word."<br />";
echo $domains_comments."<br />";
}
prints out:
MS Office
domain 1
MS Office
domain 1 - part 1
MySQL
domain 1
MySQL
domain 1 - part 1
PHP
domain 1
PHP
domain 1 - part 1
Visual Basic
domain 1
Visual Basic
domain 1 - part
and i need it to be:
(info from keywords)
MS Office
MySQL
PHP
Visual Basic
(info from comments)
domain 1
domain 1 - part 1

I'm not sure if I see how your domain comments and keywords are related, and if you simply want two lists or if you want one comment-list per keyword.
Anyway, you could rewrite your query logic to make a primary query for the keywords, and then run simpler queries for the comments (either one for all, or one per keyword), but if your query time and dataset is such that you prefer doing it in a single query you can restructure the data in multiple-leve arrays.
Also, i presume you only want to list every item once.
$keywords = array();
$comments = array(); //if you want all comments in one list
for($i=0;$i<$num;$i++){
$domains_result = mysql_fetch_array($domains_sql);
//Stores complete row data, only keeps the last, if the same value is fetched from the db several times
$keywords [$domains_result['keywords_word']] = $domains_result;
$comments[$domains_result['domains_comments_comment']] = $domains_result;
}
//Now you have the two list, could be printed several ways, to only print the values
print implode("<br />\n",array_keys($keywords));
print "<br />";
print implode("<br />\n",array_keys($comments));
//Loop trough
foreach ($keywords as $keyword=>$data) {
print "$keyword<br>\n";
print $data['keywords_word']."<br>\n";
print_r($data);
}

Related

Saving data from database into associative array with counting up - PHP

I would like to sort data from my database. I want to use associative arrays so it can be sorted the best.
I get all the data from a database, as said above. By doing $row['manufacturer'] I'll get some data like the following:
motorola
sony
motorola
google
samsung
lg
samsung
I would like it to be saved like this in the array: (order is not important, although alphabetically is preferred)
"motorola" => 2
"sony" => 1
"google" => 1
"samsung" => 2
"lg" => 1
I tried it by doing this, but it just didn't work and caused my web host to clean the logs, as it caused almost 2 gigs of log files.
The code I wrote to save it
$manufacturers = array();
//$row are the rows from my database. I will not add them, but by doing $row['manufacturer'] you'll get some brands like google, motorola, etc.
while($row = $resultSelect->fetch_assoc()) {
for ($i = 0; $i < $manufacturers; $i++) {
$alreadyEntered = 0;
if ($manufacturers[$i] == $row['manufacturer']) $alreadyEntered = 1;
if ($alreadyEntered == 0) {
$manufacturers[$row['manufacturer']] = 1;
} else {
$manufacturers[$row['manufacturer']] += 1;
}
//It caused huge logs, so I decided to break on 50.
if ($i > 50) {
break;
}
}
}
//Dump it :) to see if it worked
var_dump($manufacturers);
I have no idea how I can make it work. I tried searching on Google and SO for setting values in associative arrays, but nothing worked.
EDIT:
My rows:
You could do it through SQL query.
Using the count and group by query.
SELECT name, COUNT(*) as total
FROM manufactures
GROUP BY name
ORDER BY name ASC
name is your manufactures name column. manufactures is your table name.
Example PHP code:
$sql="SELECT name, COUNT(*) as total
FROM manufactures
GROUP BY name
ORDER BY name ASC";
$result=mysqli_query($con,$sql);
while($row = mysqli_fetch_assoc($result))
{
echo "Name: ". $row['name'] . " Total: ". $row['total'] . "<br>";
}
Brief explanation:
What the query will do is that it will select all manufactures name, and count them. By in the same time, it will group together the names, which means, multiple same name will be grouped together, and counted together. Finally order by name asc is used to sort the result alphabetically in ascending order (A->Z).

MySQL SELECT WHERE id IN() get num_rows

I use this code to show category from database
$select_newscats = $mysqli->query("SELECT * FROM news_cats order by ord_show asc");
while ($rows_newscats = $select_newscats->fetch_array(MYSQL_ASSOC)){
$id_newscats = $rows_newscats ['id'];
$title_newscats = $rows_newscats ['title'];
$ord_show_newscats = $rows_newscats ['ord_show'];
$icon_newscats = $rows_newscats ['icon'];
$kind_newscats = $rows_newscats ['kind'];
$description_newscats = $rows_newscats ['description'];
//here is my data
}
i have in news table row for categoies it's name is cats and i insert data inside it like that 1,5,6,8
and i use this code to count news inside each cat
$select_newsnum = $mysqli->query("SELECT id FROM news where $id_newscats IN (cats)");
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
$num_newsnum = $select_newsnum->num_rows;
it gets only first value for example if i have this values 1,5,6,8 it gets only 1 the first value
I would do the counting in a single sql call, not with php logic and separate sql calls. For this I would join the 2 tables using left join and use a join condition instead of an in clause:
SELECT nc.id, nc.title, nc.ord_show, nc.icon, nc.king, nc.description, count(n.id) as newsnum
FROM news_cats nc
LEFT JOIN news n ON nc.id=n.cats
GROUP BY nc.id, nc.title, nc.ord_show, nc.icon, nc.king, nc.description
ORDER BY nc.ord_show asc
Obviously, make sure that the join condition is the right one. When you loop through the resultset, the number of news per category will be in the newsnum field.
$select_newsnum = $mysqli->query("SELECT id FROM news where $id_newscats IN (cats)");
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
$num_newsnum = $select_newsnum->num_rows;
Here $rows_newsnum will only return the first row in the database.
Fetch Array only returns one row at a time, and then moves the row pointer forward. For example the following code on the dataset you provided (1, 5, 6, 8).
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
echo $rows_newsnum["id"]; // Will print 1
$rows_newsnum = $select_newsnum->fetch_array(MYSQL_ASSOC);
echo $rows_newsnum["id"]; // Will print 5
What you need to do is move it into a while loop (like your first example) to get to access each row, like below:
while($row = $select_newsnum->fetch_array(MYSQL_ASSOC)) {
echo $rows_newsnum["id"] . ", ";
}
// Will produce:
// 1, 5, 6, 8,
If you just want to get a count
Your existing code should work fine. And you can omit the call to fetch_array.
$num_newsnum = $select_newsnum->num_rows;
echo $num_newsnum; // Will display 4
Read more about fetch_array on the PHP documentation:
http://php.net/manual/en/mysqli-result.fetch-array.php
Hope this helps.

Foreach looping too many times

I'm using this to display information from a queried db in Wordpress. It displays the correct information but it loops it too many times. It is set to display from a SELECT query and depending on the last entry to the db seems to be whether or not it prints double or triple each entry.
foreach ($result as $row) {
echo '<h5><i>'.$row->company.'</i> can perform your window installation for <i>$'.$row->cost.'</i><br>';
echo 'This price includes using<i> '.$row->material.'</i> as your material(s)<br>';
echo '<hr></h5>';
}
Does anyone know what could be producing this error?
Thanks
The query powering that script is:
$result = $wpdb->get_results( "SELECT bp.*, b.company
FROM `windows_brands_products` bp
LEFT JOIN `windows_brands` b
ON bp.brand_id = b.id
JOIN Windows_last_submissions ls
JOIN windows_materials wm
JOIN Windows_submissions ws
WHERE ws.username = '$current_user->user_login'
AND bp.width = ROUND(ls.width)
AND bp.height = ROUND(ls.height)
AND bp.material IN (wm.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");
I can't seem to see the duplicate but I agree it must be there.
EDIT-- when I replace the WHERE clause to WHERE ws.username = 'password' , it still repeats. It it displaying a result for each time a result has username='password' , and displaying that set twice as well.
I think you want the following, if you're using MySQLi:
while ($row = $result->fetch_object()) {
echo '<h5><i>'.$row->company.'</i> can perform your window installation for <i>$'.$row->cost.'</i><br>';
echo 'This price includes using<i> '.$row->material.'</i> as your material(s)<br>';
echo '<hr></h5>';
}
Redundant JOIN clauses in my query which was pretty much pulling the same results from two tables (one of which was just a VIEW of the other).

Organize array in PHP from mysql

Hi i have a social networking website.
what i want it to do is pull out my friends status updates.
basically what it does is i have a mysql query that pulls out all of my friends and in that while loop there is another mysql query that pulls out the status's from my friends.
i want it to be in order of date but since its one while loop in another what it does is pull out all status's from friend 1 then 2 then 3 and not in order by date. i even tried ORDER BY DATE but that just ordered it by date within the friend..
my thought is that i could putt it all in an array and friends is one thing and the values is the stats. then just sort by values would this work and how could i do it.
the friend and stats are in two differants tables
THANKS SO MUCH
CODE:
$friendssql = mysql_query("SELECT * FROM friends WHERE sender='$id'");
while($row = mysql_fetch_object($friendssql)) {
$friendid = $row-> accepter;
$frsql = mysql_query("SELECT * FROM myMembers WHERE id='$friendid'");
while($rowa = mysql_fetch_object($frsql)) {
$ufirstname = $rowa-> firstname;
$ulastname = $rowa-> lastname;
}
$blabsql = mysql_query("SELECT * FROM blabbing WHERE mem_id='$friendid' ORDER BY blab_date DESC");
while($rowb = mysql_fetch_object($blabsql)) {
$blab = $rowb-> the_blab;
$blabd =$rowb-> blab_date;
$ucheck_pic = "members/$friendid/image01.jpg";
$udefault_pic = "members/0/image01.jpg";
if (file_exists($ucheck_pic)) {
$blabber_pic = "<img src=\"$ucheck_pic\" width=\"50px\" border=\"0\" />"; // forces picture to be 100px wide and no more
} else {
$blabber_pic = "<img src=\"$udefault_pic\" width=\"40px\" border=\"0\" />"; // forces default picture to be 100px wide and no more
}
Once you've put your data into the array, you could take a look at some of the various array sorting functions in PHP: http://php.net/manual/en/array.sorting.php
why not do it all in one query? this is psuedo sql, so you'll have to modify with your real tables and relationships.
select f.name,s.statustext
from friends f
inner join status s
on s.friend_id = f.id
inner join myfriends mf
on mf.friend_id = f.id
where mf.myid = 'myid'
order by f.name, s.datestamp
or something similar.

MySQL: printing data just once for each grouping

I'm coding in PHP/MySQL and have the following query to fetch products and product group data:
SELECT products.id,products.name,product_groups.id,product_groups.name
FROM products
INNER JOIN product_groups
ON products.id=product_groups.id
WHERE products.name LIKE '%foobar%'
ORDER by product_groups.id ASC
So this query fetches products and orders them by product group. What I would like to have is to display product_groups.name just once for each product grouping. So even if I have ten shoe products, the group name "Shoes" is only displayed once.
I'm using the following PHP to print out the results:
while ($data = mysql_fetch_array($result))
If you want it done in the MySQL query, it is honestly more trouble than it's worth. For one, the syntax is really wonky (as I recall) to have a group name listed at the top of each grouping. And the results are still treated as rows, so the group name will be treated like a row with all the other columns as Null, so you won't really save any time or effort in the PHP script as it has to do an if statement to catch when it hits a group name instead of the group data.
If you want it done by the PHP while loop, Johan is on the right track. I use the following for a similar situation:
$result = $sql->query($query);
$prev_group = "";
while($data = $result->fetch_assoc()){
$curr_group = $data['group'];
if ($curr_group !== $prev_group) {
echo "<h1>$curr_group</h1>";
$prev_group = $curr_group;
}
else {
echo $data;
.....
}
Obviously the echo data would be set up to echo the parts of the data the way you want. But the $prev_group/$curr_group is set up so that the only time they won't match is when you are on a new group and thus want to print a header of some sort.
while($data = mysql_fetch_assoc($result)){
if($data['product_groups.name'] != $groupname){
echo "Groupname: ".$data['product_groups.name']."<br />";
$groupname = $data['product_groups.name'];
}
echo "ID: ".$data['products.id']."<br />";
echo "Name: ".$data['products.name']."<br />";
}
Maybe you can do like this!?

Categories