我的代码-

$con = new PDO ('mysql:host=localhost;dbname=air','root','123456');
    $con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $fields = implode(", ", $fields);
    echo $fields;
    $values = implode("','", $values);
    echo $values;

    // have to make this prevent sql injection //
    // it wont work if i added bindValue why? //
    $stmt = $con->prepare("INSERT INTO $table(ID, $fields) VALUES (?, ?)");
    $stmt->bindValue(1,'',PDO::PARAM_STR);
    $stmt->bindValue(2,$values,PDO::PARAM_STR);
    $stmt->execute();

    //if I remove `bindValue` and replace this it will insert //
    $stmt = $con->prepare("INSERT INTO $table(ID, $fields) VALUES ('', $values)");

为什么在我添加bindValue之后,我的插入将不再工作,但是当我使用normalsql时,它将工作,我的bindValue和值有什么问题?,?) ,有人能帮我看看吗??

最佳答案

我来晚了,但一个简单的方便的函数,可以使用任何人搜索答案,实现绑定和插入到任何表和字段。我看到您的字段都是PDO::PARAM_STR值。希望这有帮助:)

//get array containing fields and its values to be added $fv_array
$fv_array=array(
"field_one_name"=>$field_one_value,
"field_two_name"=>$field_two_value,
"field_three_name"=>$field_three_value
);

$con=new PDO ('mysql:host=localhost;dbname=air','root','123456');
$con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$fv="";
 //create string like :field_one_name,:field_two_name,:field_three_name,
foreach($fv_array as $field=>$value {$fv.=":".$field.",";}
//rtrim removes trailing comma
$statement=$con->prepare("INSERT INTO ".$table." (".implode(",",array_keys($fv_array)).") VALUES (".rtrim($fv, ",").")");
//bind values
foreach($fv_array as $field=>$value){$statement->bindValue(':'.$field,$value);}
$statement->execute();

关于php - INSERT中的bindValue无法正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30010577/

10-11 20:14