Insert data to database from CSV file. Only inserts last row - php

I read in data from a csv file, and want to insert it into my database. The issue is that it only inserts the last row in the CSV file each time. However when i print my $sq1 to screen it shows all 48 inserts with the different values that they should have. Could anyone tell me why it only inserts one row into the database?
<?php
// Did modify login values for privacy
$servername = "10.100.";
$username = "myusername";
$password = "abc123";
$dbname = "informationdata";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = fopen("ALMGrade.csv","r");
while(! feof($file)){
$ar =fgetcsv($file);
$sql = "INSERT INTO gradetable_copy (Grade, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6)
VALUES ('$ar[0]', '$ar[1]', '$ar[2]', '$ar[3]', '$ar[4]', '$ar[5]', '$ar[6]' )";
echo $sql;
echo "<br>";
}
fclose($file);
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

move the execution of query ($conn->query($sql) ) inside while:
while(! feof($file))
{
$ar =fgetcsv($file);
$sql = "INSERT INTO gradetable_copy (Grade, Grade1, Grade2, Grade3, Grade4, Grade5, Grade6)
VALUES ('$ar[0]', '$ar[1]', '$ar[2]', '$ar[3]', '$ar[4]', '$ar[5]', '$ar[6]' )";
echo $sql;
echo "<br>";
if ($conn->query($sql) === TRUE)
{
echo "New record created successfully";
}
else
{
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
fclose($file);

Related

I have a problem to insert into mysql all data from inputs and foreach loop ( only one data enters mysql)

Just the last data enters mysql with this program :
<?php
$servername = "localhost";
$username = "bern...";
$password = "password";
$dbname = "base";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo $_POST["quantité"];
$a = $_POST["trekking"];
foreach ($a as $v) {
echo $v . "<br />\n";
$sql = "INSERT INTO Donnesmi (commentaire) VALUES ('$v')";
}
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
Would you have a solution for this basic concern , thank you very much
the reason for your actual problem is
foreach ($a as $v) {
echo $v . "<br />\n";
$sql = "INSERT INTO Donnesmi (commentaire) VALUES ('$v')";
}
so you overwrite your $sql variable each time, and at the end of the loop you are left with the last value. but see the comments for the various issues/suggestions with this code
Edit: 5th Mar 2019
issue with your code was, since within for loop $sql always gets overwritten only the final $sql is executed.
As pointed out by #jameson2012, one optimum way to do this would be,
<?php
$servername = "localhost";
$username = "bern...";
$password = "password";
$dbname = "base";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo $_POST["quantité"];
$a = $_POST["trekking"];
$values = [];
foreach ($a as $v) {
echo $v . "<br />\n";
$values[] = "('$v')";
}
$sql = "INSERT INTO Donnesmi (commentaire) VALUES " . emplode(',', $values);
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
mysqli_close($conn);
?>
basically rather than running multiple insert statements, you build a one single statement and execute it.
========================================================================
Old Answer
You must execute SQL inside foreach. Refer below.
<?php
$servername = "localhost";
$username = "bern...";
$password = "password";
$dbname = "base";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo $_POST["quantité"];
$a = $_POST["trekking"];
foreach ($a as $v) {
echo $v . "<br />\n";
$sql = "INSERT INTO Donnesmi (commentaire) VALUES ('$v')";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
}
mysqli_close($conn);
?>

Another empty row with time stamp added with every entry in mysql database

another empty row with timestamp added in mysql database each time a new row with entries added ,
here is part of my code
$servername = "localhost";
$username = "root";
$password = "zaheer442";
$dbname = "76H";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else {
echo "wooo connected";
}
$sql = "INSERT INTO 76Hlog (Device_ID, Response_status, Device_NO, Status, Time) VALUES ('$keywords[4]', '$keywords[8]', '$keywords[15]', '$keywords[17]', now())";
if(mysqli_query($conn, $sql)){
echo "Records inserted successfully.";
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
//displaying data
$sql = "SELECT Device_ID, Response_status, Device_NO, Status FROM 76H";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "id: " . $row["Device_ID"]. " - Staus: " . $row["Response_status"]. " Devic No " . $row["Device_NO"]. " Mode " . $row["Status"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
[Entries Screenshot has also attached]

SQL and POST requests

How do I handle variables from POST requests? Lets say I have tables like this And I want to update the votes variable wherever a specific id is.
So for the code I have this
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
along with something like this
UPDATE `my_exampleo202s`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = sentid
And in the post request I send the sentid with a number. sentid=3
This doesn't work though. I'm not able to give any errors or anything because I'm not viewing it from a browser.
Any idea what the proper way is that I'm supposed to do this?
(Here's the code I have right now if it's needed)
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
$conn = new mysqli("localhost","exampleo202s","","my_exampleo202s");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_exampleo202s`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>
UPDATE
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
$conn = new mysqli("localhost","jusavoting10rxx9s3","","my_jusavoting10rxx9s3");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_jusavoting10rxx9s3`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = $sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>
Try echo your $_POST value if it doesn't work:
<?php
$vote = $_POST["votes"];
$sentid = $_POST["sentid"];
$conn = new mysqli("localhost","exampleo202s","","my_exampleo202s");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "UPDATE `my_exampleo202s`.`President Candidates` SET votes = votes + 1 WHERE `President Candidates`.`id` = $sentid";
if ($conn->query($sql) === TRUE) {
echo "<br>Record updated successfully <br>";
} else {
echo "<br>Error updating record: <br>" . $conn->error;
}
$conn->close();
?>

Undefined offset error on php when importing a CSV

I am trying to import a CSV file into my database and it is being successfully executed at the end. But, during the execution, I receive an "undefined offset" error message and when I checked the data imported, I see that there are some null records updated in the table. How can I avert importing these null cells into my database? I also would like not to see these error messages.
<?php
require_once("database.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
/// Delete table contents
$dsql = "TRUNCATE TABLE User_Mirror_Tbl";
if ($conn->query($dsql) === TRUE) {
echo "Table content is truncated successfully". PHP_EOL;
} else {
echo "Error: " . $dsql . "<br>" . $conn->error;
}
//read file
$csvfile=file_get_contents("/samba/import/User_Update_Tbl.csv");
//counters:
$record_number=0;
$record_number_err=0;
$lines = explode(PHP_EOL, $csvfile);
$array = array();
foreach ($lines as $line) {
$field = str_getcsv($line);
if $field[0] != ''){
$field[1]= ( $field[1] == '' ? NULL : $field[1]);
$field[6]= ( $field[6] == '' ? NULL : $field[6]);
$field[7]= ( $field[7] == '' ? NULL : $field[7]);
$sql="INSERT INTO User_Mirror_Tbl (History_Record_ID, Employee_ID, Application_ID, User_Status, Record_Date, User_Name, User_Role, Last_Signon, UserKeyString)
VALUES
('$field[0]','$field[1]','$field[2]','$field[3]','$field[4]','$field[5]','$field[6]','$field[7]','$field[8]') ";
//insert record to database
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully". PHP_EOL;
$record_number=$record_number+1;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
$record_number_err=$record_number_err+1;
}
}
}
echo $record_number.' Successful record and '.$record_number_err.' Unsuccessful record executed.';
$conn->close();
<?php
require_once("database.php");
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
/// Delete table contents
$dsql = "TRUNCATE TABLE User_Mirror_Tbl";
if ($conn->query($dsql) === TRUE) {
echo "Table content is truncated successfully". PHP_EOL;
} else {
echo "Error: " . $dsql . "<br>" . $conn->error;
}
//read file
$csvfile=file_get_contents("/samba/import/User_Update_Tbl.csv");
//counters:
$record_number=0;
$record_number_err=0;
$lines = explode(PHP_EOL, $csvfile);
$array = array();
foreach ($lines as $line) {
$field = str_getcsv($line);
if $field[0] != ''){
$field[1]= ( $field[1] == '' ? NULL : $field[1]);
$field[6]= ( $field[6] == '' ? NULL : $field[6]);
$field[7]= ( $field[7] == '' ? NULL : $field[7]);
$sql="INSERT INTO User_Mirror_Tbl (History_Record_ID, Employee_ID, Application_ID, User_Status, Record_Date, User_Name, User_Role, Last_Signon, UserKeyString)
VALUES
('$field[0]','$field[1]','$field[2]','$field[3]','$field[4]','$field[5]','$field[6]','$field[7]','$field[8]') ";
//insert record to database
if ($conn->query($sql) === TRUE) {
// echo "New record created successfully". PHP_EOL;
$record_number=$record_number+1;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
$record_number_err=$record_number_err+1;
}
}
}
echo $record_number.' Successful record and '.$record_number_err.' Unsuccessful record executed.';
$conn->close();
Sometimes you need to ignore the last line or lines of the csv. I set the number of ignore lines from the top as $start_offset and the number of lines to ignore from the bottom as $end_offset. Start with zero and increase until the offset error goes awayHere's how I do it:
$data = file_get_contents($filename);//load up csv
$data_array = explode("\n", $data);//break file into lines
$csv = array_map('str_getcsv', $data_array);//break up comma delimited
$csv_len = count($csv); //count of number of lines
$start_offset = 2;
$end_offset = 3;
for ($i=$start_offset; $i<$csv_len-$end_offset; $i++)
{
//access columns as $csv[$i][0], $csv[$i][1] etc
}

Select, Insert and Update MySQL table PHP script not working

I wrote the following code:
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
echo $result;
if ($result > 0) {
$result = $result + 1;
$sql2 = "UPDATE Eshop SET quantity = $result WHERE id = $insert";
if ($conn->query($sql2) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
} else {
$sql3 = "INSERT INTO Eshop (id, quantity) VALUES ($insert, 1)";
if ($conn->query($sql3) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
}
?>
What I want this script to do is select the quantity where the id is $insert and then if quantity > 0, add 1 to the quantity and update the quantity, if not insert the id and quantity = 1 into the table. The table has only two fields id(VARCHAR(32)) and quantity(DECIMAL(8,1)). I tried to do it more general in order to help as many people as possible. Could you please help me? Thanks in advance. NOTE: When I run the script in the browser(after uploading it to the server with the correct username,domain etc.) nothing shows up and I dont even get an error in the console.
You need to extract the result of your query and loop through each row:
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
while($row = mysqli_fetch_array($result)) {
if ($row['quantity'] > 0) {
$new_quantity = $row['quantity'] + 1;
$sql2 = "UPDATE Eshop SET quantity = '$new_quantity' WHERE id = '$insert'";
if ($conn->query($sql2) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql2 . "<br>" . $conn->error;
}
} else {
$sql3 = "INSERT INTO Eshop (id, quantity) VALUES ('$insert', 1)";
if ($conn->query($sql3) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql3 . "<br>" . $conn->error;
}
}
}
?>
<?php
$servername = "domain";
$insert = 12345678;
$username = "user";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT quantity FROM Eshop WHERE id = $insert";
$result = $conn->query($sql);
//check if particular record exists or not
$count=mysql_num_rows($result);
if($count>0) // if records exists for the particular id
{
while($row = mysqli_fetch_array($result)) {
if ($row['quantity'] > 0) {
$new_quantity = $row['quantity'] + 1;
$update = "UPDATE Eshop SET quantity = '$new_quantity' WHERE id = '$insert'";
if ($conn->query($update ) == TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $update . "<br>" . $conn->error;
}
} else {
$insert = "INSERT INTO Eshop (id, quantity) VALUES ('$insert', 1)";
if ($conn->query($insert ) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $insert . "<br>" . $conn->error;
}
} // else qty is <=0
} //end while
}
else {
echo "Records do not exists for that particular id";
}
?>

Categories