简体   繁体   中英

Inserting values using PDO

•So I'm trying to change my coding habits and want to at least prevent SQL Injections. However, I'm still confuse about the parameters or syntax in creating a query. For instance,

$q = //LINE 1 "insert into tblProject(projectName, projectLocation, projectType, projectStatus) //LINE 2 values(:projectName, :projectLocation, :projectType, :projectStatus);";

I believe that the first line refers to the column name in the database , however in LINE 2 , what does ':" means and what does it do? Where does the values inside the values() references? Does it refers to the variable I declared, for instance, $projectName = $_POST['projectName']; . Does it refer to the $projectName or the value inside the $_POST['projectName'] ?

•Another question is all about this ...->execute(array(...)); Let's use this code as example:

$results = $query->execute(array(
":projectName"      => $projectName,
":projectLocation"  => $projectLocation,
":projectType"      => $projectType,
":projectStatus"    => $projectStatus
));

Can you explain briefly but precise what it does? And also, where does :projectName and so on.. Came from or where is their origin?

•It uses an array(). Therefore, if I were to only update or insert a single value and use execute(array()) , will it cause me any error?

I believe I ask too much question, any good references where I can find most of the answers here?

Thanks in advance.

The two parts of your question are the same. The names with the colons is how you specify the name of your binding. When you use the bindValue/bindParam or execute, you say "this :parameter is actually this value". So it will take your query:

$q =  "insert into tblProject(projectName, projectLocation, projectType, projectStatus) 
   values(:projectName, :projectLocation, :projectType, :projectStatus);";

Then when you execute it with this:

$results = $query->execute(array(
":projectName"      => $projectName,
":projectLocation"  => $projectLocation,
":projectType"      => $projectType,
":projectStatus"    => $projectStatus
)); 

the driver will go through and say "Okay, so the value of $projectName needs to be escaped and used in place of :projectName in the query, and $projectLocation should be :projectLocation..." and so on and so forth

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