PHP PDO预处理语句执行后未存入传入数据问题求助
问题:PDO预处理执行后,数据库存入占位符而非实际数据
我是PDO新手,最近在使用PDO预处理语句时遇到了一个问题:执行插入查询后,目标表中存入的是通过bindParam()绑定的占位符(比如:cod_articolo),而不是我传入的实际数据。以下是我的相关代码,以及执行后的表情况,请问该怎么解决这个问题?
控制器代码(AJAX调用部分)
if(isset($_POST['code'])){ $code = filter_var($_POST['code'],FILTER_SANITIZE_STRING); $qty = filter_var($_POST['quantity'],FILTER_SANITIZE_STRING); $brand = filter_var($_POST['brand'],FILTER_SANITIZE_STRING); $article_name = filter_var($_POST['artName'],FILTER_SANITIZE_STRING); $price = filter_var($_POST['price'],FILTER_SANITIZE_STRING); $article_type = filter_var($_POST['artType'],FILTER_SANITIZE_STRING); $note = filter_var($_POST['note'],FILTER_SANITIZE_STRING); $save = $core->insert_article($code,$qty,$brand,$article_name,$price,$article_type,$note); if($save){ echo 'ok'; } else { echo 'error'; } }
数据库操作类的insert_article方法
public function insert_article($code,$qty,$brand,$article_name,$price,$article_type,$note){ $db = $this->init_db(); $sql = "INSERT INTO products (cod_articolo, pezzi_disponibili, marca, nome_articolo, prezzo, tipologia_articolo, note) VALUES (':cod_articolo',':pezzi_disponibili',':marca',':nome_prodotto',':prezzo',':tipologia_articolo',':note')"; $stmt = $db->prepare($sql); $stmt->bindParam(':cod_articolo',$code,PDO::PARAM_STR); $stmt->bindParam(':pezzi_disponibili',$qty,PDO::PARAM_STR); $stmt->bindParam(':marca',$brand,PDO::PARAM_STR); $stmt->bindParam(':nome_articolo',$article_name,PDO::PARAM_STR); $stmt->bindParam(':prezzo',$price,PDO::PARAM_STR); $stmt->bindParam(':tipologia_articolo',$article_type,PDO::PARAM_STR); $stmt->bindParam(':note',$note,PDO::PARAM_STR); if($stmt->execute()){ echo 'ok'; } else { echo 'error'; } }
执行后数据库表中显示的是占位符字符串(比如:cod_articolo),而非传入的实际数据。
解决方案
兄弟,问题根源就在你的SQL语句里!你给占位符套上了单引号,这就把它们变成了普通的字符串常量——PDO会直接把这些带引号的内容当成要插入的数据,根本不会去替换成你绑定的实际值。
你只需要做两个小修改:
- 把SQL语句中VALUES部分的单引号全部去掉,让PDO能识别出这些是占位符
- 修正占位符名称不匹配的问题:你SQL里写的是
:nome_prodotto,但绑定的时候用的是:nome_articolo,这俩得统一
修改后的SQL语句应该是这样的:
$sql = "INSERT INTO products (cod_articolo, pezzi_disponibili, marca, nome_articolo, prezzo, tipologia_articolo, note) VALUES (:cod_articolo,:pezzi_disponibili,:marca,:nome_articolo,:prezzo,:tipologia_articolo,:note)";
改完之后再执行,PDO就能正确把你绑定的实际数据替换到占位符位置,存入数据库啦!
内容的提问来源于stack exchange,提问作者user9741470
相关产品推荐
相关产品推荐

