使用AngularJS将数据插入数据库

时间:2016-07-22 18:13:09

标签: php mysql angularjs

我目前正在开发一个AngularJS项目,它有一个表单和表单提交表单数据被推送到一个sql数据库。

我已经成功设法将AngularJS项目连接到sql数据库,但是表单中的数据没有插入到表列中而是显示为空 - 请参阅附件以获得可视化解释。

问题,为什么我的数据没有插入到sql中,如何更正我的代码才能使其正常工作?

任何和所有建议都将不胜感激,谢谢。

AngularJS

$scope.submit = function() {
  console.log($scope.form);
  $http.post('XXX/submit.php', {'id':'3','coachName':'1','contractArea':'2','attendance':'4'})
  .success(function(data,status,headers,config){
    console.log('Success');
  });
};

PHP

  $data = json_decode(file_get_contents('php://input'));

  $coachName = mysql_real_escape_string($data->coachName);
  $contractArea = mysql_real_escape_string($data->contractArea);
  $id = mysql_real_escape_string($data->id);
  $attendance = mysql_real_escape_string($data->attendance);

  mysql_connect('XXX','XXX','XX');
  mysql_select_db('XX');
  mysql_query("INSERT INTO participants(`id`, `coachName`, `contractArea`, `attendance`)VALUES('".$id."','".$coachName."','".$contractArea."','".$attendance."')");

SQL enter image description here

enter image description here

PHP,Update 1

  $servername = "XXX";
  $username = "XXX";
  $password = "XXX";
  $dbname = "XXX";

  $conn = new mysqli($servername, $username, $password, $dbname);

  if ($conn->connect_error) {
      die("Connection failed: " . $conn->connect_error);
  }

  $stmt = $conn->prepare("INSERT INTO participants (id,coachName, contractArea, attendance) VALUES (?, ?, ?, ?)");
  $stmt->bind_param("ssss", $iddb, $coachName, $contractArea, $attendance);

  $id = "1";
  $coachName = "2";
  $contractArea = "3";
  $attendance = "4";
  $stmt->execute();

  echo "Success";

  $stmt->close();
  $conn->close();

AngularJS,Update 2

  var variableName = {id:'1', coachName:'AA', contractArea:'BB', attendance:'CC'};
  $http({
    method: 'POST',
    url: "xxx/submit.php",
    data:  variableName,
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  }).then(function(){
    console.log('Success');
  },function(){
    console.log('Error');
  });

PHP,更新2

$servername = 'xxx';
$username = 'xxx';
$password = 'xxx';
$dbname = 'xxx';

$conn = new Mysqli($servername, $username, $password, $dbname);

if ($conn->connect_error) {
  mail( "xxx@xxx.com", "DB connect error", $db->connect_errno . ": " . $db->connect_error );
}

$id = '1';
$coachName = $_POST['coachName'];
$contractArea = $_POST['contractArea'];
$attendance = $_POST['attendance'];

$stmt = $conn->prepare('INSERT INTO participants (id, coachName, contractArea, attendance) VALUE(?, ?, ?, ?)' );
$stmt->bind_param('ssss', $id, $coachName, $contractArea, $attendance);

$stmt->execute();

echo 'Success';

$stmt->close();


$conn->close();

3 个答案:

答案 0 :(得分:1)

我也在我的一个项目中使用AngularJS和PHP并遇到了同样的问题,然后我遇到了类似这样的事情。尝试在您的请求中添加headers参数。可能这会对你有帮助。

var variableName = {'id':'3','coachName':'1','contractArea':'2','attendance':'4'})
$http({
        method : 'POST',
        url : "XXX/submit.php",
        data   :  variableName,
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
        }).then(function(){
               console.log('Success');
           },function(){
               console.log('Error');
        });

如果它没有解决你的问题,我只是想尝试,请告诉我。

答案 1 :(得分:0)

花了几个小时,大量的阅读和Stack社区的支持,但我终于明白了。

这就是我最终的结果:

<强> AngularJS

/* Submit */
$scope.submit = function() {
  var request = $http({
    method: "post",
    url: 'xxx/submit.php',
    data: {
      id: '1',
      coachName: 'B',
      contractArea: '2',
      attendance: 'C',
    },
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
  });
};

<强> PHP

<?php

  $postdata = file_get_contents("php://input");
  $request = json_decode($postdata);
  $id = $request->id;
  $coachName = $request->coachName;
  $contractArea = $request->contractArea;
  $attendance = $request->attendance;

  $servername = 'xxx';
  $username = 'xxx';
  $password = 'xxx';
  $dbname = 'xxx';

  $conn = new Mysqli($servername, $username, $password, $dbname);

  if ($conn->connect_error) {
    mail( "adamwadsworth@xxx.com", "DB connect error", $db->connect_errno . ": " . $db->connect_error );
  }
  $stmt = $conn->prepare('INSERT INTO participants (id, coachName, contractArea, attendance) VALUES (?, ?, ?, ?)' );
  $stmt->bind_param('ssss', $id, $coachName, $contractArea, $attendance);

  $stmt->execute();

  echo 'Success';

  $stmt->close();

  $conn->close();

?>

<强> SUCCESS
enter image description here

答案 2 :(得分:-1)

更新回答

Angular

$scope.submit = function () {
    $http.post('test.php', {'id':'3','coachName':'1','contractArea':'2','attendance':'4'})
        .success(function(data,status,headers,config){
            if(!data.success)
                 alert(data.message)
            console.log(data);
        });
}

<强> PHP

if($_SERVER['REQUEST_METHOD'] == 'POST')
{
    header('Content-Type:application/json');

    $data = json_decode(file_get_contents('php://input'));

    $servername = 'xxx';
    $username = 'xxx';
    $password = 'xxx';
    $dbname = 'xxx';

    try {
    $dbh = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);

    $sql = 'INSERT INTO participants (id,coachName, contractArea, attendance) VALUES (?, ?, ?, ?)';
                $sth = $dbh->prepare($sql);

    try {

        $dbh->beginTransaction();

        $sth->execute(array(
                        $data->id,//if id is string replace $data->id to '".$data->id."'
                        '".$data->coachName."',
                        '".$data->contractArea."',
                        '".$data->attendance."'
                    ));

        $dbh->commit();

        echo json_encode(['success'=> true,'data'=>$sth->fetch(PDO::FETCH_ASSOC)]);

    } catch(PDOExecption $e) {
        $dbh->rollback();
        echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
    }
} catch( PDOExecption $e ) {
    echo json_encode(['success'=>false,'message'=>$e->getMessage()]);
}

应该有效