出于项目的实现目的,我正在遵循此CRUD tutorial with PDO, Ajax and Modal Bootstrap。我的数据库有2个表(用户)和( tipo_ps )。
用户表具有以下结构:
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`tipo_fk` int(11) NOT NULL,
`first_name` varchar(150) NOT NULL,
`last_name` varchar(150) NOT NULL,
`image` varchar(150) NOT NULL,
PRIMARY KEY (`id`),
KEY `tipo_fk` (`tipo_fk`),
CONSTRAINT `users_ibfk_1` FOREIGN KEY (`tipo_fk`) REFERENCES `tipo_ps` (`tipo_id`) ON DELETE NO ACTION ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8
下面的用户表示例,其寄存器为:
+-------+-------------+--------------+-------------+-------------+
| id | tipo_fk | first_name | last_name | image |
+-------+-------------+--------------+-------------+--------------
| 1 | student | John | Jackson | 001.jpg |
| 2 | Professinal | Stephany | Roberts | 002.jpg |
| 3 | Professinal | Bruce | Wayne | 003.jpg |
| 4 | Professinal | Jimmy | Forbes | 004.jpg |
| 5 | student | Lisa | Fooman | 005.jpg |
+-------+-------------+--------------+-------------+-------------+
tipo_ps 表具有以下结构:
CREATE TABLE `tipo_ps` (
`tipo_id` int(11) NOT NULL AUTO_INCREMENT,
`tipo` varchar(11) NOT NULL,
PRIMARY KEY (`tipo_id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8'
在下面的 tipo_ps 表中带有示例寄存器:
+---------+--------------+
| tipo_id | tipo |
+---------+--------------+
| 1 | Student |
| 2 | Professional |
+---------+--------------+
如您所见,我在 users 表中创建了一个调用 tipo_fk 的前键,该键的关系已正确创建并插入了 users 当我使用phpMyAdmin时,该表还可以。
我在 users 表中创建了列 tipo_fk 后,我只是在PHP PDO代码脚本中添加了 tipo_fk ,这些功能是该功能的一部分使工作变得可行,但是即使如此,dataTable也不会在index.php页中显示任何数据,并且PDO不会插入 users 表的数据中。填写表单后,用户单击“提交”按钮,Ajax警报将显示空白响应,如下图所示:
完成此提交操作后,浏览器通过“网络”菜单中的F12按钮,通知操作发生的响应,如下图所示:
Answer of browsers after click submit button form
下面,我发布了PHP PDO插入脚本( insert.php ),其中显示了代码行(':tipo_fk'=> $ _POST ['tipo_fk'],)以PDO格式插入:
<?php
include('db.php');
include('function.php');
if(isset($_POST["operation"]))
{
if($_POST["operation"] == "Add")
{
$image = '';
if($_FILES["user_image"]["name"] != '')
{
$image = upload_image();
}
$statement = $connection->prepare("
INSERT INTO users (tipo_fk, first_name, last_name, image)
VALUES (:tipo_fk, :first_name, :last_name, :image)
");
$result = $statement->execute(
array(
/*here*/':tipo_fk' => $_POST['tipo_fk'],
':first_name' => $_POST['first_name'],
':last_name' => $_POST['last_name'],
':image' => $image
)
);
if(!empty($result))
{
echo 'Data Inserted';
}
}
?>
在我无法通过上面显示的形式插入数据的同时,我可以通过phpMyAdmin正常插入数据。另外,即使正常地通过phpMyAdmin插入数据,index.php文件中的dataTable也不会将所插入的数据加载到phpMyAdmin中,从而在下面的图像中显示一个空表:
Empty table even insert data by phpMyAdmin
下面是我用来显示表单的Bootstrap Modal代码。该代码在index.php页面中:
<button type="button" id="add_button" data-toggle="modal" data-target="#userModal" class="btn btn-info btn-lg">Add</button>
<div id="userModal" class="modal fade">
<div class="modal-dialog">
<form method="post" id="user_form" enctype="multipart/form-data">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Add User</h4>
</div>
<div class="modal-body">
<label for="tipo">Select</label>
<select name="tipo_fk">
<?php
include 'db.php';
$commandstring = "SELECT tipo FROM tipo_ps";
$cmd = $connection->prepare($commandstring);
$cmd->execute();
$result = $cmd->fetchAll(PDO::FETCH_ASSOC);
foreach($result as $row) {
if($selid==$row['tipo_id']) {
echo '<option value="'.$row['tipo_id'].'">'.$row['tipo'].'</option>';
}
}
?>
</select>
<br />
<label>Enter First Name</label>
<input type="text" name="first_name" id="first_name" class="form-control" />
<br />
<label>Enter Last Name</label>
<input type="text" name="last_name" id="last_name" class="form-control" />
<br />
<label>Select User Image</label>
<input type="file" name="user_image" id="user_image" />
<span id="user_uploaded_image"></span>
</div>
<div class="modal-footer">
<input type="hidden" name="user_id" id="user_id" />
<input type="hidden" name="operation" id="operation" />
<input type="submit" name="action" id="action" class="btn btn-success" value="Add" />
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</form>
</div>
</div>
还有一个名为( fetch.php )的PHP PDO脚本,该脚本负责根据SELECT查询选择数据并将其显示在表中:
<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM users ";
if(isset($_POST["search"]["value"]))
{
$query .= 'WHERE first_name, tipo_fk LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= 'OR last_name LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
$query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1)
{
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
$image = '';
if($row["image"] != '')
{
$image = '<img src="upload/'.$row["image"].'" class="img-thumbnail" width="50" height="35" />';
}
else
{
$image = '';
}
$sub_array = array();
$sub_array[] = $image;
$sub_array[] = $row['tipo_fk'];
$sub_array[] = $row['first_name'];
$sub_array[] = $row['last_name'];
$sub_array[] = '<button type="button" name="update" id="'.$row["id"].'" class="btn btn-warning btn-xs update">Update</button>';
$sub_array[] = '<button type="button" name="delete" id="'.$row["id"].'" class="btn btn-danger btn-xs delete">Delete</button>';
$data[] = $sub_array;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $filtered_rows,
"recordsFiltered" => get_total_all_records(),
"data" => $data
);
echo json_encode($output);
?>
最后,在index.php页面中的Ajax脚本:
Ajax-网址:insert.php
$(document).on('submit', '#user_form', function(event){
event.preventDefault();
var tipo = $('#tipo_fk').val();
var firstName = $('#first_name').val();
var lastName = $('#last_name').val();
var extension = $('#user_image').val().split('.').pop().toLowerCase();
if(extension != '')
{
if(jQuery.inArray(extension, ['gif','png','jpg','jpeg']) == -1)
{
alert("Invalid Image File");
$('#user_image').val('');
return false;
}
}
if(tipo != '' && firstName != '' && lastName != '')
{
$.ajax({
url:"insert.php",
method:'POST',
data:new FormData(this),
contentType:false,
processData:false,
success:function(data)
{
alert(data);
$('#user_form')[0].reset();
$('#userModal').modal('hide');
dataTable.ajax.reload();
}
});
}
else
{
alert("Both Fields are Required");
}
});
Ajax-网址:fetch_single.php(更新):
$(document).on('click', '.update', function(){
var user_id = $(this).attr("id");
$.ajax({
url:"fetch_single.php",
method:"POST",
data:{user_id:user_id},
dataType:"json",
success:function(data)
{
$('#userModal').modal('show');
$('#tipo_fk').val(data.tipo_fk);
$('#first_name').val(data.first_name);
$('#last_name').val(data.last_name);
$('.modal-title').text("Edit User");
$('#user_id').val(user_id);
$('#user_uploaded_image').html(data.user_image);
$('#action').val("Edit");
$('#operation').val("Edit");
}
})
});
Ajax-网址:delete.php
$(document).on('click', '.delete', function(){
var user_id = $(this).attr("id");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
url:"delete.php",
method:"POST",
data:{user_id:user_id},
success:function(data)
{
alert(data);
dataTable.ajax.reload();
}
});
}
else
{
return false;
}
});
在这种情况下,我无法确定哪里出了问题,什么原因导致无法在Mysql中插入数据,以及没有显示 users 表的数据通过index.php中的dataTable。关键是,在我在 users 表中创建 tipo_fk 列之前,CRUD运行良好。
当我在 users 表和PHP PDO脚本中将 tipo_fk 列作为前导键添加时,就会出现问题。