From angular trying to insert excel sheet data in mysql database table using php script. I have installed xlsx in angular then trying to read xlsx sheet.
Below is my CandidateuploadComponent.ts class
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)
);
}
}
}
service class
sendFormData(userData) {
console.log('hi');
console.log(userData);
return this.http.post("http://localhost:8088/post_candidateDetails.php", userData);
}
Belwo is 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);
?>
Below i am getting error in browser and postman differently, first error in browsers which is line number 9 in php script undifine index: tab and post man error : <b>Warning</b>: Invalid argument supplied for foreach() in <b>C:\xampp\htdocs\post_candidateDetails.php</b> on line <b>23</


I refer this axample for php script:
Is there anyway to send a json array to server side php and insert it's values in a table?
Getting error Undefined index: tab for inserting array list using php script In service method i am getting json data as shown in above browser debug, i am trying since a week not resolving still please help me to out this issue.
Updated PHP script as suggested Olivier answer.
<?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);
?>
output in browser with error after suggested by 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->execute(Array)
#1 {main}
thrown in <b>C:\xampp\htdocs\post_candidateDetails.php</b> on line <b>27</b><br />
The message says that there is no tab item in the JSON data, which is perfectly normal since you don't send such an item.
The real problem is that you copy/pasted some code without really understanding what it does. The guy you took the code from is a French speaker, and the French word for "array" is "tableau", which is often abbreviated as "tab" in programs. So he obviously stored his array in a tab item.
But that's not what you are doing. You convert your array directly to JSON, which means $decoded is already the array. So you should do something like this instead:
$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();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With