我正在用PHP和MySQL编写一个简单的数据库应用程序。我正在使用ajax运行脚本服务器端。我使用PDO编写了一个数据库类。
我编写了各种php脚本来处理插入数据,它们都使用我们类的“pre准备()”和"execute()“方法。
我编写了一个单独的php脚本来创建表和删除表,并插入示例数据和删除所有数据。这是为了帮助我在构建和调试数据库应用程序时返回“已知”数据集。
我已经在html中创建了四个按钮,并且我正在缓慢地调用一个php脚本,使用GET传递一个名为" script“的变量。在我的脚本中,我有一个开关语句,它决定要运行的SQL命令。我不需要绑定任何变量。
当我单击一个按钮来执行一个脚本时,如果情况允许的话,它可以工作。因此,例如,如果我单击删除所有表,它将删除这些表。但是,如果我再次单击它(并且没有要删除的表),javascript将返回一个500 -内部服务器错误。我想返回一个错误消息,但无法确定在我的脚本中处理这个错误的位置。
以下是我的课堂方法:
public function prepare($query){
// PDO prepare allows for binding of values, removes threat of SQL injection and improves query performance
$this->statement = $this->connection->prepare($query);
}
public function bind($parameter, $value, $type = null){
// PDO bindValue binds inputs to placeholders
if(is_null($type)){
switch(true){
case is_int($value):
$type = PDO::PARAM_INT;
break;
case is_bool($value):
$type = PDO::PARAM_BOOL;
break;
case is_null($value):
$type = PDO::PARAM_NULL;
break;
default:
$type = PDO::PARAM_STR;
}
}
$this->statement->bindValue($parameter, $value, $type);
}
public function execute(){
// Executes the prepared statement
return $this->statement->execute();
}
public function allresults(){
// Returns all results
$this->execute();
return $this->statement->fetchAll(PDO::FETCH_ASSOC);
}下面是使用ajax调用php脚本的关键部分:
switch ($script) {
case "create":
global $create_tables;
global $database;
$database->prepare($create_tables);
$result = $database->execute($create_tables);
if($result){
echo "Success";
}
else{
echo "Failed";
}
break;其中一个按钮:
<button type="button" class="btn btn-success" onclick="library('newsql.php?script=create')">Create Tables</button>我的js:
function library(path) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("main").innerHTML = this.responseText;
}
};
xmlhttp.open("GET",path,true);
xmlhttp.send();
};我认为这与准备语句的标准返回有关,但可能与执行准备好的语句而不绑定变量有关,还是重复准备好的语句而不更改变量?
发布于 2018-01-14 19:15:59
所以你在诊断发生了什么方面有问题。
希望这能有所帮助。
https://stackoverflow.com/questions/48253108
复制相似问题