Multiple objects per array row - php

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.

Related

Adding Formatted Numbers To A MySQL Select Array

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"];

How to Fix This SQL Loop (PHP)?

I have designed a loop but it's not working as I'd like it to, and I'm assuming there are better ways to do this, but I'm quite confused.
Basically, there are two tables.
BlogSubscribers and Users
The BlogSubscribers simply holds the User ID's for subscribers (correlating to the Users) table, and I am trying to fetch the "Gender" value of each user that is a subscriber, but that information is stored in the Users table.
The loop only goes through once (which is why I tried to loop it with integers) - how can I make this work + more efficient?
It'd be great if you could explain any answers you post so I know how the code works in future.
$ID is just a GET paramater through the url, i.e ?Blog=$ID
$GetSubInfo = mysqli_query($db, "SELECT * FROM BlogSubscribers WHERE BlogID = '$ID'");
$GetSubInfoCount = mysqli_num_rows($GetSubInfo);
$LoopCount = 0;
while($LoopCount < $GetSubInfoCount){
$GetSubs = mysqli_fetch_object($GetSubInfo);
$GetFemaleSubs = mysqli_num_rows(mysqli_query($db, "SELECT * FROM Users WHERE ID = '$GetSubs->UserID' AND Gender = 'Female'"));
$GetMaleSubs = mysqli_num_rows(mysqli_query($db, "SELECT * FROM Users WHERE ID = '$GetSubs->UserID' AND Gender = 'Male'"));
$GetOtherSubs = mysqli_num_rows(mysqli_query($db, "SELECT * FROM Users WHERE ID = '$GetSubs->UserID' AND Gender = 'Other'"));
$GetUnknownSubs = mysqli_num_rows(mysqli_query($db, "SELECT * FROM Users WHERE ID = '$GetSubs->UserID' AND Gender = 'Unknown'"));
$LoopCount = $LoopCount + 1;
}

Display value instead of ID mysqli

When I add $elan_category, I get category_id, instead category_title.
Tried to apply "left join" but no success. I have following tables in database:
function getElanDetail()
{
global $con;
if (isset($_GET['elan_id'])) {
$elan_id = $_GET['elan_id'];
$get_elan = "select * from elan where elan_id='$elan_id'";
$run_elan = mysqli_query($con, $get_elan);
while ($row_elan = mysqli_fetch_array($run_elan)) {
$elan_id = $row_elan['elan_id'];
$elan_category = $row_elan['elan_category'];
$elan_title = $row_elan['elan_title'];
$elan_description = $row_elan['elan_description'];
$elan_image = $row_elan['elan_image'];
$elan_contact = $row_elan['elan_contact'];
echo "
$elan_category //Getting ID of category instead Title :(
$elan_title
$elan_description
$elan_image
$elan_contact
";
}
}
}
With join you can do something like:
$elan_id = $_GET['elan_id'];
$get_elan = "SELECT * FROM `elan`
JOIN `categories` ON `categories`.category_id = `elan`.elan_category
WHERE `elan`.elan_id='$elan_id'";
$run_elan = mysqli_query($con, $get_elan);
while ($row_elan=mysqli_fetch_array($run_elan)){
print_r($row_elan);
// see the keys in $row_elan and use them accordingly
}
For subcategories try this query:
SELECT * FROM `elan`
JOIN `categories` ON `categories`.category_id = `elan`.elan_category
JOIN `subcategories` ON `subcategories`.subcategory_id = `elan`.elan_subcategory
WHERE `elan`.elan_id='$elan_id'
$elan_category = $row_elan['elan_category'];
add these two lines after above code
$cat = mysqli_fetch_row(mysqli_query($con,"SELECT category_title FROM categories WHERE category_id = $elan_category"));
$cat_name = $cat[0];
$cat_name is your category name enjoy

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

Query error not getting numbers

Here is my query, I am trying to get numbers from another table using a number from another table here is my query ...
$order_id = $template_vars['{order_name}'];
// Query to find the product id for the current order and then set it to a variable
$query="SELECT product_id FROM ps_order_detail WHERE id_order = $order_id";
$result = mysql_query($query);
$row = mysql_fetch_row($result);
$Product_id = $row['0'];
// get all the custom part numbers and set them to the variables
$customnumbers ="SELECT API, SWAIM, JOHN_CRANE, SNOW_WELL, MIDAS, QUINN, WILSON, WEATHERFORD, HF, BLACK_GOLD, EDI, SO_CAL_PUMPS, WEST_RIVER
FROM ps_product_part_number WHERE Product_ID = $Product_id";
$secondresult = mysql_query($customnumbers);
$secondrow = mysql_fetch_row($secondresult);
$API = $secondrow['0'];
$SWAIM = $secondrow['1'];
$JOHN_CRANE = $secondrow['2'];
$SNOW_WELL = $secondrow['3'];
$MIDAS = $secondrow['4'];
$QUINN = $secondrow['5'];
$WILSON = $secondrow['6'];
$WEATHERFORD = $secondrow['7'];
$HF = $secondrow['8'];
$BLACK_GOLD = $secondrow['9'];
$EDI = $secondrow['10'];
$SO_CAL_PUMPS = $secondrow['11'];
$WEST_RIVER = $secondrow['12'];
How about doing it in one step with a join?
SELECT ppn.*
FROM ps_product_part_number ppn
join ps_order_detail od on od.product_id = ppn.Product_ID
WHERE od.id_order = $order_id

Categories