如果输入为空,则不在mysql中插入(pdo)

时间:2013-05-08 08:40:50

标签: php mysql ajax pdo

如果任何输入字段为空,则不要在mysql中插入。某些输入字段是空白的(可接受的)是可能的。在这种情况下,我需要插入非空白字段(值)。但是剧本根本没有插入。

我可以写类似

的内容
if ( (strlen($date_day1) < 1) ) {
$date_day1 = 0;
}

但可能是更好的解决方案?如果为空输入字段,则插入所有其他字段。空字段可能无法插入或插入0。

输入

<input type="text" name="date_day1" id="date_day1"</td>
<input type="text" name="amount1" id="amount1"</td>
<input type="text" name="row_id1" id="row_id1"</td>

然后ajax获取输入值

$(document).ready(function(){
autosave();
});
function autosave() {
var t = setTimeout("autosave()", 5000);
var date_day1 = $("#date_day1").val();
var amount1 = $("#amount1").val();
var row_id1 = $("#row_id1").val();
$.ajax( {
type: "POST",
url: "_autosave.php",
data: "date_day1=" + date_day1 + "&amount1=" + amount1+ "&row_id1=" + row_id1,
cache: false,
} );
}

然后php获取变量

$date_day1 = $_POST['date_day1'];
$amount1 = $_POST['amount1'];
$row_id1 = $_POST['row_id1'];

然后尝试在mysql中录制

$stmt_insert = $db->prepare("INSERT INTO 2_1_journal(RecordDay, Amount, RowId) VALUES(:RecordDay,:Amount,:RowId)");


$stmt_insert->execute(array(':RecordDay' => $date_day1, ':Amount' => $amount1, ':RowId' => $row_id1,

));

更新

有了这样的改变ajax插入工作,但这不起作用 success: function(){ document.getElementById('is_row_changed1').value = 0;}

$(document).ready(function(){           
autosave();
});
function autosave() {
var t = setTimeout("autosave()", 5000);
var date_day1 = $("#date_day1").val();
var amount1 = $("#amount1").val();
var row_id1 = $("#row_id1").val();

if ($("#is_row_changed1").val() > 0) {
$.ajax( {
type: "POST",
url: "_autosave.php",
dataType: "json",
data: {"date_day1" : date_day1, "amount1" : amount1, "row_id1" : row_id1},
cache: false,

success: function(){
document.getElementById('is_row_changed1').value = 0;
}

} );

}
}

2 个答案:

答案 0 :(得分:1)

更改你的ajax部分,这将有效:

$.ajax( {
type: "POST",
url: "_autosave.php",
dataType: "json",
data: {"date_day1" : date_day1, "amount1" : amount1, "row_id1" : row_id1},
cache: false,
} );

希望这会对你有所帮助。

答案 1 :(得分:1)

要添加非空白值,请尝试此

$date_day1 = (trim($_POST['date_day1'])!="" ? $_POST['date_day1'] : 0);

同样,您可以测试其他字段是否为空并添加默认值并将这些变量传递给查询。