Stacks

Whenever i get time from my work or personal life I try to solve the questions posted in Stacksoverflow. It help me to keep update every time. As there are big brains out their who implement new things or do the same thing in some interesting ways.  And also I can recall and share few implementation of my self answering related questions.

And YES….I do also ask question whenever i done with enough googling. The best thing in stack is it will provide correct answer within few minutes and only correct answers are promoted by the users.

My account link : Suresh Kamrushi
Listing below some of the questions and answer in which i have participated.

Stack2RSS Custom Feed

A custom RSS feed for the "/users/1900692/answers" Stack Exchange API method.

You can fetch it directly from mysql itself:

Select DATE_ADD('09:45:00', INTERVAL 15 MINUTE) as updatetime from tableName

For more information you can visit : http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add

As per your comment if you want to do it in PHP, You can do like this:

$date = new DateTime('09:45:00');
$date->add(new DateInterval('PT15M'));
echo $date->format('h:i:s') . "\n";  //it i will give you 10:00:00
Posted: April 6, 2017, 7:30 am

If I understood correct,You need to set time zone first like:

date_default_timezone_set('UTC');

And than you can use date function:

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A');
Posted: March 8, 2017, 1:42 pm

How to increase the size of the Clipboard:

  1. Click the Start button. Type sysdm.cpl into the search box and press the Enter key.
  2. Click the Advanced tab in the System Properties window. Click the Settings button under the Performance label header.
  3. Click the Advanced tab in the Performance Options window. Under the Virtual Memory header, click the Change... button.
  4. Clear the check box next to the Automatically manage paging file size for all drives option. This disables automatic "Virtual Memory" settings in Windows.
  5. Enter a value for the size of the new paging file. Enter a value larger than the current paging file size in the "Maximum Size" field (enter the value in megabytes). Click the Set button and then OK.
  6. Restart the computer for the new "Virtual Memory" settings to take effect. The Windows Clipboard now stores more data when copying and pasting between applications.

Reference: I need to increase the clip board size in Word

Posted: January 25, 2017, 9:19 pm

I Think bitwise operator are the best way to implement user permission. Here I am showing how we can implement it with MySQL.

Below is a sample tables with some sample data:

Table 1: Permission table to store permission name along with it bit like 1, 2, 4, 8.. etc (multiple of 2)

CREATE TABLE IF NOT EXISTS `permission` (
  `bit` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`bit`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Insert some sample data into the table.

INSERT INTO `permission` (`bit`, `name`) VALUES
(1, 'User-Add'),
(2, 'User-Edit'),
(4, 'User-Delete'),
(8, 'User-View'),
(16, 'Blog-Add'),
(32, 'Blog-Edit'),
(64, 'Blog-Delete'),
(128, 'Blog-View');

Table 2: User table to store user id,name and role. Role will be calculated as sum of permissions.
Example:

If user 'Ketan' having permission of 'User-Add' (bit=1) and 'Blog-Delete' (bit-64) so role will be 65 (1+64).
If user 'Mehata' having permission of 'Blog-View' (bit=128) and 'User-Delete' (bit-4) so role will be 132 (128+4).

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `role` int(11) NOT NULL,
  `created_date` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Sample data-

INSERT INTO `user` (`id`, `name`, `role`, `created_date`)
   VALUES (NULL, 'Ketan', '65', '2013-01-09 00:00:00'),
   (NULL, 'Mehata', '132', '2013-01-09 00:00:00');

Loding permission of user After login if we want to load user permission then we can query below to get the permissions:

SELECT permission.bit,permission.name  
   FROM user LEFT JOIN permission ON user.role & permission.bit
 WHERE user.id = 1

Here user.role "&" permission.bit is a Bitwise operator which will give output as -

User-Add - 1
Blog-Delete - 64

If we want to check weather a particular user have user-edit permission or not-

  SELECT * FROM `user` 
     WHERE role & (select bit from permission where name='user-edit')

Output = No rows.

You can see also : http://goo.gl/ATnj6j

Posted: February 25, 2016, 10:33 am

Go to the Sql tab run one of the below query:

delete from tableName;

Delete: will delete all rows from your table. Next insert will take next auto increment id.

or

truncate tableName;

Truncate: will also delete the rows from your table but it will start from new row with 1.

Posted: December 2, 2015, 7:51 pm

Try something like this:

insert into B (UPDATE_FILE, RUN_DATE, CREATED_DATE) 
SELECT UPDATE_FILE, RUN_DATE,now() from A 

It will insert current date in the "CREATED_DATE" column.

Posted: September 18, 2015, 7:55 am

Singleton

The single pattern is an often used pattern in many applications when only a single instance of a resource is required. The most obvious type of resource for PHP web pages is a database connection, although other resource types can be used. When fetching of dynamically creating a web page several database calls may need to be made. If a single instance of the resource could be used, rather than creating several connections, the overhead is minimized. The single instance in this case, is created by the singleton pattern.

<?php
class db {
    /*** Declare instance ***/
    private static $instance = NULL;

    /**
     * the constructor is set to private so
     * so nobody can create a new instance using new
     */
    private function __construct() {
        /*** maybe set the db name here later ***/
    }

    /**
     * Return DB instance or create intitial connection
     *  @return object (PDO)
     * @access public
     */
    public static function getInstance() {
        if (!self::$instance) {
            self::$instance = new PDO("mysql:host='localhost';dbname='animals'", 'username', 'password');
            self::$instance->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        return self::$instance;
    }
    /**
     * Like the constructor, we make __clone private
     * so nobody can clone the instance
     */
    private function __clone() {

    }
} /*** end of class ***/
?>

Lets look at what has happened in the singleton class above. A variable name $instance is created and made private, this ensures nobody and try to access it directly. Similarly, the constructor and __clone methods have been made private to prevent cloning of the class, or of somebody trying to instantiate an instance of it. The class has a single method for providing a resource, the getInstance() method.

The getInstance() method checks that an instance does not already exist. If no instance exists a new instance of the PDO class is created and assigned to the $instance variable. If an existing instance is available, the getInstance() method returns this. The result is that the returned value is always the same instance, and no new resource, or overhead, is required.

Here is a small demonstration of how this might be used in an application.

<?php
try {
    /*** query the database ***/
    $result = DB::getInstance()->query("SELECT animal_type, animal_name FROM animals");

    /*** loop over the results ***/
    foreach ($result as $row) {
        print $row['animal_type'] .' - '. $row['animal_name'] . '<br />';
    }
} catch (PDOException $e) {
    echo $e->getMessage();
}
?>

Factory

The factory pattern is a class that creates objects for you, rather than you needing to use the new keyword to create one yourself. The factory is, as the name suggests, a factory for creating objects. Why do we need this? Lets consider an application that uses an ini file for configuration option. Then the application is changed to gain the configuration options from a database. The rest of the application falls apart like a house of cards as the base is removed. This "tight coupling" of objects, where each object relies heavily on another, creates problems in larger applications. A system is needed where objects can reference each other, but are not inter dependent.
In our example of the configuration file becoming a database, if other classes were dependent on the class that read from the ini file, and this was suddenly tasked to the database class problems occur.
By using the factory design pattern, if you change the type of object from the ini reader class to the database class you only need to change the factory. Any other code that uses the factory will be updated automatically.

<?php
/**
 * @config interface
 */
interface Config {
    function getName();
}

/**
 * @config class
 */
class userConfig implements Config {
    /*
     * @username
     */
     public $user_id;

     /*** contructor is empty ***/
     public function __construct($id) {
        $this->user_id = $id;
     }

     public static function Load($id) {
        return new userConfig($id);
     }

     public function getName() {
         try {
             /*** query the database ***/
             $sql = "SELECT username FROM user_table WHERE user_id=:user_id";
             $db = db::getInstance();
             $stmt = $db->prepare($sql)
             $stmt->bindParam(':user_id', $this->user_id, PDO::PARAM_INT);
             return $stmt->fetch(PDO::FETCH_COLUMN);    
        } catch (PDOException $e) {
            /*** handle exception here ***/
            return false;
        }
    }
} /*** end of class ***/

/*** returns instance of config ***/
$conf = userConfig::Load( 1 );
echo $conf->getName();
?> 

This might seem a little excessive code for simply retrieving a username. But in large-scale application where a change from file based to database retrieval is made, the results could be catastrophic. Here its is simply a matter of changing the the getName() method retrieves the name, and the returned object is the same, thus allowing other parts of the application that require the username, eg: a login for a cart, to continue as they did previously.

Posted: December 22, 2014, 3:10 pm

Just add below lines to your “config.inc.php” file in the bottom:

$i++;
$cfg['Servers'][$i]['host'] = 'HostName:port'; //provide hostname and port if other than default
$cfg['Servers'][$i]['user'] = 'userName';   //user name for your remote server
$cfg['Servers'][$i]['password'] = 'Password';  //password
$cfg['Servers'][$i]['auth_type'] = 'config';       // keep it as config

. You will get “Current Server:” drop down with both “127.0.0.1” and one what you have provided with “$cfg['Servers'][$i]['host']” cam switch between the servers.

more Details: http://goo.gl/FZ6nqD

Posted: September 4, 2014, 6:14 am
$startDate = new DateTime( '2013-04-01' );    //intialize start date
$endDate = new DateTime( '2013-04-30' );    //initialize end date
$holiday = array('2013-04-11','2013-04-25');  //this is assumed list of holiday
$interval = new DateInterval('P1D');    // set the interval as 1 day
$daterange = new DatePeriod($startDate, $interval ,$endDate);
foreach($daterange as $date){
if($date->format("N") <6 AND !in_array($date->format("Y-m-d"),$holiday))
$result[] = $date->format("Y-m-d");
}
echo "<pre>";print_r($result);
Posted: September 4, 2014, 5:54 am

I Think bitwise operator are the best way to implement user permission. Here I am showing how we can implement it with Mysql.

Below is a sample tables with some sample data:

Table 1 : Permission table to store permission name along with it bit like 1,2,4,8..etc (multiple of 2)

CREATE TABLE IF NOT EXISTS `permission` (
  `bit` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`bit`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Insert some sample data into the table.

INSERT INTO `permission` (`bit`, `name`) VALUES
(1, 'User-Add'),
(2, 'User-Edit'),
(4, 'User-Delete'),
(8, 'User-View'),
(16, 'Blog-Add'),
(32, 'Blog-Edit'),
(64, 'Blog-Delete'),
(128, 'Blog-View');

Table 2: User table to store user id,name and role. Role will be calculated as sum of permissions.
Example :
If user 'Ketan' having permission of 'User-Add' (bit=1) and 'Blog-Delete' (bit-64) so role will be 65 (1+64).
If user 'Mehata' having permission of 'Blog-View' (bit=128) and 'User-Delete' (bit-4) so role will be 132 (128+4).

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `role` int(11) NOT NULL,
  `created_date` datetime NOT NULL
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Sample data-

INSERT INTO `user` (`id`, `name`, `role`, `created_date`)
   VALUES (NULL, 'Ketan', '65', '2013-01-09 00:00:00'),
   (NULL, 'Mehata', '132', '2013-01-09 00:00:00');

Loding permission of user After login if we want to load user permission than we can query below to get the permissions:

SELECT permission.bit,permission.name  
   FROM user LEFT JOIN permission ON user.role & permission.bit
 WHERE user.id = 1

Here user.role "&" permission.bit is a Bitwise operator which will give output as -

User-Add - 1
Blog-Delete - 64

If we want to check weather a particular user have user-edit permission or not-

  SELECT * FROM `user` 
     WHERE role & (select bit from permission where name='user-edit')

Output = No rows.

You can see also : http://goo.gl/ATnj6j

Posted: September 3, 2014, 12:09 pm

Here I am showing how we can implement it with Mysql.

Below is a sample tables with some sample data:

Table 1 : Permission table to store permission name along with it bit like 1,2,4,8..etc (multiple of 2)

CREATE TABLE IF NOT EXISTS `permission` (
  `bit` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`bit`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Insert some sample data into the table.

INSERT INTO `permission` (`bit`, `name`) VALUES
(1, 'User-Add'),
(2, 'User-Edit'),
(4, 'User-Delete'),
(8, 'User-View'),
(16, 'Blog-Add'),
(32, 'Blog-Edit'),
(64, 'Blog-Delete'),
(128, 'Blog-View');

Table 2: User table to store user id,name and role. Role will be calculated as sum of permissions.
Example :
If user 'Ketan' having permission of 'User-Add' (bit=1) and 'Blog-Delete' (bit-64) so role will be 65 (1+64).
If user 'Mehata' having permission of 'Blog-View' (bit=128) and 'User-Delete' (bit-4) so role will be 132 (128+4).

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `role` int(11) NOT NULL,
  `created_date` datetime NOT NULL
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Sample data-

INSERT INTO `user` (`id`, `name`, `role`, `created_date`)
   VALUES (NULL, 'Ketan', '65', '2013-01-09 00:00:00'),
   (NULL, 'Mehata', '132', '2013-01-09 00:00:00');

Loding permission of user After login if we want to load user permission than we can query below to get the permissions:

SELECT permission.bit,permission.name  
   FROM user LEFT JOIN permission ON user.role & permission.bit
 WHERE user.id = 1

Here user.role "&" permission.bit is a Bitwise operator which will give output as -

User-Add - 1
Blog-Delete - 64

If we want to check weather a particular user have user-edit permission or not-

  SELECT * FROM `user` 
     WHERE role & (select bit from permission where name='user-edit')

Output = No rows.

You can see also : http://goo.gl/ATnj6j

Posted: September 3, 2014, 12:07 pm

I Think bitwise operator are the best way to implement user permission. Here I am showing how we can implement it with Mysql.

Below is a sample tables with some sample data:

Table 1 : Permission table to store permission name along with it bit like 1,2,4,8..etc (multiple of 2)

CREATE TABLE IF NOT EXISTS `permission` (
  `bit` int(11) NOT NULL,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`bit`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

Insert some sample data into the table.

INSERT INTO `permission` (`bit`, `name`) VALUES
(1, 'User-Add'),
(2, 'User-Edit'),
(4, 'User-Delete'),
(8, 'User-View'),
(16, 'Blog-Add'),
(32, 'Blog-Edit'),
(64, 'Blog-Delete'),
(128, 'Blog-View');

Table 2: User table to store user id,name and role. Role will be calculated as sum of permissions.
Example :
If user 'Ketan' having permission of 'User-Add' (bit=1) and 'Blog-Delete' (bit-64) so role will be 65 (1+64).
If user 'Mehata' having permission of 'Blog-View' (bit=128) and 'User-Delete' (bit-4) so role will be 132 (128+4).

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `role` int(11) NOT NULL,
  `created_date` datetime NOT NULL
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

Sample data-

INSERT INTO `user` (`id`, `name`, `role`, `created_date`)
   VALUES (NULL, 'Ketan', '65', '2013-01-09 00:00:00'),
   (NULL, 'Mehata', '132', '2013-01-09 00:00:00');

Loding permission of user After login if we want to load user permission than we can query below to get the permissions:

SELECT permission.bit,permission.name  
   FROM user LEFT JOIN permission ON user.role & permission.bit
 WHERE user.id = 1

Here user.role "&" permission.bit is a Bitwise operator which will give output as -

User-Add - 1
Blog-Delete - 64

If we want to check weather a particular user have user-edit permission or not-

  SELECT * FROM `user` 
     WHERE role & (select bit from permission where name='user-edit')

Output = No rows.

You can see also : http://goo.gl/ATnj6j

Posted: September 3, 2014, 11:28 am

Detail blog to fix this issue is : http://goo.gl/JXWqfJ

You can solve this problem by following two ways:
A) Start your WAMP befor you login to skype. So that WAMP will take over the the port and there will be no conflict with the port number. And you are able to use Skype as well as WAMP.
But this is not the permanent solution for your problem. Whenever you want to start WAMP you need to signout Skype first and than only you are able to start WAMP. Which is really i don’t like.

B) Second option is to change the port of Skype itself, so that it will not conflict with WAMP. Following screen/steps will help you to solve this problem:
1) SignIn to Skype.
2) Got to the Tools -> options
3) Select the “Advanced” -> Connection
4) Unchecked “Use port 80 and 443 as alternatives for incoming connections” checkbox and click save.
5) Now Signout and SignIn again to skype. (this change will take affect only you relogin to skype)
Now every time you start WAMP will not conflict with skype.

Posted: May 16, 2014, 4:00 pm

Yes you can generate ERD with PHPMyAdmin. PHPMyadmin added this functionality from version 3.4

detail step to generate ERD : http://goo.gl/0z3vFE

You can refer to PHPMyAdmin documentation for more info: http://www.phpmyadmin.net/documentation/#pmadb

Posted: March 5, 2014, 10:37 am

you can achieve with mysql event scheduler--

http://dev.mysql.com/doc/refman/5.1/en/events.html

detail blog: http://goo.gl/6Hzjvg

Posted: February 28, 2014, 1:10 pm

Mysql introduce Event scheduler which we can use alternative to Cronjob. There are many advantages over cronjob like:

1)It is directly written on Mysql Server.

2) This is platform independent. Your application might be written in any language it does not matters. You just need to know mysql.

3) We can use them whenever there is a database update or cleanup required at regulare interval.

4) No need to compile queries every time hence performace increased.

5) Error can be log in log files. Syntax:

DELIMITER //
CREATE EVENT eventName
ON SCHEDULE EVERY 1 WEEK
STARTS 'Some Date to start'
ENDS 'End date If any' 

DO
BEGIN
   // Your query will be here
END//
DELIMITER ;

For more information you can visit official site:http://dev.mysql.com/doc/refman/5.1/en/create-event.html

detail blog: http://goo.gl/6Hzjvg

Posted: February 28, 2014, 1:09 pm

You can use function as below:

select FROM_UNIXTIME(UNIX_TIMESTAMP(),'%a %b %d %H:%i:%s UTC %Y');

output will be:

'Wed Feb 05 05:36:16 UTC 2014'

In your query

select COUNT(DISTINCT devices) AS "Devices",
  FROM_UNIXTIME(measure_tab.time,'%a %b %d %H:%i:%s UTC %Y') as d from measure_tab where 
  measure_tab.time >= 1375243200 and 
  measure_tab.time < 1375315200;

For more info you can check documentation: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_from-unixtime

You can see sql fiddle:http://sqlfiddle.com/#!2/a2581/20357

Posted: February 5, 2014, 5:57 am

instead using:

alert('Loaded: <? $_GET['someparameter'] ?>');

use like this:

alert('Loaded: <?php echo $_GET['someparameter'] ?>'); 
Posted: February 4, 2014, 10:16 am

remove single quote around amount like this and try:

SELECT * FROM {$db_sales} WHERE date = '{$date}' ORDER BY amount DESC
Posted: January 23, 2014, 10:56 am

simple you can do like this-

$result = $array1 + $array2;

Simple exapmle

$array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a');
$array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b');
$result = $array1 + $array2;
var_dump($result);

Output

array(5) {
  [0]=>
  string(6) "zero_a"
  [2]=>
  string(5) "two_a"
  [3]=>
  string(7) "three_a"
  [1]=>
  string(5) "one_b"
  [4]=>
  string(6) "four_b"
}
Posted: December 4, 2013, 10:56 am

Dont use mail() function of php it will send your mail to junk only. Instead use SMTP php mailer function.

Why we should use SMTP instead PHP mail():

SMTP log in to an actual account on a mailserver and send the mail through SMTP to another mail server. If the mail server is configured correctly, your mails are sent from an actual account on a mailserver and will not wind up flagged as spam.

Mail sent with the mail() function is sent with sendmail in most cases. There is no authentication going on and it will almost always be flagged as spam if you use the "From:" in the extra headers.

This is because if you take a look at an original email file in say, gmail, you will see the headers that are sent. You are actually sending from user@serverhostname.tld and not someone@example.com like you had told the mail function to do. If you use SMTP and view the original the email is actually sent from someone@example.com

You can download SMTP class from:

  1. https://code.google.com/a/apache-extras.org/p/phpmailer/source/browse/trunk/class.smtp.php?r=170
  2. http://www.phpclasses.org/package/14-PHP-Sends-e-mail-messages-via-SMTP-protocol.html
Posted: November 19, 2013, 9:30 am

login to Mysql as admin:

 mysql -uroot -ppassword;

And than run command:

mysql> show processlist;

You will get something like below :

+----+-------------+--------------------+----------+---------+------+-------+------------------+
| Id | User        | Host               | db       | Command | Time | State | Info             |
+----+-------------+--------------------+----------+---------+------+-------+------------------+
| 49 | application | 192.168.44.1:51718 | XXXXXXXX | Sleep   |  183 |       | NULL             ||
| 55 | application | 192.168.44.1:51769 | XXXXXXXX | Sleep   |  148 |       | NULL             |
| 56 | application | 192.168.44.1:51770 | XXXXXXXX | Sleep   |  148 |       | NULL             |
| 57 | application | 192.168.44.1:51771 | XXXXXXXX | Sleep   |  148 |       | NULL             |
| 58 | application | 192.168.44.1:51968 | XXXXXXXX | Sleep   |   11 |       | NULL             |
| 59 | root        | localhost          | NULL     | Query   |    0 | NULL  | show processlist |
+----+-------------+--------------------+----------+---------+------+-------+------------------+

You will see complete details of different connections. Now you can kill the sleeping connection as below:

mysql> kill 52;
Query OK, 0 rows affected (0.00 sec)
Posted: November 8, 2013, 7:44 am

If you want to do it manually you can do like this:

login to Mysql as admin:

 mysql -uroot -ppassword;

And than run command:

mysql> show processlist;

You will get something like below :

+----+-------------+--------------------+----------+---------+------+-------+------------------+
| Id | User        | Host               | db       | Command | Time | State | Info             |
+----+-------------+--------------------+----------+---------+------+-------+------------------+
| 49 | application | 192.168.44.1:51718 | XXXXXXXX | Sleep   |  183 |       | NULL             ||
| 55 | application | 192.168.44.1:51769 | XXXXXXXX | Sleep   |  148 |       | NULL             |
| 56 | application | 192.168.44.1:51770 | XXXXXXXX | Sleep   |  148 |       | NULL             |
| 57 | application | 192.168.44.1:51771 | XXXXXXXX | Sleep   |  148 |       | NULL             |
| 58 | application | 192.168.44.1:51968 | XXXXXXXX | Sleep   |   11 |       | NULL             |
| 59 | root        | localhost          | NULL     | Query   |    0 | NULL  | show processlist |
+----+-------------+--------------------+----------+---------+------+-------+------------------+

You will see complete details of different connections. Now you can kill the sleeping connection as below:

mysql> kill 52;
Query OK, 0 rows affected (0.00 sec)
Posted: November 8, 2013, 7:41 am

you should write like this-

if(is_array($result)){
   foreach($result as $er){
    echo $er."<br>";
   }
} else {
  //your code for handling error
}

You can get more info :http://us2.php.net/is_array

Posted: November 6, 2013, 1:53 pm

You can use array_unique like below:

$input = array("a" => "green", "red", "b" => "green", "blue", "red");
$result = array_unique($input);
print_r($result);

Output:

Array
(
    [a] => green
    [0] => red
    [1] => blue
)
Posted: November 5, 2013, 8:49 am

Try like this, it will create array of your varibale:

$array = Array ( 
  [0] => Ú 
  [1] => Ý 
  [2] => æ 
  [3] => â 
);
extract($array, EXTR_PREFIX_ALL, 'var');
$defined_vars = get_defined_vars(); 
print_r($defined_vars);

I know this is not exactly what you looking for, but can get some idea from this.

Posted: October 30, 2013, 8:29 am

try like this-

echo $a = "<script type='text/javascript' src='buyback$source.js'></script>";

Posted: August 14, 2013, 2:20 pm

You can try like this:

$start = new DateTime('01:00:00 PM');
$end = new DateTime('02:00:00 PM');
$diff = $start->diff($end);
echo $diff->format('%H'); 

You can get more info: http://in1.php.net/manual/en/datetime.diff.php

Posted: August 7, 2013, 2:18 pm

you can do that with Insert...on duplicate key update

OR

alternatively you can also be use Replace

Posted: April 9, 2013, 9:46 am

You can do like this-

$where = array();

if(1==$case) 
 $where['x'] = $something;
 $where['y'] = 'fixed';

else if(2==$case)
 $where['x'] = $something;
 $where['y'] = 'fixed';

$this->db->where($where);
$this->db->get();
Posted: April 5, 2013, 9:55 am

Try this-

$dStart = new DateTime('2013-03-15');
$dEnd = new DateTime('2013-04-01');
$dDiff = $dStart->diff($dEnd);
echo $dDiff->format('%d days')

Check PHP

Please check demo link

Posted: April 2, 2013, 5:03 am

You can use DOM, which support PHP4 for parsing XML.

Please see the below example:


XML Data:
<data>
<Report ID="1">
    <Date>REVIEW</Date>
    <AuthorID>1</AuthorID>
</Report>
<Report ID="2">
    <Date>REVIEW</Date>
    <AuthorID>2</AuthorID>
</Report>
</data>

<?php
$xmlDoc = new DOMDocument();
$xmlDoc->load( 'data.xml' );

$searchNode = $xmlDoc->getElementsByTagName( "Report" );

foreach( $searchNode as $searchNode )
{
    $valueID = $searchNode->getAttribute('ID');

    $xmlDate = $searchNode->getElementsByTagName( "Date" );
    $valueDate = $xmlDate->item(0)->nodeValue;

    $xmlAuthorID = $searchNode->getElementsByTagName( "AuthorID" );
    $valueAuthorID = $xmlAuthorID->item(0)->nodeValue;

    echo "$valueID - $valueDate - $valueAuthorID\n";
}
?>

Output:

1 - REVIEW - 1 2 - REVIEW - 2


Posted: February 22, 2013, 7:06 am

Try this-

CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
    insert into student (name,user_name,branch) values (in_name ,in_user_name,in_branch);
END
Posted: February 22, 2013, 6:56 am

Use IN only like below:

select * from TableName where 2 IN (ColumnOne,ColumnTwo,ColumnThree)
Posted: January 18, 2013, 4:17 pm

Just try this-

SELECT * FROM `pizza_table` WHERE  FIND_IN_SET(2,pizza_topping_id)

OR REGEXP

SELECT * FROM `pizza_table` WHERE pizza_topping_id REGEXP '^2,|,2$|,2,' OR pizza_topping_id =2

Please see the demo : demo

Posted: January 18, 2013, 3:27 pm

This is better way as it gives you result in a single line:

$this->db->query("Your query")->row()->campaign_id;
Posted: January 17, 2013, 2:01 pm

Just Try this- (tested working fine)

function createColumnsArray($end_column, $first_letters = '')
{
  $columns = array();
  $length = strlen($end_column);
  $letters = range('A', 'Z');

  // Iterate over 26 letters.
  foreach ($letters as $letter) {
      // Paste the $first_letters before the next.
      $column = $first_letters . $letter;

      // Add the column to the final array.
      $columns[] = $column;

      // If it was the end column that was added, return the columns.
      if ($column == $end_column)
          return $columns;
  }

  // Add the column children.
  foreach ($columns as $column) {
      // Don't itterate if the $end_column was already set in a previous itteration.
      // Stop iterating if you've reached the maximum character length.
      if (!in_array($end_column, $columns) && strlen($column) < $length) {
          $new_columns = createColumnsArray($end_column, $column);
          // Merge the new columns which were created with the final columns array.
          $columns = array_merge($columns, $new_columns);
      }
  }

  return $columns;
}
echo "<pre>";
print_r( createColumnsArray('BZ'));

copied from http://php.net/range

Posted: January 11, 2013, 12:59 pm

Add semicolon after use

USE e-commerce;
CREATE TABLE `categories` (
  `id` SMALLINT NOT NULL AUTO_INCREMENT,
  `category` VARCHAR( 30) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `category` (`category`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;
Posted: January 10, 2013, 11:23 am

you can do like this--

$file = "Some text content".file_get_contents($url);
Posted: January 7, 2013, 2:45 pm

You can do like this-

public function members() {

    if($this->session->userdata('is_logged_in')){
        $data['session'] = $this->session->all_userdata();
        $facebook_id = $data['id']; 


        $this->load->model('idea'); 
        $data['idea'] = $this->idea->get_idea($facebook_id); 

        $this->load->view('members', $data); 
    } else {
        redirect('main/login'); 
    }
}
Posted: January 3, 2013, 2:42 am

You can do it with .htaccess file like below

RewriteRule ^var1-([a-zA-Z0-9-]+)$-var2-([a-zA-Z0-9-]+)$  youpage.php?var1=$1&var2=$2;

or you can can split it regular expression-

Posted: January 2, 2013, 2:56 pm

You can try this-

$num_args = func_num_args();
if($num_args == 1)
 $surname = func_get_arg(1);
else
 $surname = func_get_arg(2);
 $name = func_get_arg(1);

Please test it before you use it.

Posted: January 2, 2013, 1:28 pm

You can use the keyword between

select * from tableName where id between 80 AND 90
Posted: January 2, 2013, 9:09 am

do it like this-

$data['pageTitle'] = 'Your page title';

instead

$this->data['pageTitle'] = 'Your page title';
Posted: December 27, 2012, 7:26 am

I just try with loop structure in Mysql and got success. Posting to share only--

CREATE PROCEDURE `root_connect`(IN init char(1),OUT str char(15))
BEGIN
    set @startChar:=(select connector from tableName where root = init);
    set @endloop := "no";
    set @fullchar:= @startChar;
    set @newchar:= "";  
    if (@startChar !="-" OR @startChar =null) then 
        WHILE (@endloop = "no") DO                  
            set @newchar :=(select connector from tableName where root = @startChar);       
            if(@newchar = '-') THEN
                set @endloop := "yes";
            else
                set @fullchar:= concat(@fullchar,"-",@newchar);
            end if;         
            set @startChar := @newchar;     
        END WHILE;
    end if;
        select @fullchar;
END
Posted: December 21, 2012, 4:27 pm

As you mentions your table contain around 9.5K of data. There is no logic to load data on login or scanning page.

Better to index your table and do a ajax call whenever required.

Best of Luck!!

Posted: December 20, 2012, 5:05 pm

Try this, i clobbed both-

SELECT s.pid AS 'ID', 
       CONCAT_WS(', ', p.lastname, p.firstname) AS 'Name', 
       CONCAT(s.date, ' ', s.time) AS Serviced, 
       p.institution AS Facility, 
       s.description AS 'description title', 
       ((SELECT COUNT(*) 
          FROM series se 
         WHERE se.studyid = s.id) 
          * 
       (SELECT COUNT(*) 
          FROM image i 
         WHERE i.seriesid = se.id) 
          ), 
       AS 'Number of Images' 
  FROM product p, 
          series se 
       JOIN 
          study s 
       ON s.pid = p.id 
GROUP BY s.id 
ORDER BY Serviced DESC
Posted: December 20, 2012, 5:01 pm

1) I can use 1st as the days and can store along with month and year.

This option is better as if there is any calculation or sorting need to be done, it will be useful and handy.

2) Instead of using date I can use varchar datatype and can only store month and year in it.

3) I can store the two as two separate columns as integers. i.e. for month and year.

For above two option are fine as it will take less space as compare to date or timestamp. But you can do calucation or orderby with this. For calculation you need to convert it date by "str_to_date" function

I hope this will help you in some way.

Posted: December 20, 2012, 10:59 am

Try this--

var st = "Monday, 9 Jan 2012 12:59:05";
var dt = new Date(st);
var m_names = new Array("Sun", "Mon", "Tue","Wed", "Thu","Fri", "Sat");
var dayInNum =dt.getDay();
var desireDate = m_names[dayInNum] + ","+ dt.getHours() +":"+ dt.getMinutes();
alert(desireDate);
Posted: December 13, 2012, 11:30 am