Drupal & PHP/MySQL : How to compare fields with current user's field? - php

I've an issue, which is about php syntax/mysql in drupal:
Let's say that userA has created a content type called "test" where he filled the field field_example with value "xxx". Afterwards, another user, userB has created another content and filled the same field field_example with the same value "xxx".
I'd like to know how is it possible to display a view only with the node created where the field field_example is the same for the current user ? I don't have (and i don't want) a user reference in the content type "test" i'm using.
I've looked through View PHP Filter, but i'm wondering how to compare values of field ? Here's my attempt [i'm not an expert in PHP as you'll might notice :) ] :
<?php
$a="SELECT uid FROM users WHERE uid=%d";
/* ??? How to create $b which can get value of field_example from content_type_test from current user which is logged in ? */
$b="";
$c="SELECT field_example FROM content_type_test";
if ($b==$c){
echo "Ok, I've what I want :) ";
}
?>
Any help would be greatly appreciated since it's been a while i'm looking for information about this query...
Thanks all :)

I don't have a Views module solution.
One thought that comes to mind is what if User A submits multiple nodes, which example value would you use then? Also, what version of Drupal are you working with?
Assuming that a user will only ever submit one content of this type and you are running Drupal 6 (my guess from code examples), then it might look something like this:
<?php
// current user
global $user;
// select this user's node
$nid = db_result(db_query("SELECT nid FROM {node} WHERE type = 'my_content_type' AND status = 1 AND uid = %d", $user->uid));
// if this node loads fine, then proceed with the rest
if ($node = node_load($nid)) {
// find nodes with the same example value, which do not belong to the current user
$result = db_query("SELECT nid FROM {node}
INNER JOIN {content_type_test} ctt ON n.vid = ctt.vid
WHERE n.status = 1 AND ctt.field_example_value = '%s' AND uid <> %d
ORDER BY n.created DESC", $node->field_example[0]['value'], $user->uid);
// loop through results
while ($row = db_fetch_object($result)) {
$node = node_load($node->nid);
// append the teaser output (if this is what you want to do)
$output .= node_view($node, TRUE);
}
// print the output
print $output;
}
else {
print t('No other content found.');
}
?>
If users submit more than one of those content types, then that would have to be another answer to avoid from writing a novel here. There's a couple ways to approach that.
Also if this was Drupal 7, I'd be using different functions as well.

I assume you want something like this:
function _get_list() {
global $user; // This is global variable, contains information for current logged in user.
$results = db_query("SELECT ctt.field_example FROM {node} n JOIN {content_type_test} ctt ON n.nid = ctt.nid AND n.vid = ctt.vid WHERE n.uid = %d", $user->uid);
while($row = db_fetch_object($results)){
//$row->nid.. etc..
}
}

Related

PHP highlight selected item

Just like the image above, when the user clicks one of the list on the right side, it highlights the selected one.
$result = mysqli_query($con, "SELECT * FROM contacts") or die(mysqli_error($con));
while($row = mysqli_fetch_array($result)){
$company = $row['eyo_company_name'];
$id = $row['con_id'];
$editLinks .= "\n\t$company<br>";
}
this is how I brought the list out from the database. Would there be any way I could add a class or add b tag on selected one only ?
If I understand correctly, you are trying to highlight one of the links output by PHP. To do so you will need to know which one to highlight.
If you have a GET variable set to the current contact ID, you could do something like this:
while($row = mysqli_fetch_array($result)){
$company = $row['eyo_company_name'];
$id = $row['con_id'];
//let's check if we've pre-selected a company
// and if so, is this the company we selected?
if (true === array_key_exists('CURRENT_COMPANY_ID', $_GET) && $id === $_GET['CURRENT_COMPANY_ID']) {
//we did select this company for this PHP request
// let's make the HTML output custom to highlight the selected company
$editLinks .= "\n\t<strong>$company</strong><br>";
} else {
$editLinks .= "\n\t$company<br>";
}
}
This example expects that your request to the PHP script generating your list of links will include CURRENT_COMPANY_ID=<ID HERE> in the URL.
For example, if the URL for the request that generates your list of links looks like this:
/getMySuperAwesomeList.php
It would need to look like this:
/getMySuperAwesomeList.php?CURRENT_COMPANY_ID=123
Where 123 matches the con_id of the record you want to highlight.
I chose to use array_key_exists() to make sure that the request actually included the CURRENT_COMPANY_ID data in the URL. Here is documentation for that function: https://www.php.net/array_key_exists

socialmedia status comment system

I am trying to create a post-comment system, with simple php-mysqli, as simple as it is, it does not seem to give me the result in the fashion I want i.e:
---POST MESSAGE----
-----comments-----
Here is the code I used:
<?php
session_start();
include_once('php_includes/db_conx.php');
$user=$_SESSION['user'];
$o =mysqli_query($db_conx, "SELECT post.id,post.post,post.date,post_comments.poster,post_comments.comment,post_comments.date FROM post LEFT JOIN post_comments ON post.id=post_comments.post_id AND post.username='$user' ORDER BY post.date");
while($r=mysqli_fetch_array($o,MYSQLI_ASSOC)){
$status= $r['post'];
$date=$r['date'];
$com=$r['comment'];
$pid=$r['id'];
$poster=$r['poster'];
if(count($pid) > 1){
}
echo $status.'|'.$pid.'|'.$date.'<br>'.$poster.':'.$com.'<hr>';
}
?>
It seems to duplicate the post for each comment for same post.
Not sure am making sense, but i will appreciate an answer.
First, add post id to your query's ORDER BY. That will ensure that your post and all its comments appear together, and only once. (I'd recommend adding post_comments.date as well so your comments will appear in order, but that won't be necessary to get the grouping working.)
... ORDER BY post.date, post.id, post_comments.date
Then keep track of the post id as you go. Echo the post information only when the post id changes.
$id = null; // initialize to null
while ($r = mysqli_fetch_array($o, MYSQLI_ASSOC)) {
$pid = $r['id'];
$status = $r['post'];
$date = $r['date'];
$com = $r['comment'];
$poster = $r['poster'];
if ($pid !== $id) {
echo $status.'|'.$pid.'|'.$date.'<br>'; // new post, so echo post info here
$id = $pid; // $id becomes new post id
}
if ($com) {
echo $poster.':'.$com.'<br>'; // echo comment if present
}
}
One other thing that will probably cause some trouble is that you have selected both post.date and post_comments.date in your query, so I'm not sure which one will be in $r['date']. It would be a good idea to alias at least one of those columns to disambiguate them.

can not get the id by using the foreach() and $_POST[]

okay friends,
I have two tables
1st table: social_networks
2nd table: members_social_accounts
In the user control panel, I have a page contains a form where I list all the social networks; and in a front of each one of them there is an input text box.
When the member opens that page, he will see all the social networks listed, and if he previously added his account in any social network, then he will see it in the text box, otherwise, the text box will be empty. I used the following code to that:
$s = mysqli_query($link, "SELECT social_networks.network_id, social_networks.network_name, members_social_accounts.member_account FROM social_networks LEFT JOIN members_social_accounts ON social_networks.network_id = members_social_accounts.network_id AND members_social_accounts.member_id = '$member_id' ORDER BY social_networks.network_id");
while($i = mysqli_fetch_assoc($s)){
$network_id = $i['network_id'];
$network_name = $i['network_name'];
$member_account = $i['member_account'];
}
and the input box is:
<?=$network_name;?> = <input type="text" name="ids[<?=$network_id;?>]" id="<?=$network_id;?>" value="<?=$member_account;?>" /><br />
Now, what I am trying to do is when the user update the page (submit the form), I want the code to update the database by the following steps:
If the member (e.g. $member_id =1 ) has already added his account to that network (e.g. $network_id = 1) then, we will UPDATE the members_social_accounts table with the member network account (e.g. $member_account = 1111111111). So, I DO NOT add a new record for the same member_id and the same network_id but with different account value.
so, the database table will be something like this:
else if the member (e.g. $member_id=1) is adding a new account (e.g. $member_account = 2222222222) to a network (e.g. $network_id = 3), then I want to INSERT that to the members_social_accounts table as a new record, and the table will be for example like the following:
What I've tried so far is the following:
<?php
if(isset($_POST))
{
foreach($_POST['ids'] AS $ids)
{
$s = mysqli_query($link, "SELECT * FROM members_social_accounts WHERE network_id = '{$ids}' AND member_id = '$member_id'");
echo $n = mysqli_num_rows($s);
if($n == 1)
{
// UPDATE the members_social_accounts table
}
else
{
// INSERT a new record in members_social_accounts table
}
}
}
?>
but I have a problem which is that $_POST[ids] AS $ids is getting the member_account (e.g. aaaaaaaaaa and bbbbbbbbbb) instead getting the netword_id (e.g. 1 and 2). Therefore, I am not able to update or insert in the members_social_accounts table.
I appreciate your help in pointing what is wrong with my code or logic.
Thanks in advance
P.S. You can download a copy of the files and the database from this link:
sample files and db
This is due to the fact that the actual value of your input is the member_account field.
<input type="text" name="ids[<?=$network_id;?>]" id="<?=$network_id;?>" value="<?=$member_account;?>" />
Take a look at the value which has been assigned the return from $member_account variable.
You could just do:
<input type="hidden" name="nid" value="<?=$network_id;?>"/>
Then you can do $_POST['nid'] to get the real value of the network id.

Creating a Chart with PHP and MySql

I have a database with the following table:
id value
-----------
1 yes
2 no
3 no
4 maybe
I'm using some simple php to log the choices entered on a poll website. The user selects a radio box and it is entered into the above table. However, I want to make this a little more flexible. I created a simple backend that allowed an admin user to add or delete poll choices. What would I do to show on the frontend the number of votes for each individual choice, when the number of choices is not constant? I know I could do this easily if the poll choices were static but since the backend user will be changing the choices, how could I dynamically display the results?
I am not really sure what you are asking. Is it COUNT you're looking for?
Don't worry about the choices or the number of choices, grab all the votes/choices and iterate through them and add them to an array indiscriminately: http://codepad.org/LWPyuTqj
$total = array();
$votes = array(1=>'yes',2=>'no',3=>'no',4=>'maybe');
foreach($votes as $vote) {
if (!isset($total[$vote]))
$total[$vote] = 1;
else
$total[$vote] += 1;
}
print_r($total);
I would recommend google graph API for this. It is really easy!
http://code.google.com/apis/chart/interactive/docs/gallery/piechart.html
Generate the code dynamically, using the first example on the link above. First select the values. This assuming there is a question ID so you can relate to the question. In this case id 1.
$result = mysql_query('SELECT value,COUNT(*) as num FROM choises WHERE question_id = 1 GROUP BY value');
Then with PHP loop through the data
$results = array();
while ($row = mysql_fetch_assoc($result)){
$results[$row['value']] = $num;
}
With this you can generate the graph:
echo 'data.addRows('.count($results).');';
$i = 0;
foreach ($results as $value => $num){
echo'
data.setValue('.$i.', 0, "'.$value.'");
data.setValue('.$i.', 1, '.$num.');
';
$i++;
}

How to make a "distinct" detection on a foreach loop

At this time I have this very complex query that I loop through and I get something like this:
List of Challenges:
TEAM A
- Challenge 1
TEAM A
- Challenge 4
TEAM A
- Challege 6
And I want to change to something like:
TEAM A
- Challenge 1
- Challenge 4
- Challenge 6
My question is, since the query is a very complex one, maybe I could do this inside the loop but, if that's the case, how can we achieve something like that?
Can I ask an example case so that I can use, in order to solve this issue?
Thanks a lot,
MEM
UPDATE:
The query is something like this:
Translated:
public function listachallengesPendentes()
{
$select = $this->getAdapter()->select();
$select->from(array("e"=>"teams"),array('name'));
$select->join(array("de"=>"challengeperteam"),"e.cod_team = de.cod_teamFk",array());
$select->join(array("d"=>"challenges"),"d.cod_challenge = de.cod_challengeFk",array('title'));
$select->columns(array("e.cod_team"
,"name_team"=>"e.name"
,"d.cod_challenge"
,"name_challenge"=>"d.title"
,"d.details"
,"d.score"
,"category"=>"d.cod_categoryFk"
,"de.proof"
,"de.date_concluded"
,"de.cod_challenge_team"
));
$select->where("de.status = 0");
$select->order(array('e.cod_team DESC', 'de.cod_challenge_team DESC'));
return $this->getAdapter()->fetchAll($select);
}
So I need to add a distinct some part :s :D ?
The foreach actually is pretty basic:
foreach ($challenges as $d){
//display the name:
echo $d['name_team'];
...
}
UPDATE 2
The clean query (not tested):
SELECT e.name
,d.cod_team
,d.cod_challenge
,d.title
,d.details
,d.score
,de.proof
,de.date_concluded
,de.cod_challenge_team
FROM teams e
INNER JOIN challengeperteam de ON de.cod_teamFk = e.cod_team
INNER JOIN challenges d ON d.cod_challenge = de.cod_challengeFk
WHERE de.status = 0
ORDER BY e.cod_team DESC, de.cod_challenge_team DESC;
Something along the lines of:
$current_team = null;
foreach($challenges as $challenge){
if($current_team != $challenge->team){
$current_team = $challenge->team;
echo $current_team, "\n";
}
echo $challenge->challenge_name, "\n";
}
At a very basic level, ie in the loop, you can just detect if the TEAM A variable is equal to the current (previous) value, and if so, don't print it a second time. This relies on the result set being sorted on the TEAM A column.
However, you can also do this in the SQL query, so if you can provide the current SQL Query, I can explain how you'd update it.
you could store the array results in a multi-dimensional array like so:
$query_Challenges = "SELECT `Team`,`Challenges` FROM YourTable";
$Challenges = mysql_query($query_Challenges, $dbconnection) or die(mysql_error());
$row_Challenges = mysql_fetch_assoc($Challenges);
$challengeResults = array();
do{
if(!array_key_exists($row_Challenges['cod_team'])){
$challengeResults[$row_Challenges['cod_team']] = array();
}
$challengeResults[$row_Challenges['cod_team']][] = $row_Challenges['cod_challenge_team'];
}while($row_Challenges = mysql_fetch_assoc($Challenges));
EDIT
looking at your query statement, the data should be already sorted properly by your ORDER clause, so if you just need not repeatedly print the team as shown in codeblock 2, then something like:
$team = '';
do {
if($team != $row_Challenges['cod_team']){
echo "TEAM $row_Challenges['cod_team']<br/>";
$team = $row_Challenges['cod_team'];
}
echo " - $row_Challenges['cod_challenge_team']<br />";
}while($row_Challenges = mysql_fetch_assoc($Challenges));
you could easily substitute a foreach for the do loop, as long as there is a variable used as the "current team" and an if statement used to say "dont print the next team name unless its different than the current team name"

Categories