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

时间:2022-10-08 18:17:32

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

好的,所以我在网上找到了一些教程,并逐步完成了每一个教程。我的问题是我知道javascript / jQuery比我知道的PHP要好得多,我无法弄清楚如何调试那部分出了什么问题。基本上我有一堆按钮和一个按钮,当按下按钮时,它确定表格中的默认值。

jQuery Side

jQuery Side

$(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. I cannot find that explained anywhere

我也会无耻地注意到我不知道$ user和$ pass应该设置为什么。我无法在任何地方找到解释

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. This is our first job with web programming/database management so we are constantly learning.

它说“没有选择数据库”。此外,我现在无法访问我们原来的MS Access文件(我的一个团队成员拥有它)但是一旦我得到它,我将把所有标题组成一个单词标题。这是我们在网络编程/数据库管理方面的第一份工作,所以我们不断学习。

3 个解决方案

#1


5  

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

这将输出任何错误,并应帮助您解决出错的问题。

#2


5  

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

使用'引用查询中的内容将它们转换为STRINGS,而不是字段/表名称。因此,您的查询在语法和逻辑上都是错误的。您的代码只是假设成功,并且永远不会捕获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. Better read up and learn how to prevent that before you go any farther with this code.

在宏观方案中,您的代码很容易受到SQL注入攻击。在您使用此代码之前,请更好地阅读并学习如何防止这种情况。

#3


3  

sr it's outside the success callback function. Start putting it into the success function and see what happens

sr它在成功回调函数之外。开始将其置于成功函数中,看看会发生什么

$.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对象,因此您将无法直接使用数据

#1


5  

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

这将输出任何错误,并应帮助您解决出错的问题。

#2


5  

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

使用'引用查询中的内容将它们转换为STRINGS,而不是字段/表名称。因此,您的查询在语法和逻辑上都是错误的。您的代码只是假设成功,并且永远不会捕获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. Better read up and learn how to prevent that before you go any farther with this code.

在宏观方案中,您的代码很容易受到SQL注入攻击。在您使用此代码之前,请更好地阅读并学习如何防止这种情况。

#3


3  

sr it's outside the success callback function. Start putting it into the success function and see what happens

sr它在成功回调函数之外。开始将其置于成功函数中,看看会发生什么

$.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对象,因此您将无法直接使用数据