今天,有一新學PHP的網友問了茶農一個問題:“單引號和雙引號的區別和用法?”,現將答案總結了下,寫成這篇小短文。
" "雙引號裡面的欄位會經過編譯器解釋,然後再當作HTML代碼輸出。
' '單引號裡面的不進行解釋,直接輸出。
例如:
$abc='my name is tome';
echo $abc //結果是:my name is tom
echo '$abc' //結果是:$abc
echo "$abc" //結果是:my name is tom
特別在使用MYSQL語句的時候,雙引號和單引號的用法讓新手不知所措,在這裡,舉個例子,來進行說明。
假設查詢條件中使用的是常量,例如:
select * from abc_table where user_name='abc';
SQL語句可以寫成:
SQLstr = "select * from abc_table where user _name= 'abc'" ;
假設查詢條件中使用的是變數,例如:
$user_name = $_REQUEST['user_name']; //字串變數
或
$user=array ("name"=> $_REQUEST['user_name‘,"age"=>$_REQUEST['age'];//陣列變數
SQL語句就可以寫成:
SQLstr = "select * from abc_table where user_name = ' " . $user_name . " ' ";
SQLstr = "select * from abc_table where user_name = ' " . $user["name"] . " ' ";
對比一下:
SQLstr="select * from abc_table where user_name = ' abc ' " ;
SQLstr="select * from abc_table where user_name =' " . $user _name . " ' ";
SQLstr="select * from abc_table where user_name =' " . $user["name"] . " ' ";
SQLstr可以分解為以下3個部分:
1:"select * from table where user_name = ' " //固定SQL語句
2:$user //變數
3:" ' "
1,2,3部分字串之間用"." 來串連