I'm building a php notification system (kinda like facebook's).
It works as should, listing all events the way i want it. but i'm trying to get it to understand that if it gets 3+ events on the same post, it will join these events into one notification.
Now it looks like this:
User 1 wrote on article-x
User 2 wrote on article-x
user 3 wrote on article-x
user 1 wrote on article-y
instead i want it to be printed like this :
user 1 and 2 others wrote on article-x
Been trying to read up on what i need to do this, but no luck. any pointers greatly appreciated.
It's being queried like this:
edited with full code
$sesname = $_SESSION['user_name'];
$sesid = $_SESSION['full_name'];
$dbh = new PDO("mysql:host=$hostname;dbname=$db", $username, $password);
$stmt = $dbh->prepare("select * from comments WHERE full_name = '$sesid' and checked ='1' ");
$stmt->bindParam(':full_name', $safe_name, PDO::PARAM_INT, 5);
$stmt->execute();
$result = $stmt -> fetchAll();
foreach( $result as $row ) {
$name = $row['name'];
$pid = $row['pid'];
$commentid = $row['id'];
$fullink = $row['fullink'];
$datetime = $row['dt'];
if ($name == $sesname){
} else {
echo "<div id='commentnote'><a href='http://{$fullink}'>{$name}</a>kommenterte ditt <a href='{$fullink}'>blogginnlegg</a><br><div class='updentry' style='color: red ! important; cursor: pointer; margin-top: -35px; position: absolute; right: 8px;'>x</div></div>";
}
}
Tried using your answers underneath, but without luck. Thanks for answering though, i really appreciate it :)
What about turning the article into a multidimensional array? (Just an example, structure isn't optimal since I don't know what data you have and need.)
if(count($post['comments']) >= 3) {
echo $post['user'][0] ."and". (count($post['comments'])-1). " others wrote on ..";
} else {
//Just one
}
Maybe you could create a 2-dimensional array like this:
Array
(
[article-x] => Array
(
[0] => User1
[1] => User2
)
[article-y] => Array
(
[0] => User1
)
)
If you want to do this in PHP, do something like this:
$events = array();
foreach( $result as $row ) {
if( isset($events[$row['article']) ){
$events[$row['article']]['counter']++;
}else{
$row['counter'] = 0;
$events[$row['article']] = $row;
}
}
foreach( $events as $event ){
echo "<div id='commentnote'>{$event['user']}".($event['counter']?' and '.$event['counter'].' others':'')." wrote on {$event['article']}</div>";
}
Related
I have a MYSQL table with a list of services that user's provide:
The Enum values in these columns can be 0 or 1.
0 represents a service not offered and 1 represents a service offered.
Cleaning Tour Guide Cooking Parties
0 1 0 1
I am then running the following query In MYSQL to fetch my rows in the table:
<?php $myBio = $conn->query("SELECT * FROM user_data, user_services WHERE user_data.user_id = user_services.user_id AND user_id = $p_id");
if ($myBio->num_rows > 0) {
$row = $myBio->fetch_assoc();?>
I want to generate a list of the services the user provides (where the service has a value greater than 0) - and separate the list with commas like so:
Tour Guide, Parties
I am trying to do this by using an array:
$os = array(if($row['cleaning'] > 0) { echo 'cleaning';}, if($row['tour'] >0) { echo 'Tour Guide'; });
I am trying to use PHP if statements to decipher if a service is 0 or 1 before adding it to my list.
I do not believe it is possible to combine php if statements within an array.
Please can someone show me how I can achieve my desired result? Thanks in advance
Use array_keys() with the optional search parameter:
$services = array_keys($row, 1);
Example:
$row = [
'Cleaning' => 0,
'Tour Guide' => 1,
'Cooking' => 0,
'Parties' => 1,
];
$services = array_keys($row, 1);
var_export($services);
Result:
array (
0 => 'Tour Guide',
1 => 'Parties',
)
Demo
If your database columns have a speaking name, you can do it like this:
<?php
$arrayServices = array();
$arrayAllServices = array('Cleaning','Tour Guide','Cooking','Parties');
foreach($arrayAllServices as $service) {
if($row[$service] > 0) {
$arrayServices[] = $service;
}
}
$sServices = join(', ', $arrayServices);
echo $sServices;
If the speaking names are different from the column names, you need a second array to look up translations.
Would something like this achieve what you want?
$results=array();
if ($row['cleaning']>0) $results[]='Cleaning';
if ($row['tour']>0) $results[]='Tour Guide';
// ...
Also, please heed #tadman's comment about prepared statements!
<?php
$myResults = array();
$myBio = $conn->query("SELECT * FROM user_data, user_services WHERE user_data.user_id = ? AND user_id = ?");
$stmt->bind_param("ss",$user_services.user_id,$p_id);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows === 0) exit('No rows');
while($row = $result->fetch_assoc())
{
$tempArray = array();
$Cleaning = $row['Cleaning'];
$Tour_Guide = $row['TourGuide'];
$Cooking = $row['Cooking'];
$Parties = $row['Parties'];
if($Cleaning == 1)
array_push($tempArray,$Cleaning)
if($Cleaning == 1)
array_push($tempArray,$Cleaning)
if($Cooking == 1)
array_push($tempArray,$Cooking )
if($Parties == 1)
array_push($tempArray,$Parties )
array_push($myResults,$tempArray);
}
?>
You will then get the myResult array which will be an array of arrays, you can then loop over the sub arrays to check values and construct the strings you intend to make.
Using my php page i m reading mysql data and showing in json. Code of php page is --
<?php
function loadData($limit){
require "config.inc.php";
$query = $con->prepare("SELECT * FROM UploadText ORDER BY slno DESC LIMIT $limit ");
$query->execute();
$array = array();
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$id = $data['slno'];
$title = $data['textmsg'];
array_push($array, array(
"id" => $id,
"title" => $title
)
);
}
echo json_encode($array);
}
function loadMoreData($lastId, $limit){
require "config.inc.php";
try{
$query = $con->prepare("SELECT * FROM UploadText WHERE slno < $lastId ORDER BY slno DESC LIMIT $limit ");
$query->execute();
$array = array();
while($data = $query->fetch(PDO::FETCH_ASSOC)){
$id = $data['slno'];
$title = $data['textmsg'];
array_push($array, array(
"id" => $id,
"title" => $title
)
);
}
echo json_encode($array);
} catch(Exception $e){
die($e->getMessage());
}
}
if(isset($_GET['action']) && $_GET['action'] == "apiText"){
$lastId = $_GET['lastId'];
// this is teh limit set in the android java code (LOAD_LIMIT)
$limit = $_GET['limit'];
loadMoreData($lastId, $limit);
} else {
$limit = $_GET['limit'];
loaddata($limit);
}
?>
And this is the output of the above code --
[{"id":"14","title":"A Kid On His Way 2 Home With His Mom\r\nSaw A Couple Kissing On The Road,\r\nHe Suddenly Shouted & Said:\r\nLook Mom look, that boy and girl\r\nAre Fighting For A Chewing GUM."},
{"id":"13","title":null},
{"id":"12","title":null},
{"id":"11","title":null},
{"id":"10","title":"PAPPU : Daddy, have you\never been to Egypt?\nFATHER : No. Why do\nyou ask that?\nPAPPU: Well, where did\nyou get THIS mummy??"},
{"id":"9","title":"Y r u so opposite to me?\nWhen i say tea,u say coffee!\nI say white,u say black!\nI went to dental hospital,u went to mental hospital!\nI came back and u still there!"}]
Not able to understand, why its reading null values.
Data is present in mysql table, but then also reading some null values and some data are shown properly.
This is the structure of my mysql table --
Finally resolved the issue by googling, the issue is encoding problem --
$title = utf8_encode($data['textmsg']);
This resolved the problem.
In my code i get a bunch of results from my database like so:
$records = $conn->prepare('SELECT sm.taak,u.username FROM schedule_mon AS sm JOIN users AS u ON sm.user_id=u.id');
$records->execute();
$results = $records -> fetchAll();
Then i loop through the results like this:
foreach( $results as $row ) {
echo $row['taak']." ".$row['username']."</br>";
}
My results look like this:
Tafel dekken Peter
Tafel afruimen Chrisformer
Afwasmachine inruimen Frek
Afwasmachine uitruimen desley
The format is basically a task and then the user that has to perform that task. I would now like to know, lets say the user that has to perform a task is named Peter. How do i give peter a different color than the others.
So if user = peter then put peter in an <li> with a certain class. So i can give it a distinct color in css.
Use a <span> around the part you want to color differently:
foreach( $results as $row ) {
if ($row['username'] == "Peter") {
echo $row['taak']." <span class='className'>".$row['username']."</span></br>";
} else {
echo $row['taak']." ".$row['username']."</br>";
}
}
Than use CSS to assign a color to the className:
.className {
color:red;
}
I have created a function which is using recursion to find out childs of Given User. as shown below :
function recursionFunc($param) {
$q = "select cust_id,amount,position from testtab where parent_id = $param";
$res = mysql_query($q);
static $i = 0;
while ($row = mysql_fetch_assoc($res)) {
$i++;
recursionFunc($row['cust_id']);
}
return array('totalChild'=>$i);
}
There are two cases:
I want to call recursionFunc() for each user i am having
Recursion will be done in order to find childs of a user.
Now i want to call this function in while loop in order to fetch childs of all user i am having.
Since i am using static variable $i to store the value of childs.
Now when function will be called for the first user it returns correct value of childs but return wrong value in all other cases.
AS show Below
$cutData = "select cust_id from testtab";
$ress = mysql_query($cutData);
while ($raw = mysql_fetch_assoc($ress)) {
$response = recursionFunc($raw['cust_id']);
echo '<pre>'.$raw['cust_id'];
print_r($response);
echo '<br>';
}
Outputs
1Array ( [totalChild] => 7 ) 2Array ( [totalChild] => 10 ) 3Array ( [totalChild] => 12 )
It will be great if you can help me .
Thanks in advance.
UPDATE: Still can't seem to figure it out. If anyone can lend a hand, it would be appreciated ^^.
I am having a problem and I'm not sure where my code is breaking down. I have a 'follow' function where you can follow different registered users. Their userID's of who you followed are stored in an array (follower_array). It's retrieving each member from the array, but of each member that's followed instead of displaying all the content, it's only displaying the 1 latest one from each member.
$broadcastList= "";
if ( $follower_array != "" ) {
$followArray = explode(",", $follower_array);
$followCount = count($followArray);
$i = 0;
$broadcastList .= "<table>";
foreach( $followArray as $key => $value ) {
$i++;
$sqlName = mysql_query("
SELECT username, fullname
FROM members
WHERE id='$value'
LIMIT 1
") or die ("error!");
while ( $row = mysql_fetch_array($sqlName) ) {
$friendUserName = substr($row["username"],0,12);
}
$sqlBroadcast = mysql_query("
SELECT mem_id, bc, bc_date, device
FROM broadcast
WHERE mem_id='$value'
ORDER BY bc_date ASC
LIMIT 50
") or die ("error!");
while ( $bc_row = mysql_fetch_array($sqlBroadcast) ) {
$mem_id = $bc_row['mem_id'];
$bc = $bc_row['bc'];
$dev = $bc_row['device'];
$bc_date = $bc_row['bc_date'];
$broadcastList .= "<td><a href='member.php?id=' .$value. ''>
$friendUserName</a> • $when_bc • Via: $dev <b>$bc</b></td></tr>";
}
broadcastList .= "</table>";
}
}
So, it's retrieving the members entirely, but not more than their single latest "broadcast." Any insight would be appreciated.. thank you!
Here's what's happening:
while( $row = some_next_result_function() ){
$result = $row["thing"];
}
Is going to overwrite $result every time, so you'll only end up with the last result.
You need to make a list and append to it instead.
I'm gonna take a shot in the dark:
$broadcastList .= "<td><a href='member.php?id=' .$value. ''>
$friendUserName</a> • $when_bc • Via: $dev <b>$bc</b></td></tr>";
That line pretty much misses a starting "tr" element. Are you sure the content isn't shown simply because of the faulty html markup?
Also:
broadcastList .= "</table>";
You're missing the $ there ;).
I don't know if this fixes it or even helps you; but I sure hope so :). Alternatively; you can also check the HTML source to see if the entries really aren't there (see first remark).