Adding Formatted Numbers To A MySQL Select Array - php

I'm building a simple music website which has a set of albums on the selection page. On the left will be a group of album covers, and on the right will be the related album title and band name. Each album will be given a number, which will be referenced in the title/band name. Kind of like on a magazine contents page.
So my SELECT statement looks like:
$albums_sql = "SELECT albums.*, bands.name FROM albums LEFT JOIN bands ON albums.band = bands.id LIMIT $offset, $album_limit";
$albums_res = mysqli_query($con, $albums_sql);
while($album = mysqli_fetch_assoc($albums_res)){
$album_id = $album["id"];
$album_added = $album["added"];
$album_band = $album["name"];
$album_title = $album["title"];
....
And my displayed title looks like:
<div class=\"listWords\">$album_number ... <strong>$album_band: $album_title</strong></div>
Now this displays:
... The Band Name: The Album Name
But I obviously want it to display:
01 ... The Band Name: The Album Name
How do I get it to display a 2 digit numeral value for each row that is selected from the table using PHP?
Here's where I imagine I should create a number:
$albums_sql = "SELECT albums.*, bands.name FROM albums LEFT JOIN bands ON albums.band = bands.id LIMIT $offset, $album_limit";
$albums_res = mysqli_query($con, $albums_sql);
while($album = mysqli_fetch_assoc($albums_res)){
$album_id = $album["id"];
$album_added = $album["added"];
$album_band = $album["name"];
$album_title = $album["title"];
....
$album_number = ( Create a number based on how many are selected from the abover select statement )

Can be as simple as
$i=0;
while($album = mysqli_fetch_assoc($albums_res)){
$album_number = $i++;
$album_id = $album["id"];
$album_added = $album["added"];
$album_band = $album["name"];
$album_title = $album["title"];
...
and then if you want 0 padded numbers
echo sprintf("%02d",$album_number);

Just declare a variable as a counter outside of the while loop, and increment at each iteration.
$album_index = 0;
while($album = mysqli_fetch_assoc($albums_res)){
$album_number = $album_index++;
$album_id = $album["id"];
$album_added = $album["added"];
$album_band = $album["name"];
$album_title = $album["title"];

Related

PHP and MySQL: How to get all database entries form two tables?

I have the following code which gets data from a table entry and displays some html for each entry. It works fine but i want it to display html for the entries in that table AND another table. I could just duplicate this code and change it a bit to get the entries in a different table but that creates another problem, all the entries from the second table would start at the end of the entree list from the first table. How can I display the entries from both table in the order of most relevant to what the user types in? Here is my code that just displays entries from the first table in order of when they were inserted into the table. Can someone tell me how to display all the entries from two different tables in order of relavace to a user search query? My code so far, I have not been able to get much further than this.
$pagesQuery = mysql_query("SELECT count(id) FROM(`posts`) WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '%{$terms}%'");
$pageNum = ceil(mysql_result($pagesQuery, 0)/5);
$start = (($page-1)*5);
$currentname = mysql_query("SELECT * FROM `posts` WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '%{$terms}%' LIMIT $start, 5");
while ($row = mysql_fetch_array($currentname)) {
//recieve relevant data.
$title = $row[0];
$desc = $row[13];
$ID = $row[6];
$views = $row[3];
$user = $row[7];
$type = $row[15];
//fetch the last id from accounts table.
$fetchlast1 = mysql_query("SELECT * FROM allaccounts WHERE id=(SELECT MAX(id) FROM allaccounts)");
$lastrow1 = mysql_fetch_row($fetchlast1);
$lastid1 = $lastrow1[6];
//acquire the username of postee.
for ($i1=1; $i1 <= $lastid1; $i1++) {
$currentname1 = mysql_query("SELECT * FROM allaccounts WHERE id=$user");
while ($row1 = mysql_fetch_array($currentname1)) {
$username1 = $row1[0];
}
}
//Format Title, description and view count.
$title2 = rtrim($title);
$donetitle = str_replace(" ", "-", $title2);
$donetitle1 = str_replace(".", "", $donetitle);
$donetitle2 = str_replace("-", "-", $donetitle1);
$donetitle3 = str_replace(":", "-", $donetitle2);
$url = "articles/".$ID."/".$donetitle3."";
$donetitle = strlen($title) > 40 ? substr($title,0,40)."..." : $title;
$donedesc = '';
if(strlen($desc) > 150) {
$donedesc = explode( "\n", wordwrap( $desc, 150));
$donedesc1 = $donedesc[0] . '...';
} else {
$donedesc1 = $desc;
}
$SRCIMG = '';
$finviews = number_format($views, 0, '.', ',');
if($type == '1'){
$SRCIMG = "img/icons/video.png";
} else {
$SRCIMG = "img/icons/article.png";
}
//Give results
if($row[10] == null){
$SRC = "img/tempsmall.jpg";
}else{
$SRC ="generateThumbnailSmall.php?id=$ID";
}
echo "<div id = \"feature\">
<img src=\"$SRC\" alt = \"article thumbnail\" />
<img src=\"$SRCIMG\" alt = \"icon\" id=\"icondisp\"/>
</div>
<div id = \"feature2\">
$donetitle
<p id=\"resultuser\" >$username1</p>
<p id=\"resultp\">$donedesc1</p>
<img src=\"img/icons/flag.png\"/><b id=\"resultview\">$finviews views</b>
</div>
<div id = \"border\"></div>";
}
In this case you ought to use UNION to merge SELECT results from two or more tables.
So you query should look like this:
(SELECT *
FROM `posts`
WHERE `title` LIKE '%{$terms}%'
OR `descrip` LIKE '%{$terms}%')
UNION
(SELECT *
FROM `posts2`
WHERE `title` LIKE '%{$terms}%'
OR `descrip` LIKE '%{$terms}%')
LIMIT $start, 5
Notice that number and names of columns in both SELECTS should be the same.
Why not try union ?
SELECT * FROM `posts` WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '% {$terms}%'
union
SELECT * FROM `otherposts table` WHERE `title` LIKE '%{$terms}%' OR `descrip` LIKE '%{$terms}%'
order by yourRelevanceField
LIMIT $start, 5"
Actually it just hit me, I should probably create a new table called SearchElements where I store data needed for a search result. I would create a SearchElement each time an entree is added to either table. still dont understand relevance yet though.
Well you can go for UNION of two tables and try something like this
INSERT INTO table3
SELECT * FROM tabel1
UNION
SELECT * FROM tabel2

PHP MYSQL Nested While loop skips iterations

Need help to get through this Nested WHILE loop.
The Scenario is
These are the 5 tables in my db
user_info(userid,name,picurl)
user_friends(userid,friend_id)
user_post(userid,post_id,post,time)
user_likes(userid,post_id)
user_comments(userid,post_id)
I want to access user_post table and populate the data in my android application. i can access userid,post_id and time from user_post table and using friend_id of the user from friends table. Now to display a complete post with pic and name i need to access name and picurl of the person who's post it is from user_info table. If i need to display one 1 friends post i can do this simply but when there are couple of friends with more than 1 post i can't get the name and picurl of the user and it displays null in json response.
I'm using Nested While loop for this operation following is my code.
$userid = $_POST['userid'];
$query = "SELECT * FROM user_friend WHERE userid = '$userid'";
$result = mysql_query($query);
$return_arr = array();
$return_arr['newsfeed'] = array();
//Access userid
while($row = mysql_fetch_assoc($result)) {
echo "Friend Name is ".$row['friend_id']. "<br>";
$friend_id = $row['friend_id'];
$friend_id = mysql_real_escape_string($friend_id);
//accessing user_info table to access user info
$picquery = "SELECT * FROM user_info WHERE userid = '$friend_id'";
$picresult = mysql_query($picquery);
$pic = mysql_fetch_assoc($picresult);
$row_array['name'] = $pic['name'];
$row_array['picurl'] = $pic['picurl'];
$query2 = "SELECT * FROM user_post WHERE userid = '$friend_id'";
$result2 = mysql_query($query2);
//Access Posts Against userids
while( $row = mysql_fetch_array($result2) ) {
$post_id = $row['post_id'];
//for number of likes
$likesQuery = "SELECT COUNT(*) as totallikes FROM post_likes WHERE post_id = '$post_id'";
$likesResult = mysql_query($likesQuery);
$likesvalues = mysql_fetch_assoc($likesResult);
$num_of_likes = $likesvalues['totallikes'];
//for number of comments
$commentsQuery = "SELECT COUNT(*) as totalcomments FROM post_comments WHERE post_id = '$post_id'";
$commentsResult = mysql_query($commentsQuery);
$commentsvalues = mysql_fetch_assoc($commentsResult);
$num_of_comments = $commentsvalues['totalcomments'];
$row_array['post_id'] = $row['post_id'];
$row_array['userid'] = $row['userid'];
$row_array['post_text'] = $row['post_text'];
$row_array['post_time'] = $row['post_time'];
$row_array['post_num_likes'] = $num_of_likes;
$row_array['post_num_comments'] = $num_of_comments;
array_push($return_arr['newsfeed'],$row_array);
}
}
date_default_timezone_set('Asia/Karachi');
$date = date(' h:i:s a d/m/Y', time());
echo json_encode($return_arr,JSON_UNESCAPED_SLASHES);
something like this could help. As I don't have any test data I cannot see how it's working. It should display the post_id along with the count of the likes and the comments
SELECT
p.post_id,
COUNT(c.post_id) AS comments_count,
COUNT(l.post_id) AS like_count
FROM user_post p,
user_likes l,
user_comments c
WHERE p.post_id = l.post_id
AND p.post_id = c.post
GROUP BY p.post_id

Loop query with different value

I have a table schedules that contains sched_id, sc_id1, sc_id2, sc_id3, sc_id4, sc_id5, sc_id6, sc_id7, sc_id8, sc_id9, sc_id10, sched_name.
I have also table subject_current that has sc_id, sl_id, schoolyear, semister, etc... sc_id1 - scid10 is a "foreign key" from sc_id of table subject_current
Also, I have a table subject_list with sl_id, subject_code, subject_description, subject_prereq. sl_id from table subject_current is a "foreign key" from sl_id of table subject_list.
Now, what I want to do is to "echo" the subject_description from table subject_list only giving me the value of sc_id1 - sc_id10 from table schedules.
This code doesn't work:
for($jaa = 1;$jaa < 11;$jaa++){
$s_scid = "s_scid".$jaa;
$s_sublist = mysql_query("SELECT * FROM subject_current WHERE sc_id='$s_scid'");
while($rows_ss = mysql_fetch_assoc($s_sublist)){
$ss_slid = $rows_ss['sl_id'];
$ssl_sublist = mysql_query("SELECT * FROM subject_list WHERE sl_id='$ss_slid'");
while($rows_ssl = mysql_fetch_assoc($ssl_sublist)){
$ssl_slid = $rows_ssl['sl_id'];
$ssl_subdesc = $rows_ssl['subject_description'];
}
}
echo $ssl_subdesc;
}
EDIT
This is what I want to exactly happen:
$s_scid1 = $rows_s['sc_id1']; // which is a value of 1
$s_scid2 = $rows_s['sc_id2']; // which is a value of 2
$s_sublist = mysql_query("SELECT * FROM subject_current WHERE sc_id='$s_scid1'");
while($rows_ss = mysql_fetch_assoc($s_sublist)){
$ss_slid1 = $rows_ss['sl_id'];
$ssl_sublist = mysql_query("SELECT * FROM subject_list WHERE sl_id='$ss_slid1'");
while($rows_ssl = mysql_fetch_assoc($ssl_sublist)){
$ssl_slid1 = $rows_ssl['sl_id'];
$ssl_subdesc1 = $rows_ssl['subject_description'];
echo $ssl_subdesc1;
}
}
$s_sublist2 = mysql_query("SELECT * FROM subject_current WHERE sc_id='$s_scid2'");
while($rows_ss2 = mysql_fetch_assoc($s_sublist2)){
$ss_slid2 = $rows_ss2['sl_id'];
$ssl_sublist2 = mysql_query("SELECT * FROM subject_list WHERE sl_id='$ss_slid2'");
while($rows_ssl2 = mysql_fetch_assoc($ssl_sublist2)){
$ssl_slid2 = $rows_ssl2['sl_id'];
$ssl_subdesc2 = $rows_ssl2['subject_description'];
echo $ssl_subdesc2;
}
}
This is a pain to write it 10 times. So I want to loop it. But someone told me it's bad and told me about INNER JOIN. But how can I with INNER JOIN?
The way you describe it, you should do something like:
for($jaa = 1;$jaa < 11;$jaa++){
$s_scid = "s_scid".$jaa;
$the_query = "SELECT sl_id, subject_description FROM subject_list sl JOIN subject_current sc ON sl.sl_id=sc.$s_scid";
/* the above should generate a JOIN with a particular element from your master table */
$ssl_sublist = mysql_query($the_query);
while($rows_ssl = mysql_fetch_assoc($ssl_sublist)){
$ssl_slid = $rows_ssl['sl_id'];
$ssl_subdesc = $rows_ssl['subject_description'];
echo $ssl_subdesc;
}
}

Multiple objects per array row

I'm trying to create an API and I need to put multiple queries into my JSON ouput, the issue is everything is returned as an object of class stdClass... here is my code:
$querystr = "SELECT entry_id AS id FROM {$wpdb->prefix}connections_term_relationships WHERE term_taxonomy_id = '{$_GET['catID']}'";
$cID = $wpdb->get_results($querystr);
$dirCount=count($cID);
$arrayCategory= array();
$androidArray = array();
if($dirCount > 0){
foreach($cID as $company){
$querycInfo = "SELECT id, organization, contact_first_name, contact_last_name, bio FROM {$wpdb->prefix}connections WHERE id = '{$company->id}'";
$companyInfo = $wpdb->get_row($querycInfo);
$queryAddress = "SELECT line_1, line_2, line_3, state, zipcode FROM {$wpdb->prefix}connections_address WHERE entry_id = '{$company->id}'";
$address = $wpdb->get_row($queryAddress);
$queryEmail = "SELECT address FROM {$wpdb->prefix}connections_email WHERE entry_id = '{$company->id}' AND type = 'work'";
$email = $wpdb->get_row($queryEmail);
$queryWebsite = "SELECT title, url FROM {$wpdb->prefix}connections_link WHERE entry_id = '{$company->id}' AND type = 'website'";
$website = $wpdb->get_row($queryWebsite);
$queryPhone = "SELECT number FROM {$wpdb->prefix}connections_phone WHERE entry_id = '{$company->id}' AND type = 'workphone'";
$phone = $wpdb->get_row($queryPhone);
$arrayCategory[]= $companyInfo;
}
}else{
$arrayCategory[0]=array('organization'=>'No Company Found Within This Category');
}
$androidArray = array('companies'=>$arrayCategory);
echo json_encode($androidArray);
}
I need $arrayCategory to hold more then just $companyInfo, I need it to hold the other variables as well. This is being built for WordPress. Thanks in advance!
I ended up just formatting my SQL query in a matter that made more sense:
$querycInfo = "SELECT main.id, organization, contact_first_name, contact_last_name, bio, number FROM {$wpdb->prefix}connections main
JOIN {$wpdb->prefix}connections_phone phone ON phone.entry_id = main.id AND main.id = '{$company->id}'";
This solved the issue.

Selecting one image out of 5 images for one item

I have tried to create a script that loops through 5 items that match 1 item and then show one image associated with each of the 5 items.
Here is a fiddle I create to illustrate my issue.
http://sqlfiddle.com/#!2/17d66/1/0
I want to select one picture from each matching item. Here is the code I have come up with but so far it is not working. There are two points of comparison I have used, a tag and family. The tag associated with the type of product and the family is the category it belongs to. For instance, the iPhone 4 would have smartphone for a tag and iPhone 4 as the family. Any help would be appreciated, my code is below.
<?php
// main product
$images = "SELECT img_id FROM product_images WHERE img_tag = '$p_type' && img_family = '$p_family' LIMIT 5";
$img_list = mysql_query($images);
while($rows = mysql_fetch_array($img_list)) {
$img_name = $rows['img_name'];
$img_tag = $rows['img_tag'];
$img_family = $rows['img_family'];
$img_id = $rows['img_id'];
//echo $img_name;
<div>
<img src="view.php?h=400&w=400&imgid=<?php echo $img_id; ?>" />
</div>
}
</div>
</div>
<div id="left_other">
<div class="titleHeaders">Other matching items:</div>
<?php
$match_items = "SELECT id,product_name,product_type FROM product_list WHERE name_family = '$p_family' AND id <> '$id' LIMIT 5";
$match_q = mysql_query($match_items);
$count = mysql_num_rows($match_q);
if($count > 0) {
//get matching products
while($items = mysql_fetch_array($match_q)) {
$id = ($items['id']);
echo "<p>$id</p>";
$p_name = ($items['product_name']);
echo "<p>$p_name</p>";
$type = ($items['product_type']);
echo "<p>$type</p>";
$full = "$p_name $type";
echo "<p>$full</p>";
//get photos
$other_photos = "SELECT * FROM product_images WHERE img_family = '$p_family' AND img_tag <> '$p_type' LIMIT 1";
echo $other_photos;
$other_q = mysql_query($other_photos);
while($pictures = mysql_fetch_array($other_q)) {
echo "<p>----------------------</p>";
$theid = ($pictures['img_id']);
echo "<p>$theid</p>";
$photo = ($pictures['img_name']);
echo "<p>$photo</p>";
$thetype = ($pictures['img_tag']);
echo "<p>$thetype</p>";
echo "<p>----------------------</p>";
if($photo != $newname && $theid != $newid){
if ($photo == '') {
$poly = 'images/pph.jpg';
//echo $poly;
}else{
$poly = 'product_images/regular_images/'.$photo;
//echo $poly;
} // end if
$newname = $photo;
$newid = $theid;
}else{
echo "<p>The photo name is the same!</p>";
}
You can use a single query to grab the results. Here is how you can do it.
SELECT
pl.id,
pl.product_name,
pl.product_type ,
pi.product_images
FROM product_list AS pl
LEFT JOIN (SELECT product_list_id , product_images FROM product_images LIMIT 1) AS `pi` ON pi.product_list_id = pl.id
WHERE pl.img_tag = '$p_type' AND pl.img_family = '$p_family'
LIMIT 5
But it would be batter if there was some table structure , sample data and desired output.
EDIT
Try this query and you can put a where at last
SELECT
*
FROM
`products` AS p
LEFT JOIN (SELECT MAX(img_id), img_name, img_tag, img_family FROM `images`) AS i ON i.img_family = p.`p_family` AND i.img_tag = p.`p_tag` ;
EDIT
SELECT *
FROM `products` AS p
LEFT JOIN images as i
ON i.img_family = p.`p_family`
group by p.p_name;

Categories