I have to build reporting website in which SQL data will be imported using exported csv file from another system.
I built the code but I cannot proceed it, to import in SQL, I just have message QUERY FAILED, not error from SQL or connection with database.
Could someone review my code and write me where is my mistake? I user escape on data because i have come data like... "John's company"
:
<?php
if(isset($_POST['import'])) {
$filename = $_FILES['file']['tmp_name'];
if($_FILES['file']['size'] > 0 ) {
$file = fopen($filename, 'r');
while (($data = fgetcsv($file, 10000, ",")) !== FALSE ) {
$data = array_map('mysqli_real_escape_string', $data);
$query = "INSERT INTO purchasing ";
$query .= "(
purchase_req,
pr_date,
pr_item,
pr_created_by,
po_created_by,
purch_group,
purchase_ord,
po_date,
po_item,
po_state,
vendor_numb,
vendor_name,
mat_desc,
gl_acc,
cost_cent,
po_qty,
po_del_date,
po_delivered_qty,
po_to_be_del
) ";
$query .= "VALUES (
'" . $data[0] . "',
'" . $data[1] . "',
'" . $data[2] . "',
'" . $data[3] . "',
'" . $data[4] . "',
'" . $data[5] . "',
'" . $data[6] . "',
'" . $data[7] . "',
'" . $data[8] . "',
'" . $data[9] . "',
'" . $data[10] . "',
'" . $data[11] . "',
'" . $data[12] . "',
'" . $data[13] . "',
'" . $data[14] . "',
'" . $data[15] . "',
'" . $data[16] . "',
'" . $data[17] . "',
'" . $data[18] . "'
) ";
$send_to_database = mysqli_query($conn, $query);
if(!$send_to_database) {
die("QUERY FAILED <br>" . mysqli_error($conn));
} else {
header("Location: index.php");
}
}
fclose($file);
}
}
?>
/// UPDATED CODE AFTER SUGGESTIONS
<?php
if(isset($_POST['import'])) {
$filename = $_FILES['file']['tmp_name'];
if($_FILES['file']['size'] > 0 ) {
$file = fopen($filename, 'r');
$conn = new mysqli("localhost", "####", "####", "####");
if($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$stmt = $mysqli->prepare("INSERT INTO purchasing (purchase_req, pr_date, pr_item, pr_created_by, po_created_by, purch_group, purchase_ord, po_date, po_item, po_state, vendor_numb, vendor_name, mat_desc, gl_acc, cost_cent, po_qty, po_del_date, po_delivered_qty, po_to_be_del) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?) ");
fgetcsv($file, 10000, ",");
while(($data = fgetcsv($file, 10000, ",")) !== FALSE) {
$data = fgetcsv($file);
$stmt->bind_param("sssssssssssssssssss", $data[0], $data[1], $data[2], $data[3], $data[4], $data[5], $data[6], $data[7], $data[8], $data[9], $data[10], $data[11], $data[12], $data[13], $data[14], $data[15], $data[16], $data[17], $data[18]);
$stmt->execute();
}
fclose($file);
}
}
?>
With the second case, i print the array but again i can't send it to SQL...