drurhg37071 2018-08-17 08:54
浏览 75
已采纳

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

I am trying to send some data from a JavaScript program to a MySQL database using a PHP file (using PDO). 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.

Here is my save_data function:

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

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.

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

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. The actual program itself is very lengthy but here is the specific part where the relevant data is stored and save_data() is called:

 //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());
  • 写回答

1条回答 默认 最新

  • douguxun6866 2018-08-30 06:06
    关注

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

    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. This problem was found by adding a try-catch block to the PHP so that any errors thrown by the database itself were reported. Here are the relevant parts of the updated PHP file:

    <?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!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试