How to Fix This SQL Loop (PHP)? - 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;
}

Related

Converting SQL Table ID into another field in PHP

So I'm trying to get the following to work;
//SEARCH USERPETS TABLE FOR ANYTHING USER OWNS
$query = "SELECT * FROM userpets WHERE owner = '$username'";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$userspets = $row['petid'];
//SEARCH PETS TABLE FOR LIST OF PET NAMES AND DETAILS
$query = "SELECT * FROM pets";
$result = mysqli_query($conn, $query);
$row = mysqli_fetch_assoc($result);
$petid = $row['id']
$petname = $row['petname'];
$petimg = $row['petimg']
//TURN PET ID INTO PET NAME AND IMAGE
echo "Pets: ".$userspets;
Essentially what I'm trying to do is this;
The 'userpets' table contains all 'owned' pets and the players username is displayed.
I want to grab all pets owned by that user and compare the petid with the 'pets' table.
I then want to take the pet's name and image from that table and 'echo' it onto the page.
Getting all the ids is fine, I just don't know how to make it convert the id's into the names.
Table Structure
You can use JOIN of MYSQL or Foreach of PHP
This is example by using PHP Foreach
$query = "SELECT * FROM userpets WHERE owner = '".$username."'";
$result = mysqli_query($conn, $query);
$petid = array(); // store all petid of this user
$rows = mysqli_fetch_all($result,MYSQLI_ASSOC);
foreach($rows as $row) {
$petid[] = $row['petid'];
}
$query = "SELECT * FROM pets WHERE id IN (".implode(",",$petid).")";
// implode will convert an array to string with delimete
// example array(0=>35, 1=>36, 2=>48) will be convert to "35,36,48"
// and above query should be : SELECT * FROM pets WHERE id IN (35,36,48)
$result = mysqli_query($conn, $query);
$pets = mysqli_fetch_assoc($result);
// dump it
echo "<pre>";
var_dump($pets);
echo "</pre>";
die;
Using MySQL Join
<?php
$query = "SELECT pet.id, pet.petname, pet.petimg, up.owner FROM pets as pet LEFT JOIN userpets as up ON pet.id = up.pet_id WHERE up.owner = '".$username."'";
I don't know how your tables look, but the best thing I can think of is, you have 3 tables one with Users, second with pets, and third "many to many" table lets call it ownedpets with users that own pets, because many users can own many pets. So ownedpets should have id_users that is connected to user.id and id_pets which is connected to pets_id. With that in mind I would do the fallowing query
SELECT *
FROM ownedpets
LEFT JOIN users
ON users.id = ownedpets.id_users
LEFT JOIN pets
ON pets.id = ownedpets.id_pets
WHERE users.id = $user_id
hope this helps

Getting each user in table and using them where module =

I have this table: tbl_module_bid
image:
you see users: Ali2,Ali,blackbone,dickface,mhmd
let's call for each one of them it's called $player and the sql query I wanna use in:
mysql_query("UPDATE `bbcsystem`.`tbl_admin` SET games_played = games_played + 1 WHERE username = $player");
I also don't want them to be duplicated
I tried using this script below:
//Update Game Played (not working very good):
$num_qry = "Select DISTINCT * From tbl_module_bid where user = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."' AND module = '$mod_id' order by bid asc";
$get_pick = $db->get_results($num_qry,ARRAY_A);
foreach($get_pick as $arr_pic)
{
$player = $arr_pic['user'];
mysql_query("UPDATE `bbcsystem`.`tbl_admin` SET games_played = games_played + 1 WHERE username = $player");
}

SELECT WHERE id IN X, X, Xonly one result

i have the following query:
$sql_select_todo =
"SELECT * FROM
to_do_items
WHERE
id_project = ".$_SESSION['selected_projectId']."'
AND
id IN ('".$alleTaken."')";
$query_select_todo = mysql_query($sql_select_todo) or die(mysql_error());
while($fetch_todo = mysql_fetch_assoc($query_select_todo)) {
echo $fetch_todo['name'];
}
When i echo the query, i get this:
SELECT * FROM to_do_items WHERE id_project = '7401' AND id IN ('10193,12848')
But the output will only give back one name ($fetch_todo['name'])
But there are 2 id's, so i should get 2 names. What do i do wrong here?
Remove single quote in IN query
Change
$sql_select_todo =
"SELECT * FROM
to_do_items
WHERE
id_project = ".$_SESSION['selected_projectId']."'
AND
id IN ('".$alleTaken."')";
To
$sql_select_todo =
"SELECT * FROM
to_do_items
WHERE
id_project = ".$_SESSION['selected_projectId']."'
AND
id IN (".$alleTaken.")";

Looping through a mysqli result

I'm trying to display a list of status updates from artists that a logged in user is following.
So far I have this:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
}
But i'm not sure how to loop through and display the returned status updates?
This isn't a strong point of mine, so any pointers would be greatly appreciated!
What prevented you from doing similar to what you'd already done for the first query? Something like follows:
#Get the list of artists that the user has liked
$q = "SELECT * FROM artist_likes WHERE user_id = '1' ";
$r = mysqli_query($dbc,$q);
while ($row = mysqli_fetch_array($r, MYSQLI_ASSOC)) {
#Now grab the statuses for each artist
$status_query = "SELECT * FROM status_updates WHERE artist_id = '".$row['artist_id']."' ";
$status_result = mysqli_query($dbc,$status_query)
while($status_result_row = mysqli_fetch_assoc($status_result)) {
echo $status_result_row['mycol']; // This is where you know better than us
}
}
Or if those two tables artist_likes and status_updates have artist_id in common then you could just use one query with a join. (But don't know if you are asking for that).
Just for avoiding multiple query, you can use one query like this:
SELECT l.*, s.*
from artist_likes l, status_updates s
WHERE
l.artist_id = s.artist_id and
l.user_id = '1'
or
SELECT l.*, s.*
from artist_likes l
JOIN status_updates s on (l.artist_id = s.artist_id)
WHERE
l.user_id = '1'

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.

Categories