Php my admin data types

Типы данных в MySQL (сжатый справочник для PHP программиста)

Данный материал создан специально для программистов, которые быстро смогут определиться какой тип данных лучше выбрать для хранения значений в БД MySQL.

Для затравки, интересная цитата из мануала по MySQL:
«Максимальный размер записи в MyISAM составляет 65534 байтов. Каждый BLOB или TEXT-столбец засчитывается здесь как 5-9 байтов.» — как это трактовать однозначно не понятно. НО ясно что много-примного столбцов в таблицу на засунешь. «Извращенистые программисты» — будьте аккуратны (66000 столбцов вы точно создать не сможете).

UPD: Если найдете ошибку, или я что-то где-то утаил — отпишитесь в комментах, с удовольствием добавлю.

UPD1 В первую очередь (и самый лучший вариант для новичков) прочитать ОФИЦИАЛЬНЫЙ МАНУАЛ dev.mysql.com/doc/refman/5.0/en/data-types.html (спасибо Psyh за прямую ссылку), а здесь вырезка для META обработчиков данных (как в лице программистов так и в лице машинной обработки).

UPD2 В принципе, все что написано ниже, можно прочитать по адресу www.mysql.ru/docs/man/Column_types.html (за ссылку «русского перевода», спасибо artuska).

UPD3 Еще одну неплохую ссылку предоставил 4all: newcontinent.ru/h/mysqlc (материал на русском)

UPD4 Цитата из комментов от egorF:
# 14«Как главный редактор русскоязычного перевода доки на MySQL, я рекомендую в него не заглядывать — он уже сказочно морально устарел.»

Следующий массив вполне понятен PHP программистам.
Да и вообще, любые уважающие себя программисты это поймут.

Например:
‘int’=>Array(‘byte’=>4, ‘min’=>-2147483648, ‘max’=>2147483647, ‘umin’=>0, ‘umax’=>4294967295),

Трактуется следующим образом:
Тип поля INT использует 4 байта для хранения значения. Минимально значение -2147483648, максимальное 2147483647. Беззнаковый INT (unsigned) хранит значения от 0 до 4294967295.

Используется так:
Мне надо сохранить в поле максимальное числовое значение 234 259 000 000 000.
INT — для этого не подходит. Смотрим другие типы и находим, что BIGINT вполне подойдет.

$MYSQL_TYPES=Array(
// INTEGER
// byte — кол-во байт на хранение,
// max/min — предельные значения,
// umax/umin — беззнаковые предельные значения
‘int’ =>Array( ‘byte’ =>4, ‘min’ =>-2147483648, ‘max’ =>2147483647, ‘umin’ =>0, ‘umax’ =>4294967295),
‘bigint’ =>Array( ‘byte’ =>8, ‘min’ =>-9223372036854775808, ‘max’ =>9223372036854775807, ‘umin’ =>0, ‘umax’ =>18446744073709551615),
‘tinyint’ =>Array( ‘byte’ =>1, ‘min’ =>-128, ‘max’ =>127, ‘umin’ =>0, ‘umax’ =>255),
‘smallint’ =>Array( ‘byte’ =>2, ‘min’ =>-32768, ‘max’ =>32767, ‘umin’ =>0, ‘umax’ =>65535),
‘mediumint’ =>Array( ‘byte’ =>3, ‘min’ =>-8388608, ‘max’ =>8388607, ‘umin’ =>0, ‘umax’ =>16777215),

// DECIMAL DECIMAL(M,D) m — кол-во цифр (max 65 цифр), d — сколько из них могут быть после запятой
// min_byte/max_byte — краевые значения размера поля в байтах,
// byte_formula — формула вычисления размерности
// length — максимальное кол-во цифр
‘decimal’ =>Array( ‘min_byte’ =>2, ‘max_byte’ =>67, ‘byte_formula’ => ‘(D==0?(M+1):(M+2)’ , ‘length’ =>65),
‘dec’ =>Array( ‘min_byte’ =>2, ‘max_byte’ =>67, ‘byte_formula’ => ‘D==0?(M+1):(M+2)’ , ‘length’ =>65),
‘numeric’ =>Array( ‘min_byte’ =>2, ‘max_byte’ =>67, ‘byte_formula’ => ‘D==0?(M+1):(M+2)’ , ‘length’ =>65),

// FLOAT DOUBLE
// Внимание! Не храните денежные значения в этих полях. Деньги надо хранить — в DECIMAL
// у FLOAT ТОЧНОСТЬ ТОЛЬКО 7 ЦИФР. (все остальные цифры «смазываются»)
// у DOUBLE ТОЧНОСТЬ ТОЛЬКО 15 ЦИФР. (все остальные цифры «смазываются»)
// byte — кол-во байт для хранения поля (по-умолчанию)
// max_byte — максимальное кол-во байт для хранения
// negative_min/negative_max — минмаксы для отрицательных чисел
// positive_min/positive_max — минмаксы для положительных чисел
‘float’ =>Array( ‘byte’ =>4, ‘max_byte’ =>8, ‘negative_min’ =>-3.402823466E+38, ‘negative_max’ =>-1.175494351E-38, ‘positive_min’ =>1.175494351E-38, ‘positive_max’ =>3.402823466E+38),
‘double’ =>Array( ‘byte’ =>8, ‘negative_min’ =>-1.7976931348623157E+308, ‘negative_max’ =>-2.2250738585072014E-308, ‘positive_min’ =>2.2250738585072014E-308, ‘positive_max’ =>1.7976931348623157E+308),

Читайте также:  Android java path class

// BOOLEAN
// сами все поймете
‘bool’ =>Array( ‘byte’ =>1, ‘true’ =>1, ‘false’ =>0),
‘boolean’ =>Array( ‘byte’ =>1, ‘true’ =>1, ‘false’ =>0),

// VARCHAR
// byte — кол-во байт отведенных для хранения (можно задать меньше)
// min_byte — минимальное кол-во байт в которых может храниться поле (если длина равна 1)
// В MYSQL 5.0.3 и выше, VARCHAR может быть до 65,535 символов.
// length — максимальная длина символов в поле
‘varchar’ =>Array( ‘byte’ =>256, ‘min_byte’ =>2, ‘length’ =>255),
‘char’ =>Array( ‘byte’ =>256, ‘min_byte’ =>2, ‘length’ =>255),

// TEXT
// byte — кол-во байт для хранения поля
// min_byte — минимальное кол-во байт для хранения одного символа (если длина поля равна 1)
// length — максимальное количество символов в поле
‘tinytext’ =>Array( ‘byte’ =>256, ‘min_byte’ =>2, ‘length’ =>255),
‘text’ =>Array( ‘byte’ =>65537, ‘min_byte’ =>3, ‘length’ =>65535),
‘mediumtext’ =>Array( ‘byte’ =>16777218, ‘min_byte’ =>4, ‘length’ =>16777215),
‘longtext’ =>Array( ‘byte’ =>4294967300, ‘min_byte’ =>5, ‘length’ =>4294967296),
‘tinyblob’ =>Array( ‘byte’ =>256, ‘min_byte’ =>2, ‘length’ =>255),
‘blob’ =>Array( ‘byte’ =>65537, ‘min_byte’ =>3, ‘length’ =>65535),
‘mediumblob’ =>Array( ‘byte’ =>16777219, ‘min_byte’ =>4, ‘length’ =>16777215),
‘longblob’ =>Array( ‘byte’ =>4294967300, ‘min_byte’ =>5, ‘length’ =>4294967296),

// DATETIME
// byte — кол-во байт для хранения значения поля
// mask — стандартная маска ввода значения (есть куча других вариантов, о них читайте в мануале)
// min/max — минимальные максимальные значения дат которые сохраняют поля
‘datetime’ =>Array( ‘byte’ =>8, ‘mask’ => ‘YYYY-MM-DD HH:MM:SS’ , ‘min’ => ‘1000-01-01 00:00:00’ , ‘max’ => ‘9999-12-31 23:59:59’ ),
‘date’ =>Array( ‘byte’ =>3, ‘mask’ => ‘YYYY-MM-DD’ , ‘min’ => ‘1000-01-01’ , ‘max’ => ‘9999-12-31’ ),
‘time’ =>Array( ‘byte’ =>3, ‘min’ => ‘-838:59:59’ , ‘max’ => ‘838:59:59’ ),
‘year’ =>Array( ‘byte’ =>1, ‘min’ =>1901, ‘max’ =>2155),
‘timestamp’ =>Array( ‘byte’ =>4, ‘mask’ =>Array(14=> ‘YYYYMMDDHHMMSS’ ,12=> ‘YYMMDDHHMMSS’ ,10=> ‘YYMMDDHHMM’ ,8=> ‘YYYYMMDD’ ,6=> ‘YYMMDD’ ,4=> ‘YYMM’ ,2=> ‘YY’ ), ‘min’ =>1970, ‘max’ =>2036 ),

// ENUM
// byte — кол-во байт на хранение поля
// max_byte — максимальное кол-во байт, которое можно достигнуть при максимальном кол-ве элементов
// max_number_of_element — кол-во элементов, которое может содержать поле
‘enum’ =>Array( ‘byte’ =>1, ‘max_byte’ =>2, ‘max_number_of_element’ =>65535),
‘set’ =>Array( ‘byte’ =>1, ‘max_byte’ =>8, ‘max_number_of_element’ =>64)
); * This source code was highlighted with Source Code Highlighter .

Источник

PHP Data Types

Summary: in this tutorial, you will learn about PHP data types including scalar types, compound types, and special types.

Introduction to PHP data types

A type specifies the amount of memory that allocates to a value associated with it. A type also determines the operations that you can perform on it.

Читайте также:  Php завершить все сессии

PHP has ten primitive types including four scala types, four compound types, and two special types:

Scalar types

Compound types

Special types

Scalar types

A variable is a scalar when it holds a single value of the type integer, float, string, or boolean.

Integer

Integers are whole numbers defined in the set . The size of the integer depends on the platform where PHP runs.

The constant PHP_INT_SIZE specifies the size of the integer on a specific platform. PHP uses the int keyword to denote the integer type.

The following example illustrates some integers:

 $count = 0; $max = 1000; $page_size = 10;Code language: HTML, XML (xml)

Float

Floats are floating-point numbers, which are also known as floats, doubles, or real numbers.

PHP uses the IEEE 754 double format to represent floats. Like other programming languages, floats have limited precision.

PHP uses the float keyword to represent the floating-point numbers. The following example illustrates the floating-point numbers in PHP:

 $price = 10.25; $tax = 0.08;Code language: HTML, XML (xml)

Boolean

Boolean represents a truth value that can be either true or false . PHP uses the bool keyword to represent the Boolean type.

The bool type has two values true and false . Since keywords are case-insensitive, you can use true , True , TRUE , false , False , and False to indicate boolean values.

The following example shows how to assign Boolean values to variables:

 $is_admin = true; $is_user_logged_in = false;Code language: HTML, XML (xml)

When you use the values of other types in the boolean context, such as if-else and switch-case statements, PHP converts them to the boolean values.

PHP treats the following values as false :

  • The false keyword.
  • The integer 0 and -0 (zero).
  • The floats 0.0 and -0.0 (zero).
  • The empty string ( «» , » ) and the string “0”.
  • The empty array ( array() or [] ).
  • The null .
  • The SimpleXML objects created from attributeless empty elements.

The values that are not one of these falsy values above are true .

String

A string is a sequence of characters surrounded by single quotes (‘) or double quotes (“). For example:

 $str = 'PHP scalar type'; $message = "PHP data types";Code language: HTML, XML (xml)

Compound types

Compound data includes the values that contain more than one value. PHP has two compound types including array and object.

Array

An array is an ordered map that associates keys with values. For example, you can define a list of items in a shopping cart like this:

 $carts = [ 'laptop', 'mouse', 'keyboard' ];Code language: HTML, XML (xml)

The $carts array contains three string values. It maps the index 0 , 1 , and 2 to the values ‘laptop’ , ‘mouse’ , and ‘keyboard’ . The $carts is called an indexed array because it uses numeric indexes as keys.

To access a value in an array, you use the square brackets:

 echo $carts[0]; // 'laptop' echo $carts[1]; // 'mouse' echo $carts[2]; // 'keyboard'Code language: HTML, XML (xml)

Besides numeric indexes, you can use strings as keys for the array elements. These arrays are known as associative arrays. For example:

 $prices = [ 'laptop' => 1000, 'mouse' => 50, 'keyboard' => 120 ];Code language: HTML, XML (xml)

To access an element in an associative array, you specify the key in the square brackets. For example:

 echo $prices['laptop']; // 1000 echo $prices['mouse']; // 50 echo $prices['keyboard']; // 120Code language: HTML, XML (xml)

Object

An object is an instance of a class. It’s a central concept in object-oriented programming.

An object has properties. For example, a person object may have the first name, last name, and age properties.

An object also has behaviors, which are known as methods. For example, a person object can have a method called getFullName() that returns the full name.

To learn more about objects, check out the object tutorial.

Special types

PHP has two special types: null and resource

Null

The null type has one value called null that represents a variable with no value.

Resource

The resource type holds a reference to an external resource, e.g. a filehandle or a database connection.

Summary

  • PHP has four scalar types, four compound types, and two special types.
  • Scale types: integer, float, string, and boolean.
  • Compound types: array and object.
  • Special types: null and resource.

Источник

What are the Different Data Types in PHP and How to Use Them?

Different Data Types

The values assigned to a PHP variable will be Different Data Types including numeric types and simple string to more complex data types as objects and arrays.
PHP data types define the type of data a variable can store, PHP supports a total of eight different types of data types Integer, Float, Array, String, Booleans, Object, resource, and NULL.
these PHP allows eight different types of data types are used to construct variable. let’s discuss all data types in detail, the first five data types are called simple data types and the last three data types are called the compound data types, or all eight different data types that can be categorized into three types

Note: strings are classified as alphanumeric characters.
Integers are classified as Whole Numbers.
Floating points are classified as Numbers with decimal Points.
Boolean is classified as True or false values.
Integer included whole numbers like as e.g. -2, -5, 0, 9, 32.

PHP Different Data Types: Classification Data Types Table

Scalar Types Compound Types Special Types
The Scalar data types hold only a single value. There are 4 types of scalar data types in PHP.
1. boolean
2. integer
3. float
4. string
The Compound Data Types hold only a single value. There are 2 types of Compound data Types in PHP.
1. array
2. object
There are 2 types of Special data Types in PHP.
1. resource
2. NULL

Источник

Оцените статью