简体   繁体   中英

PDO PHP insert not working

$pdo = $db_con->prepare("INSERT INTO agents (Agent_ID,Agent_Name,Agent_Branch) VALUES (:1, :2, :3)");
$pdo->bindParam(':1', $id);
$pdo->bindParam(':2', $agent);
$pdo->bindParam(':3', $branch);
$pdo->execute();

No errors and this does work

$db_con->exec("INSERT INTO agents (Agent_ID,Agent_Name,Agent_Branch) VALUES ('fd','dd','d')");

By the way is the first method more secure or does it not matter?

Have you considered using ? placeholder instead of :<n> ?

Since you are not giving descriptive names to your placeholders, there is no point of doing like your are. I could not find anything at the docs that suggests it's possible to name parameters as integers.

My suggestion:

$pdo = $db_con->prepare("INSERT INTO agents (Agent_ID,Agent_Name,Agent_Branch) VALUES (?, ?, ?)");
// Params are 1-indexed!!!
$pdo->bindParam(1, $id);
$pdo->bindParam(2, $agent);
$pdo->bindParam(3, $branch);
$pdo->execute();

Since you are just ignoring the parameter type (which is OK in most cases), you'd better do:

$pdo = $db_con->prepare("INSERT INTO agents (Agent_ID,Agent_Name,Agent_Branch) VALUES (?, ?, ?)");
$pdo->execute(array($id, $agent, $branch));

Then all three parameters will be treated as strings.


About the question of which one is more secure, if $id , $agent , and $branch are information provided by the user, the more secure approach is the first one, since it uses prepared statements and therefore you'll be warded against SQL Injection at least. If these data come from a "reliable source" (ex.: is hard-coded into you application), then there is no difference between them in terms of security a priori .

However, if someone (anyone) has access to that data, he could change it, making your system vulnerable. Therefore, the wiser option is to always use prepared statements. This is "more secure" than nothing, but is not secure at all, there are several other issues that prepared statements don't treat to take in account.

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