How can I store this data in arrays - php

I have 3 tables users alerts and articles a user can setup an alert so when a new article is added that match his profile he will get an email
I am trying to write a small code to do this task
and this is what I came up with so far
$query_users = "SELECT * FROM `users`";
$result_users = $conn->query($query_users);
while ($users = mysqli_fetch_row($result_users)) {
$user_id = $users[0];
$user_email = $users[1];
$query_alerts = "SELECT * FROM `alerts` where user_id='$user_id' and active= '1' ";
$result_alerts = $conn->query($query_alerts);
while ($alerts = mysqli_fetch_row($result_alerts)) {
$category = mysqli_real_escape_string($conn,$alerts[2]);
$keyword = mysqli_real_escape_string($conn,$alerts[3]);
$query_search = "SELECT * FROM `articles` WHERE `category_id` = '$category' `title` LIKE '%$keyword%' ORDER BY `articles`.`id` ASC ";
$result_search = $conn->query($query_search);
$count = $result_search->num_rows;
}
}
Now what I want to do is to store the result this way
Put each alert category + keyword + count in an array then put it in an array that contain the user id and email
So at the bottom I can loop through the users and send to the user with id 1 and email example#website.com
a table like this
Category | Keyword | articles count
Health | Diet | 5
Buisness | Banks | 2
I hope you understood my idea, I am very confused and dizzy I didn't even know what to type in the search box

Take one array outside of while and add 3 variable in array when loop is executed.
i added 2 lines in your code which are.
$response = array();
and
$response[] = array
(
'category' => $category,
'keyword' => $keyword,
'count' => $count
);
Complete example
<?php
$query_users = "SELECT * FROM `users`";
$result_users = $conn->query($query_users);
$response = array();
while ($users = mysqli_fetch_row($result_users))
{
$user_id = $users[0];
$user_email = $users[1];
$query_alerts = "SELECT * FROM `alerts` where user_id='$user_id' and active= '1' ";
$result_alerts = $conn->query($query_alerts);
while ($alerts = mysqli_fetch_row($result_alerts))
{
$category = mysqli_real_escape_string($conn,$alerts[2]);
$keyword = mysqli_real_escape_string($conn,$alerts[3]);
$query_search = "SELECT * FROM `articles` WHERE `category_id` = '$category' `title` LIKE '%$keyword%' ORDER BY `articles`.`id` ASC ";
$result_search = $conn->query($query_search);
$count = $result_search->num_rows;
$response[] = array
(
'category' => $category,
'keyword' => $keyword,
'count' => $count
);
}
}
echo "<pre>";
print_r($response);

Related

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

Add to array in comma separated values from database

my database table is named order. it has a row like order. I store values like this 1,2,3,4,5. Now i would like to add to array and from it out info..
I tried to do that but it is not working...
here is my code:
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
if want check print_r($array) Output
Array ( [0] => 1,23,4,5 )
this one is not working.. i think its supposed to be like this: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )
FASTEST APPROACH
You need to use explode() function. Here is an example of it :
<?php
$array = array('0' =>'1,2,3,4,5');
$array = explode(',', $array[0]);
var_dump($array);
?>
Here is your updated code, to get array in that format.
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
$array = array($sql_order);
$array = explode(',', $array[0]);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}
Note this is solution which you are looking for. But it isn't recommended due to reason told to you as comment.
PROPER WAY TO HANDLE THIS
You should ideally normalize your Database so this kind of problem don't come even in future to you.
Here is a proposed table structure change, which you can consider, depending on your need & time.
Remove order column from your table. Add a new table named order_suborders as follows:
| COLUMN | TYPE |
|:-----------|------------:|
|parent_order| int |
| order_id | int |
You can change name of columns and table according to your wish.
Move old data accordingly.
Use query SELECT order_suborders.order_id FROM order, order_suborders WHERE order.id = ".$_GET['id']." AND order.id = order_suborders.parent_order
you can use explod to split with ","
$sql = mysql_query("SELECT * FROM `order` WHERE `id` = ".$_GET['id']." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
//$array = array($sql_order);
$array=explod(",",$sql_order);
foreach($array as $x) {
$sql = mysql_query("SELECT * FROM `product` WHERE `id` = ".$x." LIMIT 1");
$row = mysql_fetch_assoc($sql);
$sql_order = $row['order'];
echo $row['product_name'].'<br />';
}

mysql_query returning wrong result

Consider the following code
if ( isset( $_SESSION['FBID'] ) ) {
$uid = $_SESSION['FBID'];
$sql = "SELECT *, count(member_nr) AS notifyMe
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
while($row=mysql_fetch_array($result)){
$notification = $row['notifyMe'];
}//while
if ( $notification > 0 ) {
echo '<span class="badge">' . $notification . '</span>';
} //if
var_dump($notification);
} //isset( $_SESSION['FBID'] )
The above script returns how many notifications a member has as you can see in image below
My Problem
The script is returning the wrong result (wrong number of notifications). Have a look at the table below, the member number appears 3 times in the table so:
$notification = $row['notifyMe'] Should = 3 AND NOT 1
What am I missing or doing wrong here? Thanks for reading
Use
$sql = "SELECT *, count(*) AS notifyMe
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
Notice count(*) , it will fetch how many records are matching criteria.
And initialize $notification = 0; at the start.
Have you tried approaching it from this angle
$sql = "SELECT * FROM poolWinners WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
$notification = array();
while($row=mysql_fetch_array($result)){
$notification[] = $row['notifyMe'];
}
//an array count on notification should give you the number of elements in the array i.e those that matched the query
$total_count = count($notification);
In your code the notification will be always one, since it will take only the notifyMe field of last row in the result set.
If you want to get number of notifications, try this
if ( isset( $_SESSION['FBID'] ) ) {
$uid = $_SESSION['FBID'];
$sql = "SELECT *, count(member_nr) AS notifyMe
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
$notification = 0;
while($row=mysql_fetch_array($result)){
$notification++;
/*
OR $notification += $row['notifyMe'];
*/
}//while
if ( $notification > 0 ) {
echo '<span class="badge">' . $notification . '</span>';
} //if
var_dump($notification);
} //isset( $_SESSION['FBID'] )
$sql = "SELECT *
FROM poolWinners
WHERE member_nr = '$uid' AND notification ='1'";
$result = mysql_query($sql);
$notification = mysql_num_rows($result);
$sql = "SELECT * FROM poolWinners WHERE member_nr = '$uid' AND notification ='1'";
if ($result=mysqli_query($con,$sql))
{
// Return the number of rows in result set
echo "Toal notification".mysqli_num_rows($result);
}
mysqli_close($con);
?>

How to shuffle posts in two tables?

I was working on a post system..
So, I have to show posts by friends of the user and the groups in which user has participated..
Here is my code to show posts..
<?php
$sql = "SELECT * FROM posts WHERE uploader_id=:friend_id ORDER BY id DESC";
$query = $db->prepare($sql);
$query->execute(array(
":friend_id" => $friend_id
));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$name = $row['name'];
echo "POST BY $name";
}
$sql = "SELECT * FROM group_posts WHERE id=:member_group ORDER BY id DESC";
$query = $db->prepare($sql);
$query->execute(array(
":member_group" => $group_id
));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$name = $row['name'];
echo "POST BY $name";
}
?>
Now, I want all these posts to be shuffled in a way that all the posts of the post table and group_posts table are shown in the descending order.
UPDATE
I edited my code to this..
I figured out that first I'll have to code this before coding my post system..
<?php
$sql = "SELECT * FROM friends WHERE user_one=:me OR user_two=:me2 UNION SELECT * FROM group_members WHERE member_id=:me3";
$query = $db->prepare($sql);
$query->execute(array(
":me" => $my_id,
":me2" => $my_id,
":me3" => $my_id
));
$rows = $query->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
$user_one = $row['user_one'];
$user_two = $row['user_two'];
$group_id = $row['group_id'];
if ($user_one == $my_id) {
$friend_id = $user_two;
} else {
$friend_id = $user_one;
}
echo $friend_id . "<BR>" . $group_id;
}
?>
Now, here's the problem..
This is successfully printing the $friend_id but, it shows an undefined index 'group_id' while printing $group_id.
I have checked all the fields are correct.
Try using just one query with UNION
SELECT *
FROM (
SELECT name, id FROM posts WHERE uploader_id=:friend_id
UNION
SELECT name, id FROM group_posts WHERE id=:member_group
) p
ORDER BY p.id DESC
Note, your inner queries must return the same number of columns in the same order (and I think with the same name/alias, too).

I want to put a while loop into an array

I have a multidimensional array where under "images" I want to loop 4 rows from my database. It means I am trying to put a loop into an array. Help me.
$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());
$albums = array();
while ($row_album = mysql_fetch_assoc($res_album)) {
$albums[$row_album['title']] = array(
"description" => $row_album['description'],
"date" => $row_album['date'],
"images" => array(
//i want to insert a loop here shown down
)
);
}
This is the loop i want to insert where i wrote the comment in the upper script:
$sql_thumb = "SELECT * FROM photos WHERE album_id = '".$row_album['id']."' LIMIT 0, 4";
$res_thumb = mysql_query($sql_thumb) or die(mysql_error());
while ($row_thumb = mysql_fetch_assoc($res_thumb)) {
echo $row_thumb['thumb_url'];
}
Start here...
include('../path/to/mysqli/connection/statements');
$query = "
SELECT a.id
, a.title
, a.description
, a.date
, p.thumb_url
FROM albums a
LEFT
JOIN photos p
ON p.album_id = a.id
ORDER
BY a.id;
";
$result = mysqli_fetch_assoc($db,$query);
Sadly PHP does not allow this kind of usage. You could however do something like this
$sql_album = "SELECT * FROM albums";
$res_album = mysql_query($sql_album) or die(mysql_error());
$albums = array();
while ($row_album = mysql_fetch_assoc($res_album)) {
$albums[$row_album['title']] = array(
"description" => $row_album['description'],
"date" => $row_album['date'],
"images" => array()
);
$sql_thumb = "SELECT * FROM photos WHERE album_id = '".$row_album['id']."' LIMIT 0, 4";
$res_thumb = mysql_query($sql_thumb) or die(mysql_error());
while ($row_thumb = mysql_fetch_assoc($res_thumb)) {
$albums[$row_album['title']]["images"][] = row_thumb['thumb_url'];
}
}

Categories