简体   繁体   中英

PHP MySql double quotes than single quotes

I was reading a book about PHP and saw this code for inserting records. I do not understand a specific expression in the default case of the ternary operator. More specifically:

"'$v',"

Did the author make a mistake using single quotes (') and what he really meant were the backticks(`) to quote a soecial mysql expression? Why would you use single quotes and then double quotes on a variable?

According to the mysql documentation :

"The identifier quote character is the backtick (“`”): " http://dev.mysql.com/doc/refman/5.0/en/identifiers.html

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',";
    }
}

double quotes signify that it's a string and the single quotes are part of a string. inside double quotes variables are evaluated so the string will contain the value of the variable 'vValue' not '$v'

The singlequotes wrap your value. It's important if the value is a String.

If you don't wrap the String-value, every word would be interpreted as a reserved SQL-word.

By the way, I recommend using PDO for handling SQL stuff: http://www.php.net/manual/en/book.pdo.php

NOTE that the double quotes " " used in (is_numeric($v) && (intval($v) == $v)) ? $v . "," : "'$v',"; (is_numeric($v) && (intval($v) == $v)) ? $v . "," : "'$v',"; are referring to the value inside a ternary operation.

`$values.=((is_numeric($v) && (intval($v) == $v)) ? $v . "," : "'$v',";` 

is same as saying:

if((is_numeric($v) && (intval($v) == $v)) {
$values.= $v . ",";
}else{
$values.="'$v',";
}

Which is practically correct.... You can learn more about ternary operators here ::

This line:

$values .= (is_numeric($v) && (intval($v) == $v)) ? $v . "," : "'$v',";

Looks to see if the value of $v is a number or not. If it is a number it appends that number followed by a comma(,) to the value of $values. If it is NOT a number then it wraps the value in single quotes followed by a comma and appends that to the $values.

Basically you are making sure your statement looks like this when it's all done:

insert into sometable (col1, col2, col3, col4) values (0, 'some string', 'other string', 67, 'etc...')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM