Home > Shortcodes > [sabai-discuss-answers]

[sabai-discuss-answers]

Shortcode: [sabai-discuss-answers]

283 votes
In reply to: datetime vs timestamp?

Timestamps in MySQL generally used to track changes to records, and are updated every time the record is changed. If you want to store a specific value you should use a datetime field.

If you meant that you want to decide between using a UNIX timestamp or a native MySQL datetime field, go with the native format. You can do calculations within MySQL that way
("SELECT DATE_ADD(my_datetime, INTERVAL 1 DAY)") and it is simple to change the format of the value to a UNIX timestamp ("SELECT UNIX_TIMESTAMP(my_datetime)") when you query the record if you want to operate on it with PHP.

NOTE: This answer was originally posted at StackOverflow.com by blivet

  • Pamela answered 8 years ago
  • last active 6 years ago
226 votes

From the docs:

PHP follows Perl’s convention when dealing with arithmetic operations on character variables and not C’s.

For example, in Perl ‘Z’+1 turns into ‘AA’, while in C ‘Z’+1 turns into ‘[‘ ( ord(‘Z’) == 90, ord(‘[‘) == 91 ).

Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.

NOTE: This answer was originally posted at StackOverflow.com by CMS

  • Wayne answered 7 years ago
100 votes
In reply to: datetime vs timestamp?

I always use DATETIME fields for anything other than row metadata (date created or modified).

As mentioned in the MySQL documentation:

The DATETIME type is used when you need values that contain both date and time information. MySQL retrieves and displays DATETIME values in ‘YYYY-MM-DD HH:MM:SS’ format. The supported range is ‘1000-01-01 00:00:00’ to ‘9999-12-31 23:59:59’.

The TIMESTAMP data type has a range of ‘1970-01-01 00:00:01’ UTC to ‘2038-01-09 03:14:07’ UTC. It has varying properties, depending on the MySQL version and the SQL mode the server is running in.

You’re quite likely to hit the lower limit on TIMESTAMPs in general use — e.g. storing birthdate.

NOTE: This answer was originally posted at StackOverflow.com by scronide

  • Christine answered 8 years ago
  • last active 5 years ago
78 votes

Incrementing / Decrementing Operators

++ increment operator

-- decrement operator

Example    Name              Effect
---------------------------------------------------------------------
++$a       Pre-increment     Increments $a by one, then returns $a.
$a++       Post-increment    Returns $a, then increments $a by one.
--$a       Pre-decrement     Decrements $a by one, then returns $a.
$a--       Post-decrement    Returns $a, then decrements $a by one.

These can go before or after the variable. Putting this operator before the variable is slightly faster.

If put before the variable, the increment / decrement operation is done to the variable first then the result is returned. If put after the variable, the variable is first returned, then the increment / decrement operation is done.

For example:

$apples = 10;
for ($i = 0; $i < 10; ++$i)
{
    echo 'I have ' . $apples-- . " apples. I just ate one.\n";
}

Live example

In the case above ++$i is used, since it is faster. $i++ would have the same results.

However, you must use $apples--, since first you want to display the current number of apples, and then you want to subtract one from it.

You can also increment letters in PHP:

$i = "a";
while ($i < "c")
{
    echo $i++;
}

Once z is reached aa is next, and so on.

Note that character variables can be incremented but not decremented and even so only plain ASCII characters (a-z and A-Z) are supported.


Stack Overflow Posts:

NOTE: This answer was originally posted at StackOverflow.com by Peter Ajtai

  • Joe answered 7 years ago
  • last active 5 years ago
78 votes

Because once ‘z’ is reached (and this is a valid result within your range, the $i++ increments it to the next value in sequence), the next value will be ‘aa’; and alphabetically, ‘aa’ is < ‘z’, so the comparison is never met

for ($i = 'a'; $i != 'aa'; $i++) 
    echo "$i\n"; 

NOTE: This answer was originally posted at StackOverflow.com by Mark Baker

  • Amy answered 7 years ago
58 votes

Others answers explain the observed behavior of the posted code. Here is one way to do what you want (and it’s cleaner code, IMO):

foreach (range('a', 'z') as $i)
    echo "$i\n";

In response to ShreevatsaR’s comment/question about the range function: Yes, it produces the “right endpoint”, i.e. the values passed to the function are in the range. To illustrate, the output I got was:

a
b
c
d
e
f
g
h
i
j
k
l
m
n
o
p
q
r
s
t
u
v
w
x
y
z

NOTE: This answer was originally posted at StackOverflow.com by GreenMatt

  • Jimmy answered 7 years ago
  • last active 7 years ago
49 votes
In reply to: datetime vs timestamp?

The main difference is that DATETIME is constant while TIMESTAMP is effected by the time_zone setting.

So it only matters when you have – or may in the future have – synchronized clusters across time zones.

In simpler words: If I have a database in Australia, and take a dump of that database to synchronize/populate a database in America, then the TIMESTAMP would update to reflect the real time of the event in the new time zone, while DATETIME would still reflect the time of the event in the au time zone.

A great example of DATETIME being used where TIMESTAMP should have been used is in Facebook, where their servers are never quite sure what time stuff happened across time zones.

Once I was having a conversation in which the time said I was replying to messages before the message was actually sent.

This of course could also have been caused by bad time zone translation in the messaging software if the times were being posted rather than synchronized.

NOTE: This answer was originally posted at StackOverflow.com by ekerner

  • Rhonda answered 7 years ago
  • last active 6 years ago
47 votes
In reply to: PHP: self vs. $this

$this-> is used to refer to a specific instance of a class’s variables (member variables) or methods.

Example: 
$derek = new Person();

$derek is now a specific instance of Person.
Every Person has a first_name and a last_name, but $derek has a specific first_name and last_name (Derek Martin). Inside the $derek instance, we can refer to those as $this->first_name and $this->last_name

ClassName:: is used to refer to that type of class, and its static variables, static methods. If it helps, you can mentally replace the word “static” with “shared”. Because they are shared, they cannot refer to $this, which refers to a specific instance (not shared). Static Variables (i.e. static $db_connection) can be shared among all instances of a type of object. For example, all database objects share a single connection (static $connection).

Static Variables Example:
Pretend we have a database class with a single member variable: static $num_connections;
Now, put this in the constructor:

function __construct()
{
    if(!isset $num_connections || $num_connections==null)
    {
        $num_connections=0;
    }
    else
    {
        $num_connections++;
    }
}

Just as objects have constructors, they also have destructors, which are executed when the object dies or is unset:

function __destruct()
{
    $num_connections--;
}

Every time we create a new instance, it will increase our connection counter by one. Every time we destroy or stop using an instance, it will decrease the connection counter by one. In this way, we can monitor the number of instances of the database object we have in use with:

echo DB::num_connections;

Because $num_connections is static (shared), it will reflect the total number of active database objects. You may have seen this technique used to share database connections among all instances of a database class. This is done because creating the database connection takes a long time, so it’s best to create just one, and share it (this is called a Singleton Pattern).

Static Methods (i.e. public static View::format_phone_number($digits)) can be used WITHOUT first instantiating one of those objects (i.e. They do not internally refer to $this).

Static Method Example:

public static function prettyName($first_name, $last_name)
{
    echo ucfirst($first_name).' '.ucfirst($last_name);
}

echo Person::prettyName($derek->first_name, $derek->last_name);

As you can see, public static function prettyName knows nothing about the object. It’s just working with the parameters you pass in, like a normal function that’s not part of an object. Why bother, then, if we could just have it not as part of the object?

  1. First, attaching functions to objects helps you keep things organized, so you know where to find them.
  2. Second, it prevents naming conflicts. In a big project, you’re likely to have two developers create getName() functions. If one creates a ClassName1::getName(), and the other creates ClassName2::getName(), it’s no problem at all. No conflict. Yay static methods!

SELF::
If you are coding outside the object that has the static method you want to refer to, you must call it using the object’s name View::format_phone_number($phone_number);
If you are coding inside the object that has the static method you want to refer to, you can either use the object’s name View::format_phone_number($pn), OR you can use the self::format_phone_number($pn) shortcut

The same goes for static variables:
Example: View::templates_path versus self::templates_path

Inside the DB class, if we were referring to a static method of some other object, we would use the object’s name:
Example: Session::getUsersOnline();

But if the DB class wanted to refer to its own static variable, it would just say self:
Example: self::connection;

Hope that helps clear things up 🙂

NOTE: This answer was originally posted at StackOverflow.com by lo_fye

  • Deborah answered 9 years ago
  • last active 1 year ago
33 votes
In reply to: datetime vs timestamp?
mysql> show variables like '%time_zone%';
+------------------+---------------------+
| Variable_name    | Value               |
+------------------+---------------------+
| system_time_zone | India Standard Time |
| time_zone        | Asia/Calcutta       |
+------------------+---------------------+
2 rows in set (0.00 sec)

mysql> create table datedemo(
    -> mydatetime datetime,
    -> mytimestamp timestamp
    -> );
Query OK, 0 rows affected (0.05 sec)

mysql> insert into datedemo values ((now()),(now()));
Query OK, 1 row affected (0.02 sec)

mysql> select * from datedemo;
+---------------------+---------------------+
| mydatetime          | mytimestamp         |
+---------------------+---------------------+
| 2011-08-21 14:11:09 | 2011-08-21 14:11:09 |
+---------------------+---------------------+
1 row in set (0.00 sec)

mysql> set time_zone="america/new_york";
Query OK, 0 rows affected (0.00 sec)

mysql> select * from datedemo;
+---------------------+---------------------+
| mydatetime          | mytimestamp         |
+---------------------+---------------------+
| 2011-08-21 14:11:09 | 2011-08-21 04:41:09 |
+---------------------+---------------------+
1 row in set (0.00 sec)

The above examples shows that how TIMESTAMP date type changed the values after changing the time-zone to 'america/new_work' where DATETIMEis unchanged.

I’ve converted my answer into article so more people can find this useful.

http://www.tech-recipes.com/rx/22599/mysql-datetime-vs-timestamp-data-type/

NOTE: This answer was originally posted at StackOverflow.com by Viswanathan Iyer

  • Beverly answered 6 years ago
  • last active 5 years ago
31 votes
In reply to: datetime vs timestamp?

I make this decision on a semantic base.

I use a timestamp when I need to record a (more or less) fixed point in time. For example when a record was inserted into the database or when some user action took place.

I use a datetime field when the date/time can be set and changed arbitrarily. For example when a user can save later change appointments.

NOTE: This answer was originally posted at StackOverflow.com by unbeknown

  • Bonnie answered 8 years ago
  • last active 6 years ago
29 votes

As stated before none of the perm fixes work anymore. You need to change the perms accordingly AND put the following in your wp-config.php:

define('FS_METHOD', 'direct');

NOTE: This answer was originally posted at StackOverflow.com by Ryan Wiancko

  • Deborah answered 5 years ago
  • last active 5 years ago
27 votes
In reply to: Good PHP ORM Library?

I’ve been developing Pork.dbObject on my own. (A simple PHP ORM and Active Record implementation)
The main reason is that I find most ORMs too heavy.

The main thought of Pork.dbObejct is to be light-weight and simple to set up. No bunch of XML files, just one function call in the constructor to bind it, and an addRelation or addCustomRelation to define a relation to another dbObject.

Give it a look: Pork.dbObject

NOTE: This answer was originally posted at StackOverflow.com by SchizoDuckie

  • Tracy answered 9 years ago
  • last active 5 years ago
24 votes

You can not ethically store passwords for later plaintext retrieval. It’s as simple as that. Even Jon Skeet can not ethically store passwords for later plaintext retrieval. If your users can retrieve passwords in plain text somehow or other, then potentially so too can a hacker who finds a security vulnerability in your code. And that’s not just one user’s password being compromised, but all of them.

If your clients have a problem with that, tell them that storing passwords recoverably is against the law. Here in the UK at any rate, the Data Protection Act 1998 (in particular, Schedule 1, Part II, Paragraph 9) requires data controllers to use the appropriate technical measures to keep personal data secure, taking into account, among other things, the harm that might be caused if the data were compromised — which might be considerable for users who share passwords among sites. If they still have trouble grokking the fact that it’s a problem, point them to some real-world examples, such as this one.

The simplest way to allow users to recover a login is to e-mail them a one-time link that logs them in automatically and takes them straight to a page where they can choose a new password. Create a prototype and show it in action to them.

Here are a couple of blog posts I wrote on the subject:

NOTE: This answer was originally posted at StackOverflow.com by jammycakes

  • Stephen answered 7 years ago
  • last active 6 years ago
20 votes
In reply to: Good PHP ORM Library?

Try Doctrine2. It’s probably the most powerful ORM tool for PHP. I’m mentioning it separately from Doctrine 1, because it’s a completely different piece of software. It’s been rewritten from scratch, is still in beta phase, but it’s usable now and developed.

It’s a very complex ORM, but well designed. Lot of magic from original Doctrine 1 disappeared. It provides a complete solution, and you can write your own ORM on top of Doctrine2 or use just one of its layers.

NOTE: This answer was originally posted at StackOverflow.com by tomp

  • Chris answered 7 years ago
  • last active 5 years ago
13 votes

Prettify is the code colorizer that StackOverflow uses.

NOTE: This answer was originally posted at StackOverflow.com by Zach Johnson

  • Dawn answered 7 years ago
12 votes
In reply to: Good PHP ORM Library?

I just started with Kohana, and it seems the closest to Ruby on Rails without invoking all the complexity of multiple configuration files like with Propel.

NOTE: This answer was originally posted at StackOverflow.com by Zak

  • Rebecca answered 9 years ago
  • last active 6 years ago
11 votes
In reply to: datetime vs timestamp?

Depends on application, really.

Consider setting a timestamp by a user to a server in New York, for an appointment in Sanghai. Now when the user connects in Sanghai, he accesses the same appointment timestamp from a mirrored server in Tokyo. He will see the appointment in Tokyo time, offset from the original New York time.

So for values that represent user time like an appointment or a schedule, datetime is better. It allows the user to control the exact date and time desired, regardless of the server settings. The set time is the set time, not affected by the server’s time zone, the user’s time zone, or by changes in the way daylight savings time is calculated (yes it does change).

On the other hand, for values that represent system time like payment transactions, table modifications or logging, always use timestamps. The system will not be affected by moving the server to another time zone, or when comparing between servers in different timezones.

Timestamps are also lighter on the database and indexed faster.

NOTE: This answer was originally posted at StackOverflow.com by ianaré

  • Jay answered 7 years ago
11 votes

Refinery looks really simple but I don’t have an in depth comparison to wordpress. Looks like it has a lot less features but likely easier to maintain and extend upon. It’s pretty standard to write really crappy code in the Wordpress community.

NOTE: This answer was originally posted at StackOverflow.com by Tony

  • Anne answered 6 years ago
9 votes

Magic Quotes

The following text is taken from PHP.net

http://www.php.net/manual/en/security.magicquotes.why.php

There is no reason to use magic quotes because they are no longer a supported part of PHP. However, they did exist and did help a few beginners blissfully and unknowingly write better (more secure) code. But, when dealing with code that relies upon this behavior it’s better to update the code instead of turning magic quotes on. So why did this feature exist? Simple, to help prevent SQL Injection. Today developers are better aware of security and end up using database specific escaping mechanisms and/or prepared statements instead of relying upon features like magical quotes.

addslashes() vs mysql_real_escape_string()

The reason why you should use mysql_real_escape_string() is because it’s a “MySQL function” and is created especially for escaping user input before it’s executed in a mysql query, while addslashes() is a “PHP function”. That probably sounded a little weird, but there’s one important difference between the two and it has to do with the use of single- and multi-byte characters. You can still inject databases protected by the addslashes function, but injecting databases protected by mysql_real_escape_string is far more difficult. You can read more about it HERE

Register Globals

The reason why you should NOT use register_globals is because variables become accessible to everyone, which means that in the following example you would be able to set $access to true if it hasn’t been initialized before

<?php

if (isAuthenticated()) { $access = true; }

if ($access == true) {
  include(controlpanel.php);
}

?>

The above code would give you sh#! loads of problems, but if we initialize the variable first by adding the following to the top of the page

$access = false;

…we should be fine even if we have register_globals ON

So, if the Wordpress team have initialized all variables (which they probably have) then you don’t have to worry about the use of globals.

Conclusion

It’s definitely bad practice using any of those 3 functions/features and I would never do it myself. Are you sure you’re working with the latest version of Wordpress? Like someone commented, if you are using the latest version it’s because of laziness or worse it’s still in there. I’ld never use Wordpress for anything other than blogs that doesn’t require much security..

NOTE: This answer was originally posted at StackOverflow.com by Tom

  • Ann answered 5 years ago
  • last active 5 years ago
8 votes

Also you can use http://tohtml.com/html/ or GeSHi

NOTE: This answer was originally posted at StackOverflow.com by voodoo555

  • Jay answered 7 years ago
Showing 1 - 20 of 944 results