简体   繁体   English

PHP文件报告成功,但MySQL数据库未更新

[英]PHP file reports success but MySQL database not updated

I am trying to send some data from a JavaScript program to a MySQL database using a PHP file (using PDO). 我正在尝试使用PHP文件(使用PDO)将一些数据从JavaScript程序发送到MySQL数据库。 I had gotten it to work a few months ago, but I accidentally deleted the file containing the save_data() function I use to send the data from the JavaScript file to the PHP file, and I can't get it to work anymore. 我几个月前就开始使用它,但是我不小心删除了包含用于将数据从JavaScript文件发送到PHP文件的save_data()函数的文件,但现在我无法使其正常工作。

Here is my save_data function: 这是我的save_data函数:

function save_data(expData){
    data = JSON.stringify(expData)
    $.post('./saveData.php',data,function(response){
        console.log("Response: "+response);
    })
}

And here is my PHP file: 这是我的PHP文件:

<?php
$pdo = new PDO("mysql:host=host;dbname=name;",'admin','p');

$data = json_decode ($_POST['json'], true);

$pdo->prepare("INSERT INTO `response` (`ip`, `complete_sequence`, `total_wins`, `key_presses`, `run_length`, `subject_condition`, `time_elapsed`, `total_answered`, `total_forfeits`, `total_losses`, `total_missed`, `total_paper`, `total_rock`, `total_scissors`, `total_ties`, `run_test_part_one`, `run_test_part_two`, `run_test_part_three`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)")->execute([
$_SERVER['REMOTE_ADDR'],
$data['completeSequence'],
$data['totalWins'],
$data['key_presses'],
$data['runLength'],
implode (", ", $data['SubjectCondition']),
$data['time_elapsed'],
$data['totalAnswered'],
$data['totalForfeits'],
$data['totalLosses'],
$data['totalMissed'],
$data['totalPaper'],
$data['totalRock'],
$data['totalScissors'],
$data['totalTies'],
$data['runsTestPartOne'],
$data['runsTestPartTwo'],
$data['runsTestPartThree']
]);

echo "{'result':'success'}";

What I find strange is that the PHP file reports success after save_data() runs in the code, but no new rows are added to my Database (it doesn't update). 我发现奇怪的是,在代码中运行save_data()之后,PHP文件报告成功,但是没有新行添加到我的数据库中(它不会更新)。

Also, the PHP file has not been touched since I was last able to successfully update my database, so I'm fairly sure that the problem lies in save_data() , but I can't figure out what that is. 另外,自从我上次能够成功更新数据库以来,一直没有触动过PHP文件,因此,我很确定问题出在save_data() ,但我不知道这是什么。

I've already looked through already answered questions about issues similar to this, but in all the cases I could find the problem was that a row with a specific entry was not found, so 0 rows were successfully updated. 我已经浏览过有关类似问题的已回答问题,但是在所有情况下,我都能发现问题是未找到具有特定条目的行,因此成功更新了0行。 In this case, nothing in the Database is being searched for, I am adding a completely new row, so I can't understand why I would get a success message if the Database is not updated. 在这种情况下,没有在数据库中搜索任何内容,我添加了一个全新的行,因此我无法理解如果不更新数据库为什么会收到成功消息。

I'm very new to web development, so any help I could get with this would be really appreciated! 我是Web开发的新手,因此,我能为此提供的任何帮助将不胜感激!

UPDATE: I've been asked to show where the data is sent from. 更新:我被要求显示数据从何处发送。 The data is sent from an HTML file written using a JavaScript library called JsPsych. 数据从使用称为JsPsych的JavaScript库编写的HTML文件发送。 The actual program itself is very lengthy but here is the specific part where the relevant data is stored and save_data() is called: 实际程序本身很冗长,但以下是存储相关数据并save_data()的特定部分:

 //place data in jsPych data structure
    jsPsych.data.addDataToLastTrial({
        totalAnswered: subjectData.answered,
        totalMissed: subjectData.missed,
        totalRock: subjectData.rock,
        totalPaper: subjectData.paper,
        totalScissors: subjectData.scissor,
        completeSequence: full_sequence,
        totalWins: finalscore.wins,
        totalLosses: finalscore.losses,
        totalTies: finalscore.ties,
        totalForfeits: finalscore.forfeits,
        runLength: runLength.toString(),
        runsTestPartOne: partOneRT,
        runsTestPartTwo: partTwoRT,
        runsTestPartThree:partThreeRT,
        eventLog:event_log,
    });

    //write data to Database
    save_data(jsPsych.data.getLastTrialData());

There ended up being two problems, one was that my JSON string was not named 'json' in the save_data() function, so the PHP script was throwing an error when I tried using an uninitialized variable since $_POST['json'] did not exist. 最终有两个问题,一个是我的JSON字符串在save_data()函数中未命名为'json' ,因此当我尝试使用未初始化的变量时,PHP脚本抛出了错误,因为$_POST['json']确实这样做了不存在。 The updated and correct function is this one: 更新和正确的功能是这一功能:

function save_data(expData){
   data = JSON.stringify(expData)
    $.post('./saveData.php',{json:data},function(response){   //send POST request to PHP file
        console.log("Response: "+response);
    })
}

The fix is in line 3, where the input is {json:data} instead of simply data . 修复程序在第3行中,其中输入是{json:data}而不是简单的data

The second problem was that the database itself was misbehaving. 第二个问题是数据库本身行为异常。 One column in particular refused to accept new entries and would throw an error whenever INSERT was run. 特别是其中一栏拒绝接受新条目,并且每当运行INSERT时都会抛出错误。 This problem was found by adding a try-catch block to the PHP so that any errors thrown by the database itself were reported. 通过向PHP添加try-catch块来发现此问题,以便报告数据库本身引发的任何错误。 Here are the relevant parts of the updated PHP file: 这是更新的PHP文件的相关部分:

<?php
try{
error_reporting(E_ALL); ini_set('display_errors', 1);
$pdo= new PDO( /*irrelevant*/);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

#irrelevant code ---------

}

catch(exception $e) {
    echo 'Exception -> ';
    var_dump($e->getMessage());
}

That problem was solved by simply deleting the column and adding it again. 通过简单地删除该列并再次添加即可解决该问题。 It was a simple fix but I've included the code to find the problem because I found it useful to be able to see errors thrown by the database itself. 这是一个简单的修复程序,但是我包含了查找问题的代码,因为我发现能够查看数据库本身引发的错误很有用。

Thank you to everyone who responded for all the help! 感谢所有为您提供帮助的人!

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

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