Custom pagination query error in CakePHP - pagination

I am new in CakePHP. Now, I am using cakephp (version 2.8.5).
I try to create custom query pagination because I need to join multiple tables. But, its not work and I got Unsupported operand types error.
In my User model, I try to create paginate() and paginateCount() function as shown in below.
public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
$recursive = -1;
// // Mandatory to have
// $this->useTable = false;
$sql = '';
$sql .= "SELECT u.id,u.name, u.password, r.display_name, GROUP_CONCAT(p.display_name SEPARATOR ', ') as per_name ";
$sql .= "FROM `users` u ";
$sql .= "LEFT JOIN roles r ON (u.role_id = r.id) ";
$sql .= "LEFT JOIN user_permission up ON (u.id = up.user_id) ";
$sql .= "LEFT JOIN permissions p ON (up.permission = p.id) ";
$sql .= "WHERE 1 GROUP BY u.name ORDER BY u.id ";
// Adding LIMIT Clause
$sql .= "LIMIT ".(($page - 1) * $limit) . ', ' . $limit;
$results = $this->query($sql);
return $results;
}
public function paginateCount($conditions = null, $recursive = 0,
$extra = array()) {
$sql = '';
$sql .= "SELECT COUNT(*) as count FROM
(SELECT u.id,u.name, u.password, r.display_name, GROUP_CONCAT(p.display_name SEPARATOR ', ') as per_name
FROM `users` u
LEFT JOIN roles r ON (u.role_id = r.id) LEFT JOIN user_permission up ON (u.id = up.user_id)
LEFT JOIN permissions p ON (up.permission = p.id)
WHERE 1
GROUP BY u.name
ORDER BY u.id ) AS Temp";
$this->recursive = $recursive;
$results = $this->query($sql);
return $results;
}
In my UsersController,
public function index() {
$users = $this->User->getAllUser();
//for pagination
$this->paginate = array(
'limit' => 4
);
$page = $this->paginate();
$count = $this->paginateCount();
$this->set('page',$page);
$this->set('rowCount',$count);
$this->set('users',$users);
$this->render('index');
}
But its not work and I got Unsupported operand types fatal error. I think may be I was wrong in here($this->paginate()). But actually not sure what is wrong in my code.
I already searching a lot of place on web and can't solve. I'm very appreciate for any suggestion.

Ok, now I understand what's wrong in my code.
Problem is not in controller. I was wrong when I return $results in paginateCount() function. The correct way to returning the result must be like return $results[0][0]['count']; in the paginateCount() function.
Because the query result in paginateCount() will return like this:
array(1) { [0]=> array(1) { [0]=> array(1) { ["count"]=> string(1) "5"
} } }
Complete code for paginateCount() is as shown in below.
public function paginateCount($conditions = null, $recursive = 0,
$extra = array()) {
$sql = '';
$sql = "SELECT COUNT(*) as count FROM
(SELECT User.id,User.name, User.password, r.display_name, GROUP_CONCAT(p.display_name SEPARATOR ', ') as per_name
FROM `users` User
LEFT JOIN roles r ON (User.role_id = r.id) LEFT JOIN user_permission up ON (User.id = up.user_id)
LEFT JOIN permissions p ON (up.permission = p.id)
WHERE 1
GROUP BY User.name
ORDER BY User.id ) AS Temp";
$this->recursive = $recursive;
$results = $this->query($sql);
return $results[0][0]['count'];
}

Related

How to import the excel file to mySQL database using php

I want to import the data in the excel to mySQL DB using php. I have tried using the way explained in other questions but nothing worked out for me. Kindly let me know how to import the data in to DB using php.
Also, do let me know where to place the excel file to be uploaded,I mean the location in the system.
method 1.you can use load data command
http://blog.tjitjing.com/index.php/2008/02/import-excel-data-into-mysql-in-5-easy.html
method 2. Excel reader
https://code.google.com/p/php-excel-reader/
method 3. parseCSV
https://github.com/parsecsv/parsecsv-for-php
method4. (PHP 4, PHP 5) fgetcsv
http://in1.php.net/fgetcsv
please refer this PHP code
<?php
//table Name
$tableName = "MyTable";
//database name
$dbName = "MyDatabase";
$conn = mysql_connect("localhost", "root", "") or die(mysql_error());
mysql_select_db($dbName) or die(mysql_error());
//get the first row fields
$fields = "";
$fieldsInsert = "";
if (($handle = fopen("test.csv", "r")) !== FALSE) {
if(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$fieldsInsert .= '(';
for ($c=0; $c < $num; $c++) {
$fieldsInsert .=($c==0) ? '' : ', ';
$fieldsInsert .="`".$data[$c]."`";
$fields .="`".$data[$c]."` varchar(500) DEFAULT NULL,";
}
$fieldsInsert .= ')';
}
//drop table if exist
if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$tableName."'"))>=1) {
mysql_query('DROP TABLE IF EXISTS `'.$tableName.'`') or die(mysql_error());
}
//create table
$sql = "CREATE TABLE `".$tableName."` (
`".$tableName."Id` int(100) unsigned NOT NULL AUTO_INCREMENT,
".$fields."
PRIMARY KEY (`".$tableName."Id`)
) ";
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not create table: ' . mysql_error());
}
else {
while(($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$num = count($data);
$fieldsInsertvalues="";
//get field values of each row
for ($c=0; $c < $num; $c++) {
$fieldsInsertvalues .=($c==0) ? '(' : ', ';
$fieldsInsertvalues .="'".$data[$c]."'";
}
$fieldsInsertvalues .= ')';
//insert the values to table
$sql = "INSERT INTO ".$tableName." ".$fieldsInsert." VALUES ".$fieldsInsertvalues;
mysql_query($sql,$conn);
}
echo 'Table Created';
}
fclose($handle);
}
?>

Paypal Success transation return values empty-- sometimes

There is a problem with my paypal Integration in live site.
For 90% of transactions, I didn't get any problem. Some times only I am facing this below problem.
Problem: After successful transaction, I am not getting Pay pal values like Transaction Id, Message etc. All values shows empty. It comes for 10% of transactions only. please tell me what may be the problem. Can't able to find out the reason
Thanks in Advance..
$paypal_email = '5345345345345f';
$cur_dir='http://'.$_SERVER['SERVER_NAME'] . dirname($_SERVER['REQUEST_URI']);
$return_url = $cur_dir.'/paymentsucess.php';
$cancel_url = $cur_dir.'/payment-not-sucess.php';
$notify_url = $cur_dir.'/payments.php';
extract($_POST);
$item_name = $exam_name;
$item_amount = $amount;
$userid=$userid;
if (!isset($_POST["txn_id"]) && !isset($_POST["txn_type"])){
$querystring = "?business=".urlencode($paypal_email)."&";
$querystring .= "item_name=".urlencode($item_name)."&";
$querystring .= "amount=".urlencode($item_amount)."&";
//loop for posted values and append to querystring
foreach($_POST as $key => $value){
$value = urlencode(stripslashes($value));
$querystring .= "$key=$value&";
}
$querystring .= "return=".urlencode(stripslashes($return_url))."&";
$querystring .= "cancel_return=".urlencode(stripslashes($cancel_url))."&";
$querystring .= "notify_url=".urlencode($notify_url);
header('location:https://www.paypal.com/cgi-bin/webscr'.$querystring);
exit();
}else{
$req = 'cmd=_notify-validate';
foreach ($_POST as $key => $value) {
$value = urlencode(stripslashes($value));
$value = preg_replace('/(.*[^%^0^D])(%0A) (.*)/i','${1}%0D%0A${3}',$value);// IPN fix
$req .= "&$key=$value";
}
$data['item_name'] = $_POST['item_name'];
$data['item_number'] = $_POST['item_number'];
$data['payment_status'] = $_POST['payment_status'];
$data['payment_amount'] = $_POST['mc_gross'];
$data['payment_currency'] = $_POST['mc_currency'];
$data['txn_id'] = $_POST['txn_id'];
$data['receiver_email'] = $_POST['receiver_email'];
$data['payer_email'] = $_POST['payer_email'];
$data['custom'] = $_POST['custom'];
$data['userid'] = $_POST['userid'];
// post back to PayPal system to validate
$header = "POST /cgi-bin/webscr HTTP/1.0\r\n";
$header .= "Content-Type: application/x-www-form-urlencoded\r\n";
$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";
$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);
if (!$fp) {
// HTTP ERROR
} else {
fputs ($fp, $header . $req);
while (!feof($fp)) {
$res = fgets ($fp, 1024);
if (strcmp ($res, "VERIFIED") == 0) {
// Validate payment (Check unique txnid & correct price)
$valid_txnid = check_txnid($data['txn_id']);
$valid_price = check_price($data['payment_amount'], $data['item_number']);
// PAYMENT VALIDATED & VERIFIED!
if($valid_txnid && $valid_price){
$orderid = updatePayments($data);
if($orderid){
}else{
}
}else{
}
}else if (strcmp ($res, "INVALID") == 0) {
}
}
fclose ($fp);
}
}

drupal block variable_set not saving select value

I am trying to created a block that saves a value from a select box. However, after reload, variable_get does not return the saved value... so variable_set seams not to be working.
What am I doing wrong here? (Drupal 6)
function get_courses(){
global $user;
$my_items_sql = 'SELECT course_node.uid, ';
//get the course nid
$my_items_sql .='course_node.nid as course_nid, ';
//get the course title
$my_items_sql .='course_node.title as course_title ';
$my_items_sql .=' from node as course_node where course_node.type="course" and course_node.uid = "'.$user->uid.'"';
$my_items_sql .=' order by course_node.nid; ';
$my_items_data= db_query($my_items_sql);
$my_courses = array();
while ($row = db_fetch_array($my_items_data)) {
//$course_node = node_load($row["course_nid"]);
$my_courses[$row["course_nid"]]=$row["course_title"];
}
//$variables['courses']=$my_courses;
//drupal_add_js(array('courses'=>$my_courses), "setting");
return $my_courses;
}
function front_page_block($op='list',$delta = 0, $edit = array()) {
$course_options = array();
$courses = get_courses();
$tmp = $courses;
$first_course = $tmp;
reset($first_course );
$first_course_nid = key($first_course);
$first_course_nid = key($first_course);
switch($op){
case 'list':
$blocks[0]['info']= t('Course Data Loader');
$blocks[0]['cache']= BLOCK_NO_CACHE;
return $blocks;
case 'configure':
$form['course_to_display'] = array(
'#type' => 'select',
'#description' => t('Display flashcards from which deck on the front page?'),
'#options' => $courses,
'#default_value'=>variable_get('front_page_deck_to_load', $first_course_nid)
);
return $form;
case 'save':
variable_set('front_page_deck_to_load',
$edit['front_page_deck_to_load']);
break;
}
At first check, what value is set for $edit['front_page_deck_to_load'], before call the
variable_set('front_page_deck_to_load', $edit['front_page_deck_to_load']); function.
If the value of $edit['front_page_deck_to_load'] is set properly, then variable_set is working.
Now the problem is, the '#default_value' of $form['course_to_display'] is not set properly. Please modify the get_courses() function as follows and try again:
function get_courses(){
global $user;
$my_items_sql = 'SELECT course_node.uid, ';
//get the course nid
$my_items_sql .='course_node.nid as course_nid, ';
//get the course title
$my_items_sql .='course_node.title as course_title ';
$my_items_sql .=' from node as course_node where course_node.type="course" and course_node.uid = "'.$user->uid.'"';
$my_items_sql .=' order by course_node.nid; ';
$my_items_data= db_query($my_items_sql);
$my_courses = array();
while ($row = db_fetch_array($my_items_data)) {
//$course_node = node_load($row["course_nid"]);
$my_courses[$row["course_title"]]=$row["course_title"];
}
//$variables['courses']=$my_courses;
//drupal_add_js(array('courses'=>$my_courses), "setting");
return $my_courses;
}
FYI: Please follow the Comments #1 at http://drupal.org/node/240783

How to stay sane with ExpressionEngines ambiguous channel field IDs?

When writing queries or running through result sets, I'm constantly having to refer to fields as "field_id_X". I want to believe there is a saner way to go about this than defining a CONST for every field_id/name pair.
define(NAME_FIELD ,'field_id_3');
define(HEIGHT_FIELD, 'field_id_4');
foreach( $result as $row ){
$name = $row[NAME_FIELD]; // :(
}
Get an Array for field id's and names...
function getFieldReferences() {
$sql = "SELECT field_id, field_name
FROM exp_channel_fields
WHERE site_id = ".$this->EE->config->item('site_id');
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$result = $result->result_array();
$finalResult = array();
foreach ($result as $row)
$finalResult[$row["field_id"]] = $row["field_name"];
return $finalResult;
} else {
return false;
}
}
Example conversion of a specific entry details $entry_id...
$sql = "SELECT exp_channel_data.*, exp_channel_titles.*, exp_channels.channel_name
FROM exp_channel_data, exp_channel_titles, exp_channels
WHERE exp_channel_data.entry_id = $entry_id
AND exp_cart_products.entry_id = $entry_id
AND exp_channel_titles.entry_id = $entry_id
LIMIT = 1";
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$result = $result->result_array();
$result = $result[0];
//### Get Field Titles ###
$fieldReferences = getFieldReferences();
//### Replace Field ID reference with name ###
foreach ($result as $key => $value) {
if (substr($key,0,9) == "field_id_") {
$result[$fieldReferences[substr($key,9)]] = $value;
unset($result[$key]);
}
if (substr($key,0,9) == "field_ft_")
unset($result[$key]);
}//### End of foreach ###
}
Convert Member fields to names based on specified member $id...
$sql = "SELECT m_field_id, m_field_name
FROM exp_member_fields";
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$memberFields = $result->result_array();
$sql = "SELECT exp_member_data.*, exp_members.email
FROM exp_member_data, exp_members
WHERE exp_member_data.member_id = $id
AND exp_members.member_id = $id
LIMIT 1";
$result = $this->EE->db->query($sql);
if ($result->num_rows() > 0) {
$result = $result->result_array();
$rawMemberDetails = $result[0];
//### Loop through each Member field assigning it the correct name ###
foreach($memberFields as $row)
$memberDetails[ $row['m_field_name'] ] = $rawMemberDetails['m_field_id_'.$row['m_field_id']];
}
You could look up exp_channel_fields.field_name (or field_label) by the field_id you have from exp_channel_data.

c# help with building where clause to query

i am newbie in c#,
i want to build query string , i do some conditions , every condition add another condition to where clause
i want something like that :
// BUILD SELECT QUERY
string where = "";
string[] where_arr = new string[];
if (condition1)
{
where_arr[index++] = " field = 5 ";
}
if (condition2)
{
where_arr[index++] = " field2 = 7 ";
}
if (where_arr.Count>0)
where = " where" + String.Join(" and ", where_arr);
string sql = "select count(*) as count from mytable " + where;
but i do not know exactly how to declare all the variables like where_arr
// BUILD SELECT QUERY
string where = "";
List<string> where_arr = new List<string>();
if (condition1)
{
where_arr.Add(" field = 5 ");
}
if (condition2)
{
where_arr.Add(" field2 = 7 ");
}
if (where_arr.Count > 0)
where = " where" + String.Join(" and ", where_arr.ToArray());
string sql = "select count(*) as count from mytable " + where;

Resources