【问题标题】:Values of input field showing in console but not in input field + not able to save to the db输入字段的值显示在控制台中但不在输入字段中+无法保存到数据库
【发布时间】:2015-09-21 09:54:33
【问题描述】:

我正在处理角度和角度材料(材料设计)依赖性。

我有这个主网格,当我单击它时,将创建一个图块,当我单击该图块时会出现一个弹出窗口。在该弹出窗口中是一个带有 2 个输入字段的表单,这些字段应显示图块的 x 和 y 坐标。这些值不会显示在输入字段中,但会显示在我的控制台中。

我想要实现的是能够将这些坐标保存到我的数据库中。出于某种原因,当我点击保存时,它没有保存到我的数据库中。

这是我的弹出框代码:

<form ng-controller="AppCtrl">

          <div layout="row">
              <input type="text" id="coord_x" name="coordinate_x" value="" ng-model="task_coordinate_x" >
              <input type="text" id="coord_y" name="coordinate_y" value="" ng-model="task_coordinate_y">
          </div>
</form>

我的app.js的代码:

app.controller('AppCtrl', function($scope, $mdDialog, $http) {  
$scope.save_task = function() {
            $http.post('db.php?action=add_task', 
                {
                    'task_coordinate_x'          : $scope.task_coordinate_x,
                    'task_coordinate_y'          : $scope.task_coordinate_y
                }
            )

            .success(function (data, status, headers, config) {
                //$scope.get_task(); //this will fetch latest record from DB
console.log("The task has been added successfully to the DB");
                console.log(data);
            })
            .error(function(data, status, headers, config) {
                console.log("Failed to add the task to DB");
            });

function snapToGrid(x, y, $element, animate) {

        //Set gridsize and offsets
        var gridSizeX = 60;
        var offsetX = 0;
        var gridSizeY = 69;
        var offsetY = 10;

        //calculate the x and y positions on the grid
        var newX = x - ( x % gridSizeX );
        var newY = y - ( y % gridSizeY );

        // pass the x and x to the popup hidden input field to be able to save to db
        localStorage.setItem('coordinateX', newX);
        localStorage.setItem('coordinateY', newY);
        console.log("NewX: " + newX);
        console.log("NewY: " + newY);

        //apply the new positions
        if(animate){
            $element.animate({
                top: offsetY + newY,
                left: offsetX + newX,
            }, 200)
        }else{
            $element.css({
                top: offsetY + newY,
                left: offsetX + newX,
            })
        }
    }

};

这是我的 php 代码:

<?php 
    include('config.php');

    switch($_GET['action'])  {

        case 'add_task' :
            add_task(); 
            break;
    }


    /**  Function to add a task to db **/
    function add_task() {
        $data = json_decode(file_get_contents("php://input")); 
        $task_coordinate_x            = $data->task_coordinate_x;
        $task_coordinate_y            = $data->task_coordinate_y;

        print_r($data);

    $qry = 'INSERT INTO tblTask(task_coordinate_x, task_coordinate_y) 
                VALUES ("' 
                . $task_coordinate_x . '","' 
                . $task_coordinate_y . '")';

        echo ($qry);

        $qry_res = mysql_query($qry);
        if ($qry_res) {
            $arr = array('msg' => "Task added successfully!!!", 'error' => '');
            $jsn = json_encode($arr);
            // print_r($jsn);
        } 
        else {
            $arr = array('msg' => "", 'error' => 'Error in inserting record');
            $jsn = json_encode($arr);
            // print_r($jsn);
        }
    }
?>

【问题讨论】:

  • 由于继承和适当的样式,我建议将坐标变量存储在对象coordinates.xcoordinates.y 中。我也会在那里初始化它们。你有没有调查它失败的地方?您的服务器是否获取了变量,或者它们在 save_task 方法中不可用?
  • @enpenax,这就是发生的事情-> recordit.co/HcnJOljPxC
  • 可以去掉 print_r() 命令试试吗?我不完全确定这一点,但如果调用 PHP,它不会在 print_r() 之外执行

标签: javascript php angularjs material-design


【解决方案1】:

我认为问题可能发生在 php 中

在您的地址栏中输入: http://yourservername.com/db.php/action=debug

制作一个php函数

 switch($_GET['action'])  {

        case 'debug' :
            debug(); 
            break;
    }

function debug() {

$qry = 'INSERT INTO tblTask(task_coordinate_x, task_coordinate_y) 
            VALUES ("' 
             some value '","' 
            some value '")'
    or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error(), E_USER_ERROR

);}

并确保其正常工作

希望对你有帮助。

【讨论】:

  • 希望这会有所帮助,因为现在我只是得到一个空白页
  • 抱歉,您误会了我的意思。你的代码到底对我有什么帮助,因为当我现在使用它时,我只是得到一个空白页......
  • 哦好的@GY22...我只想通过调试您的mysqli连接和查询来填充您的空白页,使用die()打印错误报告...确保php脚本中没有错误...
  • 不,它们在 php 中没有错误,因为在表单中我有其他输入字段可以保存到数据库,但出于解释的目的,我将它们注释掉,而不是将它们粘贴到代码中更多。所以我知道 php 的工作原理
【解决方案2】:

这是您的 PHP 代码中的问题,您没有正确使用关联数组。您对 Angular 的 .post().error() 方法也有很大的误解。

$task_coordinate_x            = $data->task_coordinate_x;
$task_coordinate_y            = $data->task_coordinate_y;

应该是

$task_coordinate_x            = $data['task_coordinate_x'];
$task_coordinate_y            = $data['task_coordinate_y'];

这就是为什么您的后端为空白/不返回任何内容的原因。我已经通过这个测试验证了这一点:

<?php
$array = ['test' => 'testval'];
echo $array->test;
?>

这将返回一个空白页面,没有任何回显。 -&gt; 用于对象属性,如果你有一个 PHP 类。 PHP 中的关联数组和类非常不同。试试echo $array['test'] 就可以了。

另一件事是您正在定义 add_task 函数,但从不调用它!在文件末尾包含add_task();

此外,您的 php 函数以回显数组结束,最好让它们返回一个值,然后以 JSON 格式输出,您会明白为什么

假设您修改 add_task 函数以返回 $qry_res 变量。然后,在调用该函数后,您可以创建更好的输出

$qry_res = addtask();
$response = [];
if($qry_res){
    $response['success'] = true;
    $response['message'] = "Task added successfully";
}
else {
    $response['success'] = false;
    $response['message'] = "Task not added";
}
echo json_encode($response);

另一个非常有用的建议是对$qry_res = mysql_query($qry) 行执行某种错误检查。如果查询失败,将该错误消息连接到 $response['message'](确保在函数内声明 global $response),(另一个非常有用的 PHP 调试技术是 output buffer)。

现在有了这个响应,我们可以使用 angular 来查看任务是否成功完成,通过检查 data.success 如下:(数据是来自 PHP 的响应,现在格式更好的 JSON)

你对.post().error()方法也有很大的误解。这将在 HTTP/POST 请求失败时执行,而不是 PHP 是否成功,查看如何让 Angular 实际检测 php 是否成功:

.success(function(data, status, headers, config) {
    console.log(data.message);
    if(data.success){
        // query was successful
    }
    else {
        // query was unsuccessful
    }
})
.error(function(data, status, headers, config) {
    console.log("Failed to reach PHP file or recieve response");
});

希望对你有帮助

【讨论】:

  • @GY22 你说你切换到node,我希望你能早点看到这个,因为这是对php关联数组的误解。我认为,如果您对输入进行了一些回显,您会发现它在 $data-&gt;task_cordinate_x 处失败,这对于从一开始就开始调试并确保您没有任何假设很重要。我会说节点是新的很酷的东西,但切换通常非常痛苦,特别是如果您必须重构大型后端。我已经尝试过开关,节点实际上要复杂得多。众所周知,PHP 是最简单的。祝你好运
【解决方案3】:

您无法在函数内访问全局变量(在这种情况下是您的数据库连接),这就是您无法将数据插入数据库的原因。请在下面找到 PHP 代码并更新,我希望它对你有用!!

对我来说这是完美的!

<?php

class createCon  {
    var $host = 'localhost';
    var $user = 'root';
    var $pass = 'root';
    var $db = 'tblTask';
    var $myconn;

    public function connect() {
        $con = mysqli_connect($this->host, $this->user, $this->pass, $this->db);
        if (!$con) {
            die('Could not connect to database!');
        } else {
            $this->myconn = $con;
            //echo 'Connection established!';
        }   
        return $this->myconn;
    }

    public function close() {
        mysqli_close($myconn);
        echo 'Connection closed!';
    }

}


$connection = new createCon();
$connection->connect();


if($_GET['action'] == 'add_task'){

    $data = json_decode(file_get_contents("php://input"));         
    $task_coordinate_x  = $data->task_coordinate_x;
    $task_coordinate_y  = $data->task_coordinate_y;    

    $qry = 'INSERT INTO tblTask(task_coordinate_x, task_coordinate_y) 
            VALUES ("' 
            . $task_coordinate_x . '","' 
            . $task_coordinate_y . '")';

    if ( mysqli_query($connection->myconn, $qry)) {       
        echo "Success";
    } else {
        echo "Fail";      
    }    
}

?>

如果您有任何疑问,请告诉我!

【讨论】:

  • 我放弃了整个 php,决定使用 node 和 mongo(所以首先这对我来说更容易)。但感谢您的回复
猜你喜欢
  • 2023-03-06
  • 2021-09-09
  • 1970-01-01
  • 2019-12-27
  • 2011-08-15
  • 2020-07-05
  • 2019-02-21
  • 1970-01-01
相关资源
最近更新 更多