使用javascript函数进行MySQL查询. [英] Making MySQL queries using javascript function.

查看:60
本文介绍了使用javascript函数进行MySQL查询.的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建可以在JavaScript代码中使用的PHP函数.

I'm trying to create PHP function that I will be able to use in javascript code.

<!DOCTYPE html>
<?php
include 'pdo_connect.php';
function pleaseWork($query) {
    return dataQuery($query)->fetchAll();
}
function makeQuery($query)
{
    $work = pleaseWork($query);
    $json = json_encode($work);
}
?>
<html>

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<title>Admin check</title>
<meta charset="UTF-8">
</head>

<body>
<script type='text/javascript'> 
<?php makeQuery("SELECT * FROM `grupy`");?>

var jArray = <?= $json ?>;
console.log(jArray);
</script>

当然这是行不通的,因为JS块中的代码从文件开始就对变量一无所知.我怎么做?我从未使用过AJAX或其他任何工具,所以我不知道该怎么办.

Of course it doesn't work because code in JS block doesn't know anything about variables from beginning of file. How do I do that? I never used AJAX or anything so I don't know what to do.

推荐答案

您需要更详细地了解OOP(面向对象编程).也许搜索依赖注入或异常.另外,您需要创建一个PHP脚本,该脚本接受您的ajax请求并调用必要的函数或方法,这些函数或方法应全部分为各自的文件和类.这样会将不同的数据层彼此分开(即表示,业务逻辑,数据).您还应该花一些时间来学习MVC(模型视图控制器)的含义.这将帮助您了解分离的重要性.

You need to learn about OOP (Object Oriented Programming) in more detail. Perhaps search for Dependency Injection, or Exceptions. Also, you need to create a PHP script that accepts your ajax requests and calls the necessary functions or methods which should all be separated into their own files and in classes. This will separate the different data layers from each other (i.e. presentation, business logic, data). You should also invest some time in learning what MVC(Model View Controller) is about. This will help you understand the importance of the separation.

现在,我将向您展示快速解决您的问题的方法.假设您的文件结构都位于同一目录中,如下所示:

For now, I will show you a quick solution to your problem. Lets imagine your file structure is all in the same directory as such:

|--- ajax_requests.php
|--- Database.php
|--- Functions.php
|--- index.php

index.php 是HTML/jQuery所在的位置:

index.php is where your HTML /jQuery is located:

<!DOCTYPE html>
<html>

<head>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
    <title>Admin check</title>
    <meta charset="UTF-8">
</head>
<body>
<script type='text/javascript'>
    $.ajax({
        type: "post",
        url: "ajax_requests.php",
        data: {request: "get_grupy_json"},
        success: function(result){
            console.log(result);
        }
    });
</script>

注意我们如何使用jQuery发出我们的Ajax请求.我们正在对文件ajax_requests.php发出post请求,将get_grupy_json作为我们的request参数发送.前端视图中不应存在任何SQL查询.

Notice how we are using jQuery to make our Ajax request. We are making a post request to the file ajax_requests.php sending the get_grupy_json as our request parameter. No SQL queries should be present on your front-end views.

ajax_requests.php 接收请求,获取Database对象并将其发送到Functions对象,然后它检查该请求是否作为Functions类的方法存在,如果存在,它将运行方法并将结果转换为json(请记住要自行添加错误检查):

ajax_requests.php receives the request, gets the Database object and sends it to the Functions object, then it checks that the request exists as a method of the Functions class, if it does, it runs the method and turns the result as json (remember to add error checking on your own):

<?php
if (!empty($_POST)) {

    $method = $_POST['request'];

    include 'Database.php';
    include "Functions.php";

    $db = new Database();
    $functions = new Functions($db);

    if (method_exists($functions, $method)) {
        $data = $functions->$method();
        header('Content-Type: application/json');
        echo json_encode($data);
    }
}

Functions.php

class Functions
{
    private $db;

    public function __construct(Database $db)
    {
        $this->db = $db;
    }

    public function get_grupy_json()
    {
        $query = "SELECT * FROM `grupy`";
        $result = $this->db->dataQuery($query);
        return $result->fetchAll();
    }
}

Database.php

class Database
{
    private $conn = null;

    public function __construct()
    {
        try {
            $username = "root";
            $password = "root";
            $servername = "localhost";
            $dbname = "test";
            $this->conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        } catch (PDOException $e) {
            trigger_error("Error: " . $e->getMessage());
        }
    }

    public function dataQuery($query, $params = array())
    {
        try {
            $stmt = $this->conn->prepare($query);
            $stmt->execute($params);
            return $stmt;

        } catch (PDOException $e) {
            trigger_error("Error: " . $e->getMessage());
        };
    }


}

这是我要做的一个粗略的模型.希望您能了解如何将它们分开,以便随着应用程序的增长轻松地向其添加功能.

This is a rough mockup of what i would do. I hope you get the idea of how it is all separated so that you can easily add features to your application as it grows.

这篇关于使用javascript函数进行MySQL查询.的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆