我有一个具有以下结构的表:
Field Type Null Key Default Extra
id int(11) NO PRI NULL auto_increment
form char(255) NO NULL
valori json NO NULL
mail tinyint(1) NO 0
使用ajax调用,我试图在这个表中插入一个新记录。
我试图插入的样本数据是:
"表单":"new_field">
"valori":"{\"status\":500,\"message\":\"Nuovo+campo+creato+ccorrentamente\",\"nome\":\"ffnfaojo\",\"label\":\"vnsognos\",\"descrizione\":">vnsognos:+nosnvoisnvote\",\"autore\":"1\"}">
"mail":"true">
json数组以字符串格式发送。
php代码:
try{
$stmt = $pdo->prepare("INSERT INTO segnalazioni (form,valori,mail) VALUES (:form, :valori, :mail)");
$stmt->bindParam(':form', $form);
$stmt->bindParam(':valori', $valori);
$stmt->bindParam(':mail', $db);
$stmt->execute();
}
catch(PDOexception $e){
echo $e->getMessage();
}
将不会产生输出,也不会插入数据库
如果我发送纯json而不是字符串版本,PHP将引发数组到字符串的转换错误:
数组到字符串的转换。。。在线21
这就是我绑定json值的地方。我在这里缺少了一些东西,但由于这是我第一次存储json,我需要一些帮助。注意,我知道存储JSON的副作用是什么,这是不适用的情况之一:这是一种日志,数据应该保持不变,并且只按表单列搜索。数据库端上的json数据没有操作
编辑:ajax:
}).done(function(data) {
if(data.status==200){
//campo creato correttamente
//not in scope here
}else{
//non sono riuscito a caricare i dati
$('#modal-text').html('<p class="text-danger">'+data.message+'</p><b>Dati per il debug</b> (saranno inviati in automatico nella mail):<br>');
var risposta = data;
$("#modal-text").append(JSON.stringify(data));
$('#message').modal('show');
//default carico solo la segnalazione a db
var mail = false;
//utente sceglie di inviare il modale;
$('.segnalazione').click(function(){
if($(this).attr('id')=='error_submit'){
mail= true;
}
//effettuo il caricamento
$.ajax({
url: 'segnalazione.php',
method: 'post',
data: {form:'new_field', valori:risposta, mail: mail},
dataType: 'json'
});
});
和segnalazione.php的编辑部分:
$id=$_SESSION['id'];
$form=$_POST['form'];
$valori=json_encode($_POST['valori']);
$mail=$_POST['mail'];
try{
$stmt = $pdo->prepare("INSERT INTO segnalazioni (form,valori,mail) VALUES (:form, :valori, :mail)");
$stmt->bindParam(':form', $form);
$stmt->bindParam(':valori', $valori);
$stmt->bindParam(':mail', $db);
$stmt->execute();
}
catch(PDOexception $e){
echo $e->getMessage();
}
导致:
PHP可恢复的致命错误:类PDOStatement的对象无法在中转换为字符串。。。在线24
编辑2:实际发布的内容:
array(3({["form"]=>string(9("new_field"["valori"]=>array(6("true"}
编辑3:使用我的php响应的数据:$form=$_POST['form'];$valori=json_encode($_POST['valori'](;$mail=$_POST['mail'];
我在mysql工作台中构建了运行良好的查询,并按照我所期望的插入了该行
insert into segnalazioni SET form='new_field', valori='{"status":"500","message":"Nuovo campo creato correttamente","nome":"pippo","label":"pluto","descrizione":"pluto: </b>paperino","autore":"1"}', mail=1
这个答案归功于@num8er,它意识到当您在准备好的语句中绑定JSON对象以插入JSON类型字段时,必须指定它必须被视为字符串。
所以改变
$stmt->bindParam(':valori', $valori);
至
$stmt->bindParam(':valori', $valori, PDO::PARAM_STR);
成功了。