简体   繁体   中英

Making MySQL queries using javascript function.

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>

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.

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 (ie 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 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>

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 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.

AJAX does not work like this. Basically, product of PHP is a HTML page (with JS), that is rendered upon request in the browser. When user performs an action, that should result in displaying data retrieved by AJAX, the browser makes another request, possibly to different PHP script. Result of this request is not displayed to the user, as while performing the first request, rather it is passed to a function in JS of the currently displayed page (that is what makes it AJAX). This function can then process the data in any way it wants.

Have a look at this: http://www.w3schools.com/jquery/jquery_ajax_intro.asp .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM