Yii: SQL query for getting the top users for every month and top users at the end of year - mysql

I am a yiibie, I have a question that I have a table named user_join_event which has id(PK) ngo_id(FK) event_id(FK) date_created date_modified as objects, and I want to get the 5 users Id's(which are repeated the most in this table) for every month. Like January top 5 users, Feb top 5 users and so on and then the top 5 users at the end of the year from this table, like once the year is completed it should give again the top 5 users from all over the month. Please help me with this, how to write an SQL query for this, thank you.
public function actionAllstats()
{
$this->layout='main';
$user=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_created)=:year and MONTH(date_created)=:month',
'param' => array(':year'=>2015, ':month'=>$yourMonth),
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
$this->render('allstats', array("user"=>$user));
}
and this is my view file
<div>
<?php
foreach($user as $show)
{
for($i = 1 ; $i <=12 ; $i++)
{
if($yourMonth == $i)
{
$model = User::model()->findByAttributes(array('id'=>$show->user_id,));
if (isset($model))
{
echo '<h3>' . $show->user_id . ' - ' . $model->username . '</h3>';
}
else {
echo '<h3>' . $show->user_id . ' - Username not found</h3>';
}
}
}
}
?>
</div>

For the Year you can sue this query for getting the users
$user=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_create)=:year',
'params' => array(':year'=>2015)
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
and for the month you can do a loop from 1 to 12 using this query and set $yourMonth withe the value in loop
$user=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_create)=:year and MONTH(date_create)=:month',
'params' => array(':year'=>2015, ':month'=>$yourMonth )
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
Controller action
public function actionAllstats()
{
$this->layout='main';
$myCurrYear = date("Y")
$userYear=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_create)=:year',
'params' => array(':year'=>$myCurrYear)
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
$this->render('allstats', array("userYear"=>$userYear));
}
View
This view in not based on good pratice, because use access to model inside a view. is a trial for lead you to understand some of the problem related with question.
<?php // this for the twelve month
for($month = 1 ; $month <=12 ; $month++) {
<div>
$user=UserJoinEvent::model()->findAll(array(
'condition' => 'YEAR(date_created)=:year and MONTH(date_created)=:month',
'params' => array(':year'=>2015, ':month'=>$month),
'select'=>'user_id',
'group'=>'user_id',
'order'=>'COUNT(*) DESC',
'limit' => 5
));
foreach($user as $show) {
$model = User::model()->findByAttributes(array('id'=>$show->user_id,));
if (isset($model)) {
echo '<h3>' . $show->user_id . ' - ' . $model->username . '</h3>';
}
else {
echo '<h3>' . $show->user_id . ' - Username not found</h3>';
}
}
</div>
}
?>
<div>
<?php // the for the year
foreach($userYear as $show) {
$model = User::model()->findByAttributes(array('id'=>$show->user_id,));
if (isset($model)) {
echo '<h3>' . $show->user_id . ' - ' . $model->username . '</h3>';
}
else {
echo '<h3>' . $show->user_id . ' - Username not found</h3>';
}
}
?>
</div>

Related

Wordpress Insert Query not working

I am creating web services for an App, but I am stuck with a insert query. Actually I made a rating system and want to insert value in database with wordpress standard.
Here is my query:
$res = $wpdb->query( $wpdb->prepare(
"INSERT INTO $table_name(rating_postid, rating_posttile, rating_rating, rating_username, rating_userid) VALUES (%d, %s, %d, %s, $d )",
array(
$rating_postid,
$post_title,
$post_rating,
$user_name,
$rating_userid
)
)
);
and here is the other one:
$res = $wpdb->insert(
$table_name,
array(
'rating_postid' => $rating_postid,
'rating_posttile' => $post_title,
'rating_rating' => $post_rating,
'rating_username' => $user_name,
'rating_userid' => $rating_userid
)
);
But no one is working, why?
if($res){
echo 'inserted';
}else{
echo 'not inserted';
}
I am getting else part alwasy
I used these queries very often and they worked me very well, But I am not sure what's wrong with them now... :(
Try this.
$wpdb->insert(
$table_name,
array(
'rating_postid' => $rating_postid,
'rating_posttile' => $post_title,
'rating_rating' => $post_rating,
'rating_username' => $user_name,
'rating_userid' => $rating_userid
),
array(
'%d',
'%s',
'%s',
'%s',
'%d'
)
);
Declaring $wpdb as global and using it to execute an SQL query statement that returns a PHP object
global $wpdb;
$table_name = $wpdb->prefix . "YOUR_TABLE_NAME"; // Enter without prefix
$data = array(
'rating_postid' => $rating_postid,
'rating_posttile' => $post_title,
'rating_rating' => $post_rating,
'rating_username' => $user_name,
'rating_userid' => $rating_userid
);
$result = $wpdb->insert($table_name, $data);
if( $result ){
echo "Inserted..!";
}else{
echo "Something wrong..!";
$wpdb->show_errors();
}

Looking for a cleaner way to run a query that has to check for multiple "AND" conditions

I'm running a query against a database and have to check for multiple conditions to be true. The code I have pulls the data I want, but if I had to check many more columns, it could get out of control very quickly. I don't want a query that where I have to write out a dozen or so "AND" conditions. I'm learning some MySQL as I go and any help would be appreciated.
<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//Set up and run my Query
$sql = "SELECT Project, Client, DateReceived, LastName, FinalReviewDate FROM Projects
WHERE FinalReviewDate IS NOT NULL
AND DateDelivered IS NULL
AND DateAccepted IS NULL
ORDER BY DateAccepted DESC";
$result = $conn->query($sql);
//Display results
if ($result->num_rows > 0) {
echo "<table><tr><th>Client</th><th>Project</th><th>Point of Contact</th><th>Date Project Received</th><th>Final Review Date</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["Client"]. "</td><td>" . $row ["Project"]. "</td><td> " . $row["LastName"]. "</td><td> " . $row ["DateReceived"]. "</td><td> " . $row["FinalReviewDate"]. "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
You can use an array for your and conditions. But in general you have to be careful if you are going to have prepared statements and bind values. Also, you can create your WHERE clause dynamically in a similar way like the following:
EDIT:
$where = array(
array(
'column'=>'FinalReviewDate',
'operator'=>'AND',
'condition'=>'IS NOT NULL',
'value'=>'',
),
array(
'column'=>'DateDelivered',
'operator'=>'AND',
'condition'=>'IS NULL',
'value'=>'',
),
array(
'column'=>'DateAccepted',
'operator'=>'AND',
'condition'=>'IS NULL',
'value'=>'',
),
array(
'column'=>'other_column',
'operator'=>'OR',
'condition'=>'>=',
'value'=>5,
),
);
$temp = array();
foreach($where as $key => $value) {
if ($value['value'] == '') {
$temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'];
} else {
$temp[] = $value['operator'].' '.$value['column'].' '.$value['condition'].' '.$value['value'];
}
}
$where_sql = '1 = 1 '.implode(' ', $temp);
echo $where_sql;
Result:
1 = 1 AND FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL OR other_column >= 5
OLD ANSWER
$ands = array(
array(
'column'=>'FinalReviewDate',
'condition'=>'IS NOT NULL'
),
array(
'column'=>'DateDelivered',
'condition'=>'IS NULL'
),
array(
'column'=>'DateAccepted',
'condition'=>'IS NULL'
),
);
$temp = array();
foreach($ands as $key => $value) {
$temp[] = $value['column'].' '.$value['condition'];
}
$and_sql = implode(' AND ', $temp);
echo $and_sql;
Result:
FinalReviewDate IS NOT NULL AND DateDelivered IS NULL AND DateAccepted IS NULL

Opencart retriving data from 2 tables

I´m trying to join 2 tables in opencart to make an sales report that specifies taxes (by class, there can be many tax%) for every order. I can only get the values from 1 table, but not 2.
How should I do this?
<?php $query = $this->db->query("SELECT * FROM `" . DB_PREFIX . "order`, `" . DB_PREFIX . "order_total`");
$ordersr = array();
// Check if there are any rows returned from the query
if ($query->num_rows > 0) {
// Loop through the returned rows for processing
foreach ($query->rows as $result) {
$ordersr[] = array(
'order_id' => $result['order_id'],
'invoice_no' => $result['invoice_no'],
'total' => $result['total'],
'order_status_id' => $result['order_status_id'],
'date_added' => $result['date_added'],
'date_modified' => $result['date_modified'],
'firstname' => $result['firstname'],
'lastname' => $result['lastname'],
'payment_country' => $result['payment_country'],
'payment_method' => $result['payment_method'],
'payment_code' => $result['payment_code'],
'shipping_method' => $result['shipping_method'],
'shipping_code' => $result['shipping_code'],
'currency_code' => $result['currency_code'],
'currency_value' => $result['currency_value'],
'order_status_id' => $result['order_status_id'],
'date_payed' => $result['date_payed']
);
}
} ?>

Trying to load data from a php file to the jQuery.Gantt

I'm starting in jquery, and I am trying to load the data from a php file to the jQuery.Gantt (http://taitems.github.io/jQuery.Gantt/). But the chart does load.
The script:
$(".gantt").gantt({
source: 'gantt_data_json.php',
navigate: "scroll",
scale: "weeks",
maxScale: "months",
minScale: "days",
itemsPerPage: 10,
....
});
The gantt_data_json.php:
require_once('libs/common.php');
$query ="SELECT * from gantt_table";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$gantt[] = array(
'name' =>$row['name'],
'desc' => $row['desc'],
'values' => array(
'to' => '/Date('.strtotime($row['to']).')/',
'from' => '/Date('.strtotime($row['from']).')/',
'desc' =>$row['desc2'],
'label' => $row['label'],
'customClass' => 'ganttRed'
)
);
}
echo json_encode($gantt);
Please could you help me to solve this issue?
Try this:
$query = "SELECT * from gantt_table";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
$gantt = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$data[] = array(
'name' => $row['name'],
'desc' => $row['desc'],
'values' => array(
array(
'from' => '/Date(' . $row['from'] . ')/',
'to' => '/Date(' . $row['to'] . ')/',
'desc' => $row['desc2'],
'label' => $row['label'],
'customClass' => 'ganttRed',
),
)
);
$gantt[] = $data;
}
echo json_encode($gantt);
its workfine
$json = Array();
while ($rs = mysqli_fetch_array($rsPedidos))
{
$data[] = array(
'name' => $rs['projeto'],
'desc' => $rs["site"],
$valor[] = array(
'from' => '/Date(' . strtotime($rs["data_inicio_ti"]) . '000)/',
'to' => '/Date(' . strtotime($rs["data_fim_ti"]) . '000)/',
'desc' => $rs["funcionario"].' / PO:'.$rs["numero_po"].' / R$:'.$rs["valor_po"],//12658580,//1320192000000 1497582000
'label' => $rs["servico"],
'customClass' => 'ganttRed',
),
'values' =>$valor,
);
$json = $data;
}
print json_encode($json);

FB:registration - array doesnt save any data

I did the Facebook Registration Plugin like in the official Facebook tutorial and with this code there it shows the total Array on screen:
if ($_REQUEST) {
echo '<p>signed_request contents:</p>';
$response = parse_signed_request($_REQUEST['signed_request'],
FACEBOOK_SECRET);
echo '<pre>';
print_r($response);
echo '</pre>';
} else {
echo '$_REQUEST is empty';
}
this brings me the following array:
signed_request contents:
Array
(
[algorithm] => HMAC-SHA256
[expires] => 1324xxxx400
[issued_at] => 132446xxx80
[oauth_token] => AAADRjT73VhwBALl6Gb3EVarvyGU7xxxxxxxxxxxxxxxxxxxSAUuoZAGlydkX2pH3
[registration] => Array
(
[name] => Philipp Mail
[email] => p.mail#xxxxde
[location] => Array
(
[name] => Munich, Germany
[id] => 1.1604xxxxxx286E+14
)
[birthday] => xx/xx/19x7
)
[registration_metadata] => Array
(
[fields] => [{'name':'name'}, {'name':'email'}, {'name':'location'}, {'name':'birthday'}]
)
[user] => Array
(
[country] => de
[locale] => de_DE
)
[user_id] => 10xxxxxxx5426
)
Now I changed it for storing several data to mysql:
if ($_REQUEST) {
echo '<p>signed_request contents:</p>';
$response = parse_signed_request($_REQUEST['signed_request'],
FACEBOOK_SECRET);
$name_arr = explode(' ',$name,2);
$vname = $name_arr[0];
$zname = isset($name_arr[1])?$name_arr[1]:'';
$email = $response["registration"]["email"];
$ort = $response["registration"]["location"]["name"];
$anrede = $response["registration"]["gender"];
$geburtstag = $response["registration"]["birthday"];
// Connecting to database
mysql_connect($dbhost, $dbuser, $dbpass) or die("MySQL Error: " . mysql_error());
mysql_select_db($dbname) or die("MySQL Error: " . mysql_error());
// Inserting into users table
$result = mysql_query("INSERT INTO REKRU_mem (mem_id, vname, zname, ort, email, userpass, chili, regdatum, geburtstag, fbuid)
VALUES
(NULL, '$vname', '$zname', '$ort', '$email', MD5('".$gesamtpass."'),'$chili', '0000-00-00 00:00:00', '$geburtstag', '$user_fbid')");
if($result){
// GOT RESULTS
}
else
{
// Error in storing
}
}
else
{
echo '$_REQUEST is empty';
}
When I look in mysql after a registration there is a new line but it saves only the actual registration time. Can anyone of U see what is my mistake?
do not use this code in a plublic Area! You can make a SQL-Injection (could also be the problem why you cannot insert).
Try this instead of the mysql_query:
$vname = mysql_real_escape_string($vname);
$zname = mysql_real_escape_string($zname);
$ort = mysql_real_escape_string($ort);
$email = mysql_real_escape_string($email);
$gesamtpass = mysql_real_escape_string($gesamtpass);
$chili = mysql_real_escape_string($chili);
$geburtstag = mysql_real_escape_string($geburtstag);
$user_fbid = mysql_real_escape_string($user_fbid);
$result = mysql_query("INSERT INTO REKRU_mem (mem_id, vname, zname, ort, email, userpass, chili, regdatum, geburtstag, fbuid)
VALUES (NULL, '".$vname."', '".$zname."', '".$ort."', '".$email."', MD5('".$gesamtpass."'),'".$chili."', '0000-00-00 00:00:00', '".$geburtstag."', '".$user_fbid."')");