简体   繁体   English

jQuery 调用 PHP 文件从 mysql 数据库中获取数据?

[英]jQuery calls a PHP file to get data from mysql database?

Ok so I have found a number of tutorials online and have followed each of them step by step.好的,所以我在网上找到了许多教程,并一步一步地遵循了它们。 My problem is that I know javascript/jQuery much better than I know PHP and I cannot figure out how to even debug what is going wrong in that section.我的问题是我对 javascript/jQuery 的了解比我对 PHP 的了解要好得多,而且我什至无法弄清楚如何调试该部分中出了什么问题。 Basically I have a bunch of buttons and a from and when a button is pressed it determines what the default values are in the form.基本上我有一堆按钮和一个按钮,当按下按钮时,它决定了表单中的默认值。

jQuery Side jQuery侧

$(document).ready(function(){
// CSPC and ADDUPDATE TOGGLE ARE DEFINED GLOBALLY
    $('ul#parts').on('click', 'button', function(){
        ADDUPDATETOGGLE = "ADD";
        CSPC = $(this).attr("data-cspc");
        var   form = $('div.sidebar form'),
              sr = 0;
        form.find("#cspc").val(CSPC);
        $.ajax({
            type: "GET",
            url: "getRate.php",
            data: "pid=A5843",
            dataType: "json",
            success: function(data){
                sr = data;
            }
        });
        form.find("#strokeRate").val(sr);
        showForm();
    });
});

PHP side PHP侧

<?php

$host = "localhost";
$user = "username";
$pass = "password";
$databaseName = "movedb";
$tableName = "part parameters";

$con = mysql_connect($host, $user, $pass);
$dbs = mysql_select_db($databaseName, $con);
//get the parameter from URL
$pid=$_GET["pid"];
if (empty($pid)){
    echo "1"; //default rate
}
else{
    $db=mysql_pconnect("localhost");//connect to local database
    mysql_select_db("movedb", $db);//select the database you want to use
    if (!$db){
        echo ("error connecting to database");              
    }
    else{
        //connection successful
        $sql = "SELECT 'Processing Rate (ppm)' FROM 'part parameters' WHERE 'Part Number' LIKE '" . $pid . "'";//sql string command
          $result=mysql_query($sql);//execute SQL string command
          //result contains rows
          $rows = mysql_fetch_row($result)
          echo json_encode($rows["Processing Rate (ppm)"]); 
    }

}

?>

Any ideas why sr is not getting set?任何想法为什么 sr 没有得到设置?

Am I way off base?我离基地很远吗?

I will also shamelessly note that I do not know what $user and $pass should be set to.我还会无耻地指出,我不知道 $user 和 $pass 应该设置为什么。 I cannot find that explained anywhere我在任何地方都找不到解释

Thanks in advance提前致谢

EDIT: I followed most of the directions below and now when I run编辑:我遵循了下面的大部分指示,现在当我跑步时

http://localhost/getRate.php?pid=A5843 

it says "No database selected."它说“未选择数据库”。 Also, I dont have access to our original MS Access file now (one of my team members has it) but once I get it I will make all the headers into one word headers.另外,我现在无法访问我们原来的 MS Access 文件(我的一个团队成员拥有它),但是一旦我得到它,我会将所有标题变成一个单词标题。 This is our first job with web programming/database management so we are constantly learning.这是我们在 web 编程/数据库管理方面的第一份工作,所以我们一直在学习。

$user and $pass should be set to your MySql User's username and password. $user$pass应设置为您的MySql用户的用户名和密码。

I'd use something like this: 我会用这样的东西:

JS JS

success: function(data){
             if(data.status === 1){
                 sr = data.rows;
             }else{
                 // db query failed, use data.message to get error message
             }
        }

PHP: PHP:

<?php

    $host = "localhost";
    $user = "username";
    $pass = "password";
    $databaseName = "movedb";
    $tableName = "part parameters";

    $con = mysql_pconnect($host, $user, $pass);
    $dbs = mysql_select_db($databaseName, $con);
    //get the parameter from URL
    $pid = $_GET["pid"];
    if(empty($pid)){
        echo json_encode(array('status' => 0, 'message' => 'PID invalid.'));
    } else{
        if (!$dbs){
            echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));       
        }
        else{
            //connection successful
            $sql = "SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //sql string command
            $result = mysql_query($sql) or die(mysql_error());//execute SQL string command
            if(mysql_num_rows($result) > 0){
                $rows = mysql_fetch_row($result);
                echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
            }else{
                echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find processing rate for the give PID.'));   
            }
        }

    }

?>

As another user said, you should try renaming your database fields without spaces so part parameters => part_parameters , Part Number => part_number . 正如另一位用户所说,你应该尝试重命名没有空格的数据库字段,因此part parameters => part_parametersPart Number => part_number

If you're still having trouble then (as long as it's not a production server) put this at the top of your php file: 如果你仍然遇到麻烦(只要它不是生产服务器)把它放在你的php文件的顶部:

error_reporting(E_ALL);
ini_set('display_errors', '1');

This will output any errors and should help you work out what's going wrong. 这将输出任何错误,并应帮助您解决出错的问题。

Your DB query code is incorrect: 您的数据库查询代码不正确:

    $sql = "SELECT 'Processing Rate (ppm)' FROM 'part parameters' WHERE 'Part Number' LIKE '" . $pid . "'";//sql string command

using ' to quote things in the query turns them into STRINGS, not field/table names. 使用'引用查询中的内容将它们转换为STRINGS,而不是字段/表名。 So your query is syntactically and logically wrong. 因此,您的查询在语法和逻辑上都是错误的。 Your code is simply assuming success, and never catches the errors that mysql will be spitting out. 您的代码只是假设成功,并且永远不会捕获mysql将吐出的错误。

The query should be: 查询应该是:

SELECT `Processing Rate (ppm)`
FROM `part parameters`
WHERE `Part Number` = '$pid'

Note the use of backticks (`) on the field/table names, and the use of single quotes ( ' ) on the $pid value. 注意在字段/表名上使用反引号(`),并在$ pid值上使用单引号( ' )。

Then you execute the query with: 然后使用以下命令执行查询:

$result = mysql_query($sql) or die(mysql_error());

If this fails, you will get the error message that mysql returns. 如果失败,您将收到mysql返回的错误消息。

And in the grand scheme of things, your code is vulnerable to SQL injection attacks . 在宏大的计划中,您的代码很容易受到SQL注入攻击 Better read up and learn how to prevent that before you go any farther with this code. 在使用此代码之前,请更好地阅读并学习如何防止这种情况。

sr it's outside the success callback function. sr它在成功回调函数之外。 Start putting it into the success function and see what happens 开始将其置于成功函数中,看看会发生什么

$.ajax({
        type: "GET",
        url: "getRate.php",
        data: "pid=A5843",
        dataType: "json",
        success: function(data){
            sr = data;
            form.find("#strokeRate").val(sr);
        }
    });

remember that, if data is expected to be a json, it will become a js object, so you will not be able to use data directly 请记住,如果数据预计是json,它将成为js对象,因此您将无法直接使用数据

Here is a compilation of the above with up-to-date code.这是上面的最新代码的编译。

jQuery jQuery

$(document).ready(function(){
...
    $.ajax({
            type: "GET",
            url: "getRate.php",  //see note "url"
            data: {
                    pid : "A5843" 
                 //, ... : "..." 
                  }, 
            dataType: "json",
            success: function(data){
                sr = data;
            }
        });
...
    });
  • url > test your request-URL including any parameters (eg. http://localhost/XYZ/getRate.php?pid=251) and then enter it here, after removing anything after the '?' url > 测试您的请求 URL,包括任何参数(例如 http://localhost/XYZ/getRate.php?pid=251 之后在此处输入任何内容) symbol (including '?')符号(包括“?”)
  • data > https://api.jquery.com/Jquery.ajax/数据 > https://api.jquery.com/Jquery.ajax/

PHP PHP

<?php

    $host = "localhost";
    $user = "username";
    $pass = "password";
    $databaseName = "movedb";
    
    $pid=$_GET['pid']; //get the parameter from URL

    $con = mysqli_connect($host, $user, $pass, $databaseName);
    //$dbs = mysqli_select_db($con, $databaseName);


    if (empty($pid)){
        echo json_encode(array('status' => 0, 'message' => 'pid invalid.'));
    }
    else{
        if (mysqli_connect_errno()) {
          echo "Failed to connect to MySQL: " . mysqli_connect_error();
          exit;
        }
        //if (!$dbs)
            //echo json_encode(array('status' => 0, 'message' => 'Couldn\'t connect to the db'));          
        
        else{//connection successful
            $sql = SELECT `Processing Rate (ppm)` FROM `part parameters` WHERE `Part Number` LIKE `" . mysqli_real_escape_string($pid) . "`"; //https://www.geeksforgeeks.org/how-to-prevent-sql-injection-in-php/      
            $result = mysqli_query($con, $sql) or die(mysql_error());//execute query
            if($result){
                $rows = mysqli_fetch_row($result);
                echo json_encode(array('status' => 1, 'rows' => $rows["Processing Rate (ppm)"]);
            }
            else
                echo json_encode(array('status' => 0, 'message' => 'Couldn\'t find results'));   
            }
            mysqli_free_result($result);
            mysqli_close($con);
        }


?>

Please note that I am no PHP-expert.请注意,我不是 PHP 专家。 Any comments welcome.欢迎任何意见。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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