Data type not defined in PHP

Asked

Viewed 112 times

1

Thinking of a banking system.

If I have a $balance variable; I can play a string within that variable in PHP.

I wonder how to solve this problem in php.

and what is the advantage of php having dynamic variable type.

  • As far as I know (I worked with PHP from mid-2005 to 2012, then I had little time, I don’t know what’s new, but as for this I think nothing has changed) it is not possible to solve the "problem" because this is not a "problem" but expected behavior of the language, if you really need this type of validation I believe you will have to choose another language

  • how do people validate forms using php? uses a java script something like? because if not, it makes no sense (for me).

  • 1

    @Nicolasguilherme did not understand very well what you want, could be more specific? You want to know if a variable is numerical?

  • In client-side you do the validation by Javascript, but you also have to do the validation in PHP on the server-side and in both JS and PHP the data types are dynamic and this does not prevent the validation. If a variable can only contain numbers for example just cast a value or use PHP’s intval function

  • 1

    Advantage for banks, none. Disadvantages, none. Just knowing how to use it, I believe you’re having this difficulty because you used some ORM with a strongly typed language, but PHP doesn’t work natively like this, yet there are PHP frameworks that use ORM, like Laravel, Cakephp, or independent Orms like Propel and Doctrine. Control of their data types is usually detected automatically or configured by Migrations or a structured xml for them.

  • @cat my question is the following, if I am asking the user to enter the value of $serve; , serve is usually the correct float type? I want to restrict in php the type of data, if I simply declare the variable $serve and ask the user to enter data, he for putting what he wants inside this variable. Guilhermenascimento am beginner in programming, vim da linguagem JAVA (strongly typed). I’m studying the syntax of the PHP language, and it seems to be quite complex.

  • In JSP if I’m not mistaken n would need all this, because you already define the type of variable in the statement, I may be talking nonsense because I’m beginner, but until then, that’s what I know.

  • @Nicolasguilherme yes, but it’s not even JSP, it was Java, and it had no relation to the bank, it’s that API for the bank that was taking advantage of that. The syntax is simple, the problem is what you said, the variables are dynamic.

  • @Guilhermenascimento do not understand anything of ORM/API, do not know how they work yet, do not know the relationship with the bank you mean, unfortunately do not know about API Framework ORM etc, I am striving to learn the basis of programming, then study about the rest. But thanks for the clarification,

  • @Nicolasguilherme which ORM system used in Java? The problem is that each ORM in PHP works in a way, there is no right pattern, each has its own (although all are vaguely similar)

  • Answering the question of how the validation is made, this is the responsibility of the programmer (in case you) make the appropriate validations, if you only wait numbers, you must validate if the user only gave number, understand ? Using cast’s, native functions and even regular expressions (Regex) to validate and verify that what was reported is what was expected (How many Guilhermes, until I got confused kkk)

  • 2

    From what I understand, are you wanting to have static typing in a dynamic language? It’s not the way, although there are people who try to gambit. Either it works the way PHP works, or it uses another language. Detail: any data that the user sends via POST or GET arrives on the server as a string. From now on it’s up to you to validate and convert to another type if necessary.

  • 2

    And first of all, whether in Java or PHP, if you’re using float for $serve and $balance, you need to learn more basic things than type enforce. You need to know how to choose the correct type. Float for monetary values (or anything else that is exact value) is a serious defect in the code.

  • @Bacco which type would be used for monetary values? on the line below serve, which type would I put? I want to withdraw $11.50

  • 2

    @Nicolasguilherme or uses ( cents * 100 ) and stores in INT, or if the language has, some type specific to currency (decimal, money). Float never. Float is not an exact value. Roughly speaking, a float 5 + 5 can be 9.99997 instead of 10, which is a disaster for monetary operations. See more here: http://answall.com/questions/5746/70 - regardless of language, the reason is the same.

Show 10 more comments

1 answer

4


PHP is dynamic, but even if it wasn’t, it doesn’t really define what will enter the database.

In PHP it is possible to control the input data, outside that the data coming from the database has the type of the value "approximated" to the same of the database (except some that turn string, for example BIGINT and DECIMAL), or when PHP is 32bit and mysql 64bit (which affects some "limits"), this may depend on the API you use (mysqli or Pdo), I’m not sure.

For example if you do this by reading data:

<?php
//Conecta
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");

//Verifica se houve erros
if ($mysqli->connect_errno) {
    printf("Connect failed: %s\n", $mysqli->connect_error);
    exit;
}

//Query
$query = "SELECT id, nome, preco FROM Tabela LIMIT 1";

//Executa query
if ($result = $mysqli->query($query)) {

    /* Pega os dados */
    while ($row = $result->fetch_assoc())
    {
        //Exibe na tela, semelhante ao Symtem.out.println
        var_dump($row);
    }

    /* limpa resultados */
    $result->free();
}

/* fecha conexão */
$mysqli->close();

It returns something like this:

array(3) {
  ["id"]=> int(1)
  ["nome"]=> string(8) "carrinho"
  ["preco"]=> string(6) "100.02"
}
  • id is INT and returned a type int
  • nome is VARCHAR and returned string
  • preco is DECIMAL and returned string

In the case probably DECIMAL turns into string because it turned float could lose the accuracy of the data, which would be a big headache

Note that even without typing the value is of a specific type in case the ID is still INT (as said I’m not sure of the situation for different processors and Apis)

However it is possible to pass data to query in a way that checks the input data:

<?php
$stmt = $mysqli->prepare("INSERT INTO Tabela VALUES (?, ?, ?, ?)");
$stmt->bind_param('isd', $id, $nome, $valor);

$id    = 2;
$nome  = 'Boneca';
$valor = 11.2;

/* execute prepared statement */
$stmt->execute();

printf("%d linhas inseridas\n", $stmt->affected_rows);

/* close statement and connection */
$stmt->close();

/* close connection */
$mysqli->close();

Behold:

  • i corresponds to a type variable int
  • d corresponds to a type variable double
  • s corresponds to a type variable string
  • b corresponds to a variable that contains data for a blob and sends in packets

Although when it comes to DECIMAL, it would be better to pass string even.

!!! I recommend you read this: Best kind of data to work with money? !!!

Concluding

mysql itself in a way makes the "CAST" when working a column of a specific type, this is independent of any language, so whether the language is dynamic or not is irrelevant in some way at the end.

Popular orms and the like

This is just an addendum, there are several Orms in PHP, like Propel, Doctrine and frameworks that have their own ORM systems, for example the Laravel, him through the Migrations can control the types of column values

Browser other questions tagged

You are not signed in. Login or sign up in order to post.