Robert
Robert

Reputation: 10390

php mysql function for inserting records

I have this piece of code that I am studying but don't see the purpose of a certain line.

public function insertRecords($table, $data){
    //setup some variables for fields and values
    $fields = "";
    $values = "";

    //populate them
    foreach($data as $f => $v){
        $fields .= "`$f`,";
        $values .= (is_numeric($v) && (intval($v) == $v)) ? $v . "," : "'$v',";
    }

    //remove our trailing ,
    $fields = substr($fields, 0, -1);
    //remove our trailing ,
    $values = substr($values, 0, -1);

    $insert = "INSERT INTO $table ({$fields}) values({$values})";
    //echo $insert
    $this->executeQuery($insert);
    return true;
}

I don't see the purpose of:

intval($v) == $v))

In the ternary operator. What I understand is, if the integer value of $v is the same as $v do blah. Of course the integer value of $v is going to be equal to $v. It's the current value in the current iteration. Is my understanding incorrect?

I already know that if intval() doesn't return a integer it defaults to a string in the ternary operator.

Upvotes: 2

Views: 98

Answers (3)

Mike
Mike

Reputation: 1175

is_numeric($v) returns true if $v is a number (e.g. 234233) or numeric string (e.g. "234233"), whereas intval($v) == $v returns true if $v is an integer.

The first makes sure $v is a numeric in any way and seconds checks if $v is an integer.

I guess you could drop is_numeric($v)

Upvotes: 0

Fabio
Fabio

Reputation: 23500

It is using intval() just because it's checking for the value entered to be an integer rather than a string wich would not be allowed in your query either for column datatype and for security purpose

intval — Get the integer value of a variable

Upvotes: 0

Devon Bernard
Devon Bernard

Reputation: 2300

You are correct in your assumption.

That line is merely a method of checking whether the variable $v is indeed an integer. Because if it is any other data-type the value would differ from that intval() operation.

Upvotes: 1

Related Questions