Get data except for data in a column - php

So I have the following code:
require_once('db.php');
$getUsers = mysqli_query($db, 'SELECT * FROM users');
$rows = [];
while ($r = mysqli_fetch_assoc($getUsers)) {
$rows[] = $r;
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while($r = mysqli_fetch_assoc($getSkills)) {
$rows['skills'] = $r;
}
}
print(json_encode($rows));
Which outputs:
[{"id":"1","name":"user1","skills":{"woodcutting":"6","mining":"10"}},{"id":"2","name":user2"}]
There are two problems:
I'd like to get all of the data in the table skills EXCEPT for the id, or at-least cut it off before encoding it with json.
For some reason I can't get the "skills" shown after the first user. user2 should also have a skills object.
What am I doing wrong?

To get all the columns except the id from table skills, you can either list all the columns that you want to select, like this:
mysqli_query($db, "SELECT column1, column2, another_column FROM `skills` WHERE id = '" . $r['id'] . "'");
Or, you can SELECT everything and use unset() to weed out the id column before json-encoding:
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while ($r = mysqli_fetch_assoc($getSkills))
{
unset($r['id']);
// whatever it is that you want to do.
}
The skills are not shown except for the last user (?) because you are re-assigning it in every iteration of the while loop. Here is something you can do instead:
require_once('db.php');
$getUsers = mysqli_query($db, 'SELECT * FROM users');
$rows = array();
while ($r = mysqli_fetch_assoc($getUsers))
{
$skills = array();
$tempRow = $r;
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '" . $r['id'] . "'");
while ($r = mysqli_fetch_assoc($getSkills))
{
unset($r['id']); // since you don't want the `id`.
$skills[] = $r;
}
$tempRow['skills'] = $skills;
$rows[] = $tempRow;
}
print(json_encode($rows));
Hope that helps :)

It looks like you need something similar to this:
while($r = mysqli_fetch_assoc($getSkills)) {
unset($r['id']);
$rows['skills'] = $r;
}

Point-1: Unset id like unset($r['id']) to remove from array() $r. Before unsset id keep id to a variable because you used it for next query.
Point-2: May be there is no data exist in skills those IDs. As a result you did not get skills. Suggest you to query by those IDs whether any data exist or not in skills table.
while ($r = mysqli_fetch_assoc($getUsers)) {
$id = $r['id'];
unset($r['id']);
$rows[] = $r;
$getSkills = mysqli_query($db, "SELECT * FROM skills WHERE id = '$id'");
while($r = mysqli_fetch_assoc($getSkills)) {
$rows['skills'] = $r;
}
}

Related

Return all rows from an array

I'm trying to return a comma separated list of location names from a database.
So far I have the SQL statement that I know works because it returns the correct results when tested in phpMyAdmin.
I'm now trying to get the results returned and printed on screen in php.
The code I have bellow only seems to return the first result.
$sql = "SELECT user_locations.location_id, location.name AS LocName FROM user_locations INNER JOIN location ON user_locations.location_id=location.id WHERE user_id = '" . $id . "'";
$query = mysqli_query($conn, $sql);
while ($row = $query->fetch_assoc()) {
$array[] = $row['LocName'];
$comma_separated = implode(",", $array);
return $comma_separated;
}
You need to remove the implode and return outside your while loop, otherwise your loop will stop after the first value:
$sql = "SELECT user_locations.location_id, location.name AS LocName
FROM user_locations
INNER JOIN location ON user_locations.location_id=location.id
WHERE user_id = '" . $id . "'";
$query = mysqli_query($conn, $sql);
while ($row = $query->fetch_assoc()) {
$array[] = $row['LocName'];
}
$comma_separated = implode(",", $array);
return $comma_separated;
Note that you can achieve this result directly in your query using GROUP_CONCAT:
$sql = "SELECT GROUP_CONCAT(location.name) AS LocName
FROM user_locations
INNER JOIN location ON user_locations.location_id=location.id
WHERE user_id = '" . $id . "'";
$query = mysqli_query($conn, $sql);
$row = $query->fetch_assoc();
$comma_separated = $row['LocName'];
return $comma_separated;
Note that dependent on the source of your $id value, you may need to look into prepared statements to protect yourself from SQL injection.

Unable to get key value from a mysql multi-dimensional array

I am trying to get the key value from the multidimensinal array which I have created using .The Array snapshot is given after the Code.
Below is my PHP code-
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link,$selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if($numOfTicket > 0){
$allRowData = array();
while($row = mysqli_fetch_assoc($rsTicket)){
$allRowData[] = $row;
}
$key = 'array(1)[ticketID]';
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', array_keys($key)).")";
Array Snapshot-
I need the tickedID value from this array . Like the first one is 49 .
Please help.
change your code like
$selectTicket = "select ticketID from ticketusermapping where userID=$userID and distanceofticket <=$miles;";
$rsTicket = mysqli_query($link, $selectTicket);
$numOfTicket = mysqli_num_rows($rsTicket);
if ($numOfTicket > 0) {
$allRowData = array();
while ($row = mysqli_fetch_assoc($rsTicket)) {
$allRowData[] = $row['ticketID'];
}
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (" . implode(',', $allRowData) . ")";
$ids = array_column( $allRowData, 'ticketID'); //this will take all ids as new array
$QueryStr = "SELECT * FROM ticket WHERE ticketID IN (".implode(',', $ids).")";
You should do a single query using JOIN for this:
$query = "
SELECT t.*
FROM ticket t
JOIN ticketusermapping tum
ON t.ticketID = tum.ticketID
AND tum.userID = '$userID'
AND tum.distanceofticket <= '$miles'
";
$stmt = mysqli_query($link, $query);
$numOfTickets = mysqli_num_rows($stmt);
while($row = mysqli_fetch_assoc($stmt)){
var_dump($row); // here will be the ticket data
}

Setting dynamic array key in while loop php

I have this code
$query = "SELECT `subscriberid`,`data` FROM `****table_name*****`"
. "WHERE `subscriberid` IN (123,456,789,101)";
$result = $cxn->query($query);
$Points = array();
while ($row = $result->fetch_assoc()) {
$Points[$row['subscriberid']] = $row['data'];
}
I want the keys for $Points to be the subscriberid, but when I print out $Points I keep getting default keys 0-3 and I can't see any reason for this to be happening.
Credits to #Jongosi's Comment, about the if ($result = $cxn->query($query)) part.
Your query is currently as follows:
$query = "SELECT `subscriberid`,`data` FROM `****table_name*****`"
. "WHERE `subscriberid` IN (123,456,789,101)";
If you only edited ****table_name*****, you are missing a space ( between * and WHERE).
Your result will be nothing or an error.
$query = "SELECT `subscriberid`,`data` FROM `****table_name*****`"
. " WHERE `subscriberid` IN (123,456,789,101)";

Creating an array of IDs from a while loop

Im trying to generate an array but not sure how to go about it.
I'm currently getting my data like so:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test#test.com'");
$row = mysql_fetch_array($query);
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT * FROM usersettings WHERE userId = ".$row['userId']." AND usersettingCategory".$row1['categoryId']." LIKE 'y'");
$isyes = mysql_num_rows($query2);
if($isyes > 0){
$cat1 = mysql_query("SELECT * FROM shops WHERE shopstateId = 1 AND (categoryId1 = ".$row1['categoryId']." OR categoryId2 = ".$row1['categoryId']." OR categoryId3 = ".$row1['categoryId'].")");
$cat1match = mysql_num_rows($cat1);
if($cat1match > 0){
while($cat1shop = mysql_fetch_array($cat1)){
$cat1msg = mysql_query("SELECT * FROM messages WHERE shopId = ".$cat1shop['shopId']." and messagestateId = 1");
while($cat1msgrow = mysql_fetch_array($cat1msg)){
echo $cat1msgrow['messageContent']." - ".$cat1msgrow['messageCode'];
$cat1img = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$cat1shop['shopimageId']);
$imgpath = mysql_fetch_array($cat1img);
echo " - ".$imgpath['shopimagePath']."<br/>";
}
}
}
}
}
But this can cause duplicates when a user has all 3 of a shops categories picked in their preferences. I am trying to find a way to just pull the message ID out instead of the whole thing and put it into an array giving me, for example:
1,3,5,7,1,3,5,2,4,7,8
Then I can just run a separate query to say get me all messages where the ID is in the array, but i am unsure of the most constructive way to build such an array and examples of array from a while loop I have seen do not seem to be what I am looking for.
Is there anyone out there that can push me in the right direction?
Can't help with this code. But if you want an array from a query without duplicate result, you can use " select DISTINCT (id) " in your query or for more simple solution :
$id_arr = array();
$sql = mysql_query("select id from id_table");
while ($id_result = mysql_fetch_array($sql) {
$id = $id_result['id'];
if (!in_array($id, $id_arr)) {
$id_arr[] = $id;
}
}
I have found a much easier way to create the required result. I think at 6am after a hard night coding my brain was fried and I was making things a lot more complicated than I needed to. A simple solution to my issue is as follows:
$query = mysql_query("SELECT * FROM users WHERE userEmail LIKE 'test2#test2.com'");
$row = mysql_fetch_array($query);
$categories = "(";
$query1 = mysql_query("SELECT * FROM categories");
while($row1 = mysql_fetch_array($query1)){
$query2 = mysql_query("SELECT usersettingCategory".$row1['categoryId']." FROM usersettings WHERE userId = ".$row['userId']);
$row2 = mysql_fetch_array($query2);
if($row2['usersettingCategory'.$row1['categoryId']] == y){
$categories .= $row1['categoryId'].",";
}
}
$categories = substr_replace($categories ,")",-1);
echo $categories."<br />";
$query3 = mysql_query("SELECT * FROM shops,messages WHERE shops.shopId = messages.shopId AND messages.messagestateId = 1 AND (shops.categoryId1 IN $categories OR shops.categoryId2 IN $categories OR shops.categoryId3 IN $categories)");
while($row3 = mysql_fetch_array($query3)){
$query4 = mysql_query("SELECT shopimagePath FROM shopimages WHERE shopimageId = ".$row3['shopimageId']);
$row4 = mysql_fetch_array($query4);
echo $row3['messageContent']." - ".$row3['messageCode']." - ".$row4['shopimagePath']."<br />";
}

problem of while loop and array

$result=array();
$table_first = 'recipe';
$query = "SELECT * FROM $table_first";
$resouter = mysql_query($query, $conn);
while ($recipe = mysql_fetch_assoc($resouter, MYSQL_ASSOC)){
$result['recipe']=$recipe;
$query2="SELECT ingredients.ingredient_id,ingredients.ingredient_name,ingredients.ammount FROM ingredients where rec_id = ".$recipe['rec_id'];
$result2 = mysql_query($query2, $conn);
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'] = $ingredient;
}
echo json_encode($result);
}
this code show me all the recipes but only the last ingredients i.e
{"recipe":{"rec_id":"14","name":"Spaghetti with Crab and Arugula","overview":"http:\/\/www","category":"","time":"2010-11-11 14:35:11","image":"localhost\/pics\/SpaghettiWithCrabAndArugula.jpg"},"ingredient":{"ingredient_id":"55","ingredient_name":"test","ammount":"2 kg"}}{"recipe":{"rec_id":"15","name":"stew recipe ","overview":"http:\/\/www","category":"","time":"2010-11-11 14:42:09","image":"localhost\/pics\/stew2.jpg"},"ingredient":{"ingredient_id":"25","ingredient_name":"3 parsnips cut into cubes","ammount":"11"}}
i want to output all the ingredient records relevant to recipe id 14 and this just print the last ingredient.
$result['ingredient'] = $ingredient;
Is replacing the variable $result['ingredient'] with the most recent $ingredient value each time, culminating with the last value returned, you should use:
$result['ingredient'][] = $ingredient;
To incrememnt/create a new value within the $result['ingredient'] array for each $ingredient. You can then output this array according to your needs. Using print_r($result['ingredient']) will show you its content...to see for yourself try:
while($ingredient = mysql_fetch_assoc($result2)){
$result['ingredient'][] = $ingredient;
}
print_r($result['ingredient']);
If I understand correctly what you want to do, there is a way to optimize the code a lot, by fetching recipes and ingredients in one single query using a JOIN :
$recipes = array();
$recipe_ingredients = array();
$query = "SELECT * FROM recipe LEFT JOIN ingredients ON ingredients.rec_id=recipe.rec_id ORDER BY recipe.rec_id DESC";
$resouter = mysql_query($query, $conn);
$buffer_rec_id = 0;
$buffer_rec_name = "";
$buffer_rec_cat = "";
while( $recipe = mysql_fetch_array($resouter) )
{
if( $buffer_rec_id != $result['recipe.rec_id'] )
{
$recipes[] = array( $buffer_rec_id, $buffer_rec_name, $buffer_rec_cat, $recipe_ingredients);
$recipe_ingredients = array( );
$buffer_rec_id = $result['recipe.rec_id'];
$buffer_rec_name = $result['recipe.rec_name'];
$buffer_rec_cat = $result['recipe.rec_category'];
}
else
{
$recipe_ingredients[] = array( $result['ingredient_id'], $result['ingredient_name'], $result['ammount'] );
}
}
$print_r($recipes);
This code should give you a multi-dimensional array that you can use later to get the data you want.
I let you adapt the code to have exactly the information you need.

Categories