【问题标题】:Not able to transfer angular array list to php script for insert into mysql table无法将角度数组列表传输到 php 脚本以插入 mysql 表
【发布时间】:2020-08-06 03:32:49
【问题描述】:

从角度尝试使用 php 脚本在 mysql 数据库表中插入 excel 工作表数据。我已经以角度安装了xlsx,然后尝试读取 xlsx 表。

下面是我的 CandidateuploadComponent.ts 类

import * as XLSX from 'xlsx'; 
export class CandidateuploadComponent implements OnInit {

constructor(private userSvc: AddUsersService,private route: Router) { }

ngOnInit() {
}
title = 'XlsRead';
file:File
arrayBuffer:any
filelist:any

addfile(event)     
{    
  this.file= event.target.files[0];     
  let fileReader = new FileReader();    
  fileReader.readAsArrayBuffer(this.file);     
  fileReader.onload = (e) => {    
  this.arrayBuffer = fileReader.result;    
  var data = new Uint8Array(this.arrayBuffer);    
  var arr = new Array();    
  for(var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);    
  var bstr = arr.join("");    
  var workbook = XLSX.read(bstr, {type:"binary"});    
  var first_sheet_name = workbook.SheetNames[0];    
  var worksheet = workbook.Sheets[first_sheet_name];    
  console.log(XLSX.utils.sheet_to_json(worksheet,{raw:true}));    
        var arraylist = XLSX.utils.sheet_to_json(worksheet,{raw:true});     
        this.filelist = [];    
        let usersJson: any[] = arraylist;
 // Sends the form data to the service
  this.userSvc.sendFormData(XLSX.utils.sheet_to_json(worksheet,{raw:true})).subscribe(
  response => console.log("Success! ", response)
  // error => console.error("Error: ", error)
  );
       
  }    

  }       

  }

服务等级

sendFormData(userData) {
console.log('hi');
console.log(userData);
return this.http.post("http://localhost:8088/post_candidateDetails.php", userData);
}

Belwo 是 php.script

<?php
header("Access-Control-Allow-Origin: http://localhost:4200");
header("Access-Control-Allow-Credentials: true ");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header("Access-Control-Allow-Headers: X-Custom-Header, Origin, Content-Type , Authorisation , X-Requested-With");
header("Content-Type: application/json; charset=UTF-8 ");
$json = file_get_contents('php://input');
$decoded = json_decode($json, true);
$tab = $decoded['tab'];
function conn() {
  $dbhost = "**********";
  $user = "*****";
  $pass = "*****";
  $db = "*********";
  $conn = new PDO('mysql:host=******;dbname=******', $user, $pass);
  return $conn;
}
$db = conn();
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);                  
$p = $db->prepare("INSERT INTO CandidateDetails(EmployeeId, FirstName, LastName, Mobile,Email)VALUES(:EmployeeId,:FirstName,:LastName,:Mobile,:Email)");
                       
foreach ($tab as $item) {
  $p->execute($item);
}
echo json_encode(true);

?>

下面我在浏览器和邮递员中遇到不同的错误,浏览器中的第一个错误是 php 脚本中的第 9 行 undifine index: tab 和邮递员错误:&lt;b&gt;Warning&lt;/b&gt;: Invalid argument supplied for foreach() in &lt;b&gt;C:\xampp\htdocs\post_candidateDetails.php&lt;/b&gt; on line &lt;b&gt;23&lt;/

我参考这个 php 脚本的 axample:

Is there anyway to send a json array to server side php and insert it's values in a table?

获取错误未定义索引:使用 php 脚本插入数组列表的选项卡 在服务方法中,我正在获取 json 数据,如上面的浏览器调试所示,我正在尝试一周后仍未解决,请帮我解决这个问题。

按照 Olivier 的建议更新了 PHP 脚本。

    <?php
    header("Access-Control-Allow-Origin: http://localhost:4200");
    header("Access-Control-Allow-Credentials: true ");
    header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
    header("Access-Control-Allow-Headers: X-Custom-Header, Origin, Content-Type , Authorisation , X-Requested-With");
    header("Content-Type: application/json; charset=UTF-8 ");

    $json = file_get_contents('php://input');
    $decoded = json_decode($json, true);

    print_r($decoded);

    function conn()
    {
        $dbhost = "************";
        $user = "*******";
        $pass = "*******";
        $db = "********";
        $conn = new PDO('mysql:host=*******;dbname=*******', $user, $pass);
        return $conn;
    }
    $db = conn();
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);                  
    $p = $db->prepare("INSERT INTO CandidateDetails(EmployeeId, FirstName, LastName, Mobile,Email)VALUES(:EmployeeId,:FirstName,:LastName,:Mobile,:Email)");
                       
    foreach ($decoded as $item) {
      $p->execute($item);
    }

    echo json_encode(true);

    ?>

Olivier 建议后在浏览器中输出错误:

    Array
    (
        [0] => Array
            (
                [Employeeid] => 1
                [FirstName] => fn1
                [LastName] => ln1
                [Mobile] => 123456789
                [Email] => Email1
            )

        [1] => Array
            (
                [Employeeid] => 2
                [FirstName] => fn2
                [LastName] => ln2
                [Mobile] => 123456790
                [Email] => Email2
            )

        [2] => Array
            (
                [Employeeid] => 3
                [FirstName] => fn3
                [LastName] => ln3
                [Mobile] => 123456791
                [Email] => Email3
            )

        [3] => Array
            (
                [Employeeid] => 4
                [FirstName] => fn4
                [LastName] => ln4
                [Mobile] => 123456792
                [Email] => Email4
            )

    )
    <br />
    <b>Fatal error</b>:  Uncaught PDOException: SQLSTATE[HY093]: Invalid parameter number: parameter was not defined in C:\xampp\htdocs\post_candidateDetails.php:27
    Stack trace:
    #0 C:\xampp\htdocs\post_candidateDetails.php(27): PDOStatement-&gt;execute(Array)
    #1 {main}
      thrown in <b>C:\xampp\htdocs\post_candidateDetails.php</b> on line <b>27</b><br />

【问题讨论】:

  • 信息很清楚。您的 JSON 数据中没有 tab 项。
  • 那有什么问题,如何实现。@Olivier
  • 在客户端读取excel文件而不是在服务器端读取有什么具体原因吗?
  • 也不要在公共论坛上发布您的敏感数据,例如数据库凭据

标签: php mysql angular


【解决方案1】:

消息说 JSON 数据中没有 tab 项目,这是完全正常的,因为您没有发送这样的项目。

真正的问题是您复制/粘贴了一些代码而没有真正理解它的作用。您从中获取代码的人是说法语的人,“array”的法语单词是“tableau”,在程序中通常缩写为“tab”。所以他显然将他的数组存储在 tab 项目中。

但这不是你正在做的。您将数组直接转换为 JSON,这意味着 $decoded 已经是数组。所以你应该这样做:

$decoded = json_decode($json, true);
foreach ($decoded as $item) {
    $p->bindValue(':EmployeeId', $item['Employeeid'], PDO::PARAM_INT);
    $p->bindValue(':FirstName', $item['FirstName'], PDO::PARAM_STR);
    $p->bindValue(':LastName', $item['LastName'], PDO::PARAM_STR);
    $p->bindValue(':Mobile', $item['Mobile'], PDO::PARAM_STR);
    $p->bindValue(':Email', $item['Email'], PDO::PARAM_STR);
    $p->execute();
}

【讨论】:

  • 您能否添加完整的答案,因为几乎没有混淆,而且我是从角度正确发送的? @奥利维尔
  • 从你的截图中,Angular 发送了一个数组(有 4 个元素)。你不需要改变那一侧的任何东西。您应该只更改 PHP 脚本(删除 $tab)。

  • 警告:在 C:\xampp\htdocs\post_candidateDetails.php 中为 foreach() 提供的参数无效 行>40
    true.... 删除此行后 $tab = $decoded['tab'];. @奥利维尔
  • 您是否也更改了foreach 行?

  • 致命错误:未捕获的 PDOException:SQLSTATE[HY093]:无效参数编号:参数未在 C:\xampp\htdocs\post_candidateDetails.php 中定义: 43 堆栈跟踪:#0 C:\xampp\htdocs\post_candidateDetails.php(43): PDOStatement->execute(Array) #1 {main} 抛出 C:\xampp\htdocs\post_candidateDetails.php43 行
猜你喜欢
  • 1970-01-01
  • 2019-04-03
  • 2011-08-04
  • 1970-01-01
  • 2019-06-17
  • 1970-01-01
  • 1970-01-01
  • 2017-07-03
  • 2018-02-01
相关资源
最近更新 更多