$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.
Related
Im trying to merge or put an Array (called '$rows_ban') inside a sub item of another array (called '$rows') in a final array named '$rows_final'.
Im using array_merge but returns null inside 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[null]}
It should return the results in of the second query inside the 'data':
{"date":"2018-05-03","hour":"09:12:32","data":[{...},{...},{...}]}
PHP Script:
$rows = array();
$rows_ban = array();
$rows_final= array();
$result1 = mysqli_query($link,"SELECT `id`,`sync_date`,`sync_time` FROM sync_log");
while($r = mysqli_fetch_array($result1)) {
$rows['date']= $r[2];
$rows['hour']= $r[3];
$rows['data'][]= null;
}
$result2 = mysqli_query($link,"SELECT cod, name, total from totals " );
while($r = mysqli_fetch_array($result2)) {
$rows_ban['cod'] = $r[0];
$rows_ban['name'] = $r[1];
$rows_ban['total'] = $r[2];
$result3 = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod=".$r[0]." order by dates desc");
while($r = mysqli_fetch_assoc($result3)) {
$rows_ban['sub_data'][] = $r;
}
$rows_final = array_merge($rows['data'],$rows_ban);
// here im trying to merge the $rows_ban array inside the
$rows['data']
}
echo json_encode($rows_final);
Not sure if that's what you wanted to accomplish since your description is very poor and hard to understand.
$output = [];
$tmpRows = [];
$result = mysqli_query($link, 'SELECT `id`,`sync_date`,`sync_time` FROM sync_log');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$output['date'] = $tmp[0]['sync_date'];
$output['time'] = $tmp[0]['sync_time'];
}
$result = mysqli_query($link, 'SELECT cod, name, total from totals ');
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['cod'] = $tmp[0]['cod'];
$tmpRows['name'] = $tmp[0]['name'];
$tmpRows['total'] = $tmp[0]['total'];
$result = mysqli_query($link,"SELECT *, 1 as Filter from
table3 where cod={$tmp[0]['cod']} order by dates desc");
if ($tmp = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$tmpRows['sub_data'] = $tmp[0];
}
$output['data'] = $tmpRows;
}
print_r(json_encode($output));
Also array_merge doesn't work like you think it does. It returns merged array like it's name states. Regarding to your code, final result would be exactly $rows_ban encoded to json.
http://php.net/manual/en/function.array-merge.php
I'm having trouble with a mysqli_query from inside a foreach loop, I'm getting a string from a table first, then separating that into an array. Then I try looping through the array and calling a query inside the loop.
$langs_result = mysqli_query($con, "SELECT Languages FROM users WHERE Username = '$username'");
$row = mysqli_fetch_assoc($langs_result);
$langs = $row['Languages'];
$userLangs = str_replace(" ","",$langs);
$userLangs = explode(",",$langs);
print_r($userLangs);
$posts = array();
foreach($userLangs as $lang){
echo "$lang <br>";
$sql = "SELECT * FROM posts WHERE Language = '$lang'";
$getLangPosts = mysqli_query($con, $sql);
array_push($posts, mysqli_fetch_assoc($getLangPosts));
}
print_r($posts);
for this user the langusges are German, Italian, Danish, and English, but the $posts array only contains the first post found from the first language (German), can anybody help? I am trying to get all of the posts for each language in the $userLangs array.
It's going through the foreach loop okay as the $lang variable that's echoed changes each time but the query still isn't working properly.
Thanks for the help!
select posts.* from posts
left join users on users.language=posts.language
where users.username='your_desiredusername'
group by users.language;
Just try to run this as a single query by filling the username
no need of multiple queries
You an avoid multiple queries by doing a JOIN, using FIND_IN_SET to match on your comma separated list. You probably need to use REPLACE to get rid of the extra spaces in the comma separated list as well.
Then you can just loop around to display the data, displaying the language on change of language:-
<?php
$sql = "SELECT a.Languages AS user_languages,
b.*
FROM users a
LEFT OUTER JOIN posts b
ON FIND_IN_SET(b.Language, REPLACE(a.Languages, ' ', ''))
WHERE a.Username = '$username'
ORDER BY b.Languages";
$langs_result = mysqli_query($con, $sql);
if($row = mysqli_fetch_assoc($langs_result))
{
print_r(explode(', ', $row['user_languages']));
$prev_langauge = '';
while($row = mysqli_fetch_assoc($langs_result))
{
if ($prev_langauge != $row['Languages'])
{
if ($prev_langauge != '')
{
print_r($posts);
}
$posts = array();
echo $row['Languages']."<br>";
$prev_langauge = $row['Languages'];
}
array_push($posts, mysqli_fetch_assoc($row));
}
if ($prev_langauge != '')
{
print_r($posts);
}
}
UPDATE
See this code:
<?php
$langs_result = mysqli_query($con, "SELECT Languages FROM users WHERE Username = '$username'");
$row = mysqli_fetch_assoc($langs_result);
$langs = $row['Languages'];
// $langs = 'German, Italian, Danish, French'; added this to run the test
// $userLangs = str_replace(" ","",$langs); this is not needed, see the explode below
$userLangs = explode(", ",$langs);
foreach($userLangs as $lang){
echo $lang;
$sql = "SELECT * FROM posts WHERE Language = '$lang'";
$getLangPosts = mysqli_query($con, $sql); // this is the result of the select *
while($post = mysqli_fetch_assoc($getLangPosts)){ // iterate over all the results
$postField = $post["yourChoiceField..say..Title"]; // get something from each row
array_push($posts, $title); // push into array
}
}
print_r($posts);
Since the initial select is based on username I don't believe the first loop is needed so your code was on the right track.
A second loop was needed to iterate over the posts though and a field to populate the $posts array.
You need to perform mysqli_fetch_assoc in a loop
$langs_result = mysqli_query($con, "SELECT Languages FROM users WHERE Username = '$username'");
while($row = mysqli_fetch_assoc($langs_result)){
$langs = $row['Languages'];
$userLangs = str_replace(" ","",$langs); // i don't get why you are doing this though
$userLangs = explode(",",$langs);
print_r($userLangs);
$posts = array();
foreach($userLangs as $lang){
echo "$lang <br>";
$sql = "SELECT * FROM posts WHERE Language = '$lang'";
$getLangPosts = mysqli_query($con, $sql);
array_push($posts, mysqli_fetch_assoc($getLangPosts));
}
print_r($posts);
}
It would help to know how what the select query actually returns.
mysqli_fetch_assoc only fetches one row on each call you need to use it like this:
while ($row_new = mysqli_fetch_assoc($getLangPosts)){
array_push($posts, $row_new);
}
You need to loop the inner query to get the column data
foreach($userLangs as $lang){
echo "$lang <br>";
$sql = "SELECT * FROM posts WHERE Language = '$lang'";
$getLangPosts = mysqli_query($con, $sql);
while($row1 = mysqli_fetch_assoc($getLangPosts))
array_push($posts, $row1['YOUR_COLUMN_NAME']);
}
OR you should use IN clause instead of loop
$langs_result = mysqli_query($con, "SELECT Languages FROM users WHERE Username = '$username'");
while($row = mysqli_fetch_assoc($langs_result)){
$langs = $row['Languages'];
$userLangs = str_replace(" ","",$langs);
$userLangs = explode(",",$langs);
print_r($userLangs);
$posts = array();
$sql = "SELECT * FROM posts WHERE Language IN ('".implode(',',$userLangs)."')";
$getLangPosts = mysqli_query($con, $sql);
while($row1 = mysqli_fetch_assoc($getLangPosts))
array_push($posts, $row1['YOUR_COLUMN_NAME']);
}
Hi I am trying to use in_array, I think my syntax is correct,
but it says "Wrong datatype for second argument"
My code is
$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
while($row = mysqli_fetch_array($result))
{
if (in_array($row['ProductID'], $filter))
{
}
}
My idea is to find out if the ProductID from Products Table is in the Order Table.
Could someone helps me, Thanks :-)
$filter isn't an array; it's a mysqli_result object:
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
I think you want to iterate over that, add each ProductID to a new array, and then pass that array to the in_array function like so:
$filter = mysqli_query($con, "SELECT ProductID FROM Orders");
$product_ids = array();
while ($row = $filter->fetch_assoc())
{
$product_ids[] = $row['ProductID'];
}
$result = mysqli_query($con, "SELECT * FROM Products WHERE Quantity_On_Hand < Min_Stock");
while($row = mysqli_fetch_array($result))
{
if (in_array($row['ProductID'], $product_ids))
{
}
}
Your code is failing because $filter is a MySQLi result resource, not an array. Really, this is better accomplished with a simple inner join between the two tables. If a ProductID does not exist in Orders, the INNER JOIN will exclude it from the result set in the first place.
$sql = "
SELECT Products.*
FROM
Products
INNER JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
If instead you want to retrieve all the Products, and simply have an indication of whether it has an active order, use a LEFT JOIN and test if Orders.ProductID is null in the SELECT list:
$sql = "
SELECT
Products.* ,
/* No orders will print 'no-orders' in a pseudo column called has_orders */
CASE WHEN Orders.ProductID IS NULL THEN 'no-orders' ELSE 'has-orders' AS has_orders
FROM
Products
LEFT JOIN Orders ON Products.ProductID = Orders.ProductID
WHERE Quantity_on_Hand < Min_stock";
$result = mysqli_query($con, $sql);
if ($result) {
$results = array();
while ($row = mysqli_fetch_array($result)) {
$results[] = $row;
}
}
// Now $results is a 2D array of all your Products
// And the column $row['has_orders'] will tell you if it has any...
In this case, you may test in a loop over your rowset whether it has orders:
foreach ($results as $r) {
if ($r['has_orders'] == 'has-orders') {
// this has orders
}
else {
// it doesn't...
}
}
In the below code i want to join or implode all arrays of $trackersurl in a single line. i am getting the results in different lines, so i want to join in a single line.
Can anyone help me out?
I am searching results in stackoverflow, but could not follow.
My code is in below:
$sql = "SELECT * FROM announce WHERE torrent = $id ORDER BY seeders DESC";
$query = #mysql_query($sql);
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['url'];
$trackersurl2 = "&tr=".$trackersurl1;
$trackersurl = array($trackersurl2);
}
Results of [var.trackersurl] in html page is below:
&tr=http:ajgdsjhg/ann
&tr=udp://iuysidfu/ann
&tr=udp:wutefghgw/ann
&tr=http://sdhgsjdhgj/ann
I want to join them in a single line below
&tr=http:ajgdsjhg/ann&tr=udp://iuysidfu/ann&tr=udp:wutefghgw/ann&tr=http://sdhgsjdhgj/ann
You should be careful of sql injection.
Are you looking to create an array['trackers'] with a string of all the trackers for a magnet link?
<?php
$sql = "SELECT * FROM announce WHERE torrent = ".mysql_real_escape_string($id)." ORDER BY seeders DESC";
$query = mysql_query($sql);
$tracker = null;
if(mysql_num_rows($query)>=1){
while ($result = mysql_fetch_array($query)) {
$tracker .= "&tr=".$result['url'];
}
}
$tracker = array('trackers'=>$tracker);
//$tracker['trackers'] = "&tr=a.com&tr=b.com&tr=c.com";
?>
Try this code
$newArray=array();
while ($result = #mysql_fetch_array($query)) {
$trackersurl1 = $result['title'];
$newArray[] = "&tr=".$trackersurl1;
}
$urlString=implode('',$newArray);
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 />";
}