PHP - concatenate or directly insert variables in string

前端 未结 14 2413
無奈伤痛
無奈伤痛 2020-11-22 04:45

I am wondering, What is the proper way for inserting PHP variables into a string?

This way:

echo \"Welcome \".$name.\"!\"
         


        
14条回答
  •  心在旅途
    2020-11-22 05:13

    If you want to execute a SQL command and your variables are array members, then you should not use single quotes inside [] of array (like this: ['']); for example if you use this string as a SQL command, you get server error 500:

    $con = mysqli_connect('ServerName', 'dbUsername', 'dbPassword');
    mysqli_select_db($con, 'dbName')
    
    //'ID' is auto increment field.
    $sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray['TraceNo']')";
    mysqli_query($con, $sql)
    

    The correct string is:

    //'ID' is auto increment field.
    $sql = "INSERT INTO sampleTable (ID, TraceNo) VALUES ('','$sampleArray[TraceNo]')";
    

提交回复
热议问题