Php mysql variable types

Check PHP variable type against a MYSQL data type

It’s also worth mentioning that values have types , not variables, in PHP. If you’re looking for specific data types and how to identify them, then you might want to edit your question to facilitate more complete answers.

Check PHP variable type against a MYSQL data type

Just wondering, if is there any class, function or ideia on how to validate a specific value/variable against a mysql data type.

We’ve got in PHP the is_int() is_string() is_float() etc etc. But we do not have them all. Or do we? Any Cheat sheet? Any thoughts?

EDIT: The point basically is:

  • Go trought a array of values (comming from a CSV for instance).
  • I know what table, and have all the column information (data type s well) (with adodb).
  • Just check if each value fits in a specific column.

If the data is coming from a CSV file, you have to remember that all the values are going to be strings (even numeric strings still have a string type).

So you can’t use is_int() / is_float() /etc., because that only tells you about the type or the variable. You could use is_numeric() to check the value, but this will allow for things like exponential notation like «+0123.45e6». Sometimes ctype_digit() can be useful for testing integers for this reason, since it will only allow the numbers 0-9 to be present in a string for it to return true.

Читайте также:  Python tkinter вывод результата

Regular expressions can also be used to identify pattern-based data types, but you do have to watch for performance overhead when dealing with large data sets. It’s almost always advisable from a performance perspective to use the preg_ family of functions instead of the ereg functions.

If you’re validating things like ENUM or SET types, you’ll probably need to make an array containing legal values (or extract these with a query) and then check the value against them with in_array() .

For CHAR/VARCHAR fields, you could parse the column definition and then check whether the length of the value falls within the constraints.

If the NULL type is allowed on any of your columns, you’d also need to check against this (and probably map empty values or the string «NULL» to an actual NULL value).

If you’re looking to actually escape these values properly, look into using prepared statements and the PDO (PHP Data Objects) extension. This allows MySQL to properly escape the data based on type. (You can also use prepared statements with MySQLi.)

If you’re looking for specific data types and how to identify them, then you might want to edit your question to facilitate more complete answers.

Best way to test for a variable’s existence in PHP; isset(), Determine whether a variable is set. If a variable has been unset with unset (), it will no longer be set. isset () will return FALSE if testing a variable that has been set to NULL. Also note that a NULL byte («\0») is not equivalent to …

How can I check if a variable type is DateTime

How can I check if a variable is a datetime type on php, please? I’ve tried this, but it seems doesn’t work.

public function setRegistrationDate ($registrationDate) < if (!is_date($registrationDate, "dd/mm/yyyy hh:mm:ss")) < trigger_error('registrationDate != DateTime', E_USER_WARNING); return; >$this->_registrationDate = $registrationDate; > 

I think this way is more simple:

This expression is true if $myVar is a PHP DateTime object.

Since PHP 5, this can be further simplified to:

if ($myVar instanceof DateTime) . 
function validateDate($date, $format = 'Y-m-d H:i:s') < $d = DateTime::createFromFormat($format, $date); return $d && $d->format($format) == $date; > 

The simplest answer is : to check with strtotime() function

$date = strtotime($datevariable); 

If it’s valid date, it will return timestamp , otherwise returns FALSE .

I would use the following method:

public function setRegistrationDate ($registrationDate) < if(!($registrationDate instanceof DateTime)) < $registrationDate = date_create_from_format("dd/mm/yyyy hh:mm:ss", $registrationDate) >if(!($registrationDate instanceof DateTime)) < trigger_error('registrationDate is not a valid date', E_USER_WARNING); return false; >$this->_registrationDate = $registrationDate; return true > 

How to check the Datatype in php which is, The function gettype () should only be used to output the datatype of a variable. Testing for special datatypes – with this function – is not recommended, because the returns may change at some point.

How to Check for a Specific Type of Object in PHP

I have a method which accepts a PDO object as an argument, to allow the user to use an existing connection rather then the method to open a new one, and save resources:

public static function databaseConnect($pdo = null)  

I am aware of is_object() to check if the argument is an object, but I want to check if $pdo is a PDO object, and not just an object.

Because the user can easily enter (by mistake?) a different kind of object, a mysqli or such, and the entire script will break apart.

In short: How can I check a variable for a specific type of object?

Be aware though, you can't negate like !instanceof , so you'd instead do:

Also, looking over your question, you can use object type-hinting, which helps enforce requirements, as well as simplify your check logic:

function connect(PDO $pdo = null) < if (null !== $pdo) < // it's PDO since it can only be // NULL or a PDO object (or a sub-type of PDO) >> connect(new SomeClass()); // fatal error, if SomeClass doesn't extend PDO 

Typed arguments can be required or optional:

// required, only PDO (and sub-types) are valid function connect(PDO $pdo) < >// optional, only PDO (and sub-types) and // NULL (can be omitted) are valid function connect(PDO $pdo = null)

Untyped arguments allow for flexibility through explicit conditions:

// accepts any argument, checks for PDO in body function connect($pdo) < if ($pdo instanceof PDO) < // . >> // accepts any argument, checks for non-PDO in body function connect($pdo) < if (!($pdo instanceof PDO)) < // . >> // accepts any argument, checks for method existance function connect($pdo) < if (method_exists($pdo, 'query')) < // . >> 

As for the latter ( using method_exists ), I'm a bit mixed in my opinion. People coming from Ruby would find it familiar to respond_to? , for better or for worse. I'd personally write an interface and perform a normal type-hint against that:

interface QueryableInterface < function query(); >class MyPDO extends PDO implements QueryableInterface < >function connect(QueryableInterface $queryable)

However, that's not always feasible; in this example, PDO objects are not valid parameters as the base type doesn't implement QueryableInterface .

It's also worth mentioning that values have types , not variables, in PHP. This is important because null will fail an instanceof check.

$object = new Object(); $object = null; if ($object instanceof Object) < // never run because $object is simply null >

The value loses it's type when it becomes null , a lack of type.

 bool is_a ( object $object , string $class_name ) 

This will work for child classes too.

EDIT: Or you could use type hinting:

public static function databaseConnect(PDO $pdo = null)  

As pointed out in other answers, instanceof , get_class , and is_a are probably what you're looking for.

However, rather than coding in a lot of guards that test for type, some developers find it more productive (and easier to read) to just let the runtime handle the enforcement, particularly when you're talking about calls other programmers will be making (when a programmer makes a mistake, app-breaking loud complaints are arguably a good thing).

If you really need to not have the script fall apart when a programmer uses your method incorrectly, wrap the relevant section of code (in this case, probably the inside of databaseConnect) in a try block, maybe use set_error_handler to throw exceptions on script errors, and then set up one or more catch blocks which indicated what to do when an exception condition happens.

I think you can use instanceof something like:

if ($pdo instanceof YOUR_PDO_OBJECT_INSTANCE) < // it is. >

How to check if a variable has data in laravel blade, is_null Finds whether the given variable is NULL or not. but in our case we need to check whether the value in empty or not for this you can use either isset () or empty () function both work same in your case. while isset — Determine if a variable is set and is not NULL and. empty — Determine whether a variable is …

Источник

Variables and Data Types

Variables are used to store different kinds of data (or values). These values can be numbers, text, or much more complex data. PHP has eight basic (or primitive ) types of variables.

PHP Data types

  • Boolean - Logical TRUE or FALSE
  • Integer - Whole numbers (e.g., 7, 78, –132, 87348)
  • Float (double) - Numbers with decimal notations (e.g., 78.23, -3.25 or 348.125)
  • String - Characters, letters, or numbers, defined within double or single quotes (e.g., "Hy there" or '123AvR')
  • Array - A variable that can hold multiple, separate pieces of values. It's like a list of values, each value being a string or a number or even another array.
  • Object - The instance of a PHP class. The basics for class definitions and object-oriented programming.
  • Resource - Stores a reference to functions, databases, files, or other resources outside of PHP
  • NULL - Defines a variable with no value; the variable exists, but contains nothing (not an empty string, not the value 0, nothing)

Using variables

  • Variable names have to begin with a dollar sign ($). For example, $name
  • After the dollar sign ($), the next character in the name must be a letter or an underscore; after this, the remainder of the variable name can be any combination of letters, numbers, and underscores. For example, $var_name1
  • The name of a variable is case-sensitive, so $varname is a different variable than $varName
  • The variable named $this is reserved for use in Object Oriented PHP, so it can't be used elsewhere

Assign by value

The typical way to do assignments is to define by value. Value can be a number, a string (or any data type), or another variable previously defined.

- The values of these variables remains intact until it is reassigned or the script has completed.

• If you assign another value to an existing variable, the new value will overwrite the old one.

• Variables can be printed within double quotation marks, but not within simple quotation marks. If you add a variable inside simple quotation marks, will display its name (not its value).

'; // Hy Marius echo 'Hy $name'; // Hy $name ?>

Assign value by reference

The reference approach allows the content of a variable to affect the value of another variable (previously defined), or a function to affect a variable that is not part of that function (see the lesson: Passing variable to function by reference).
To define a variable by reference, simply add the ampersand (&) character before the dollar sign ($).

'. $var2; // marplonet.net // changing the value of $var2 will be transmitted to $var1 too $var2 = 'https://coursesweb.net'; echo '
'. $var1; // https://coursesweb.net ( because of the "by reference" ) ?>

- Once a variable is assigned by reference, it is tied to its referenced variable. If one of them changes, will transfer the same change to the other one. If you change the value of $var1 will change the value of $var2 too.
Because assigning values by reference can complicate the script, it's better to avoid this.

Dynamic variables

A dynamic variable is named using two dollar signs ($$) and is associated with a normal variable that has a similar name.
The value of an usual variable gives the name (without the dollar symbol) to a second variable.

A dynamic variable does not contain its own value. Instead, it contains the location where you can find the value, in other words, the name of another variable.
The expresions: $var_name = "good_people"; and $$var_name; make result a variable "$good_people", the value of "$$var_name" is the value of "$good_people".

- Dynamic variables, as those by reference can be confusing and it's better to avoid them.

Источник

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