Hey guys im having a problem with a script im working on.
Im getting two errors and i dont understand why.
I do know that the csv file is csv comma delimited type.
Errors
Notice: Undefined variable: data in /home1/public_html/tickets/inv.php on line 17
Notice: Undefined offset: 7 in /home1/public_html/tickets/inv.php on line 20
Here is a link to my csv file: http://goo.gl/tcNNm1
//connect to the database
$connect = mysql_connect("*****","*********","*******");
mysql_select_db("don=_scanner",$connect); //select the table
//
$file = "rfl2.csv";
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO inv (stk, vin) VALUES
(
'".addslashes($data[7])."',
'".addslashes($data[8])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
I had this script working with a file i upload through a forum but im trying to make it load that one file when i request the page.
You're using the wrong kind of loop. $data will not be defined until after the FIRST iteration of the loop, because the $data = fgetcsv() will not be executed until the do/while's innards have been run once already.
You want
while($data = fgetcsv(...)) {
... database insert ...
}
instead
Plus, you are vulnerable to sql injection attacks. addslashes is utterly useless for protection against this. At least use the proper mysql_real_escape_string().
while(...) {...} - execute loop contents only if the condition is true
do {...} while(...) - execute loop contents at least once, terminate if condition is false
As the property of Do-While , it runs at least once. So at first iteration, $data variable is undefined. hence error!. Possible solution is do something like:
if(isset($data)) instead of if($data). or better go for while loop or for loop.
do this:
while(!feof($handle)){
$values = fgetcsv( $handle);
if(isset($values[0])){
add sql here..
}
}
Related
I'm trying to populate a mysql database with the contents of a .csv file using php. I'd like to do it using php code (no phpadmin). I consulted another thread on stackoverflow (populating database from csv file using php) but am still getting stuck. Here is my code:
$file = fopen("input.csv", "r");
while ($data = fgetcsv($file, $lineLength = 0, $delimiter = ",")) {
$added = "INSERT INTO Items VALUES(".$data.")";
if($connection->query($added) === TRUE) {
echo "Values successfully added!";
} else {
echo "Error inserting values: " . $connection->error;
}
Some context: earlier in the code, I create a database, connect to it, and create a table in the database. That part works fine. I just get an error when I try to populate the database from a .csv file. Here is the error message I get:
Notice: Array to string conversion in C:\xampp\htdocs\assignment8\init.php on line 64
Error inserting values: Unknown column 'Array' in 'field list'
I get this message 12 times, which corresponds with the number of rows in the .csv file I'm trying to import. "Line 64" corresponds with the line in my code that starts with "$added = INSERT INTO..."
Any help or suggestions are greatly appreciated.
You have to access to your column in the array
If your csv is something like this
Inside your while, you can access the values like:
echo $data[0] // prints 'Value 1'
So you might want to do something like...
$added = "INSERT INTO Items VALUES(".$data[0].")";
I have searched for hours to try and find a simple answer to this query I am having. I'm very sure it is covered in many ways, by other answers at least partially. I need a clear answer specific to what I am doing because I'm having difficulty trying to put together an answer that works for me from a bunch of other differently formatted and structured questions/answers.
I have a form which is posting a range of results intended to be used as keys for a mysql lookup loop. This is working fine - my post results in a successful array. For example:
$payarr = $_POST['pay'];
print_r($payarr);
Results in:
Array ( [0] => 12 [1] => 7 [2] => 1 )
Which is good given that the I want to run a mysqli process select the rows where claim_id is each of the values in $payarr. I then want to use fputcsv to write each of these rows fully, into a CSV file that is uniquely named by the days date and time that this is all run.
I have fragments of code that don't work and my frustration at trying to cobble something together that does work is getting a bit nuts. Can someone please show me how to do this effectively?
At the moment my code looks like this (but fails miserably):
<?php
include ("../conf/dbconfig.php");
include ("../conf/funcs.php");
include ("../conf/privs.php");
if($privs == 500) {
$view = $_POST['view'];
$payarr = $_POST['pay'];
$ts = date('Ymd-His');
print_r($payarr); //Testing to make sure our array to select from has arrived here ok.
//ob_start();
$fp = fopen('../csv/ResultsFile_'.$ts.'.csv', 'w');
foreach($payarr as $val) {
$result = mysqli_query($con, "'SELECT * FROM claims' WHERE claim_id='$val'");
//$row = mysqli_fetch_array($result, MYSQLI_ASSOC);
while ($row = mysqli_fetch_array($result)) {
echo $payarr;
echo $val;
//fputcsv($fp, $row);
print_r($row);
}
}
fclose($fp);
// return ob_get_clean();
} else {
header("Location: http://www.google.com.au/");
die;
}
?>
I'm willing (and happy) to rewrite the entire thing just as long as it works, so any help and suggestions are very appreciated!
Thanks in advance.
BTW - The $view value is not important in this process but is here as it will be passed back to the resulting header once this all works.
A few rough suggestions (you may need to adapt):
1) Change your query to use IN for the possible values, so you only have to execute one DB query:
$result = mysqli_query($con, "SELECT * FROM claims WHERE claim_id IN (" . implode(",",$payarr) . ")");
2) Make sure you are actually getting a DB result, instead of just assuming:
if(!$result || mysqli_num_rows($result) == 0) {
die("We didn't get any results from the DB!"); // Obviously you'll want better error handling
}
3) Now you can open your file, knowing that you need it. Make sure to verify it worked, since you could easily hit a permissions issue:
$fp = fopen('../csv/ResultsFile_'.$ts.'.csv', 'w');
if(!$fp) {
die("We couldn't open the CSV file for writing, check permissions!"); // Obviously you'll want better error handling
}
4) Now loop through your DB results and store them:
while ($row = mysqli_fetch_array($result)) {
fputcsv($fp, $row);
}
5) Does your CSV file need a header row? If so change mysqli_fetch_array() to mysqli_fetch_assoc() and stick this inside your loop:
while ($row = mysqli_fetch_assoc($result)) {
if(!isset($header)) {
$header = array_keys($row);
fputcsv($fp, $header);
}
fputcsv($fp, $row);
}
6) Only now should you close your file (in your code you do it inside the foreach loop):
fclose($fp);
7) Sanitize your $payarr. It could be as simple as:
$payarr = is_array($_POST['pay']) ? array_map('intval', $_POST['pay']) : array();
You may want to do more than that. But at least you're guaranteed to have an array with only integer values (and as long as you have no claim_id values of 0, it's harmless to have zeros in the array).
Hope that helps, at least track down where your code is failing.
I have a HTML select form filled by SQL Query using SELECT DISTINCT...
The idea is to not show duplicate values from database, and it's almost working, but in some case it's giving a problem. To fill the SQL columns I'm using a PHP reading a TXT file with delimiters and explode function. If I have in the TXT file 10 duplicate columns, on my HTML it shows 2, instead of only 1... And I note that 1 is with 9 of the entries from database, and the other one have 1 entry that is always the last line from TXT file.
Resuming: the last line of TXT file always duplicate on the HTML select form.
Checking the database, everything looks ok, I really don't know why it's duplicating always in the last one.
I told about the PHP that make the SQL entry because i'm not sure if the problem is in the PHP that contains the HTML select or in the PHP that fill the database... I believe that the problem is in the PHP with HTML select since I'm looking in the database and everything is ok. The SQL query in this php is like this:
<td class="formstyle"><select name="basenamelst" class="formstyle" id="basenamelst">
<option value="Any">Any</option>
<?
$sql = mysql_query("SELECT DISTINCT basename FROM dumpsbase where sold=0");
while($row = mysql_fetch_assoc($sql))
{
if($row['basename'] == "")
{
echo '<option value="'.htmlspecialchars($row['basename'], ENT_QUOTES, 'UTF-8').'">unknOwn</option>';
}
else
{
echo '<option value="'.htmlspecialchars($row['basename'], ENT_QUOTES, 'UTF-8').'">'.htmlspecialchars($row['basename'], ENT_QUOTES, 'UTF-8').'</option>';
}
}
?>
</select>
Remember: if I upload to database 10 duplicate columns, it shows 2 on select. One with 9 entries, and another with 1 entry (always the last line of my TXT file)...
Okay, many people told me to trim() the columns and it still showing duplicate... So I came to the conclusion that I have some issue while loading the TXT for database. Here is the code where I get the values to put on database:
$file = fopen($targetpath, "r") or exit("Unable to open uploaded file!");
while(!feof($file))
{
$line = fgets($file);
$details = explode(" | ", $line);
foreach($details as &$value) // clean each field
{
$value = mysql_real_escape_string($value);
if($value == "")
{
$value = "NONE";
}
}
unset($value);
mysql_query("INSERT INTO dumpsbase VALUES('NULL', '$details[0]', '$details[1]', '$details[2]', '$details[3]', '$details[4]', '0', '$price', 'NONE', now(), 'NONE', 'NONE')") or die ("Uploading Error!");
It sounds to me like the error is when you are populating the table from the file, and that one of the values is ending up subtly different to the others.
The fact that it's the last line that differs makes me wonder if there are newline characters being included in each value (except that last line).
If this is the case, you should be able to correct it by running trim() or similar in your DB.
[Edit] Ideally, you want to do this as early as possible, i.e. correct the data rather than remembering it's wrong when you access it. If you can't find why the initial import is messing it up, you could correct the data immediately afterwards with UPDATE dumpsbase SET basename = TRIM(basename)
Try changing your query to the following:
SELECT DISTINCT TRIM(basename) FROM dumpsbase WHERE sold=0
Hope this helps.
I want to loop multiple times through my query results, and I have 2 ways in mind:
1-
while($data = mysql_fetch_array($res , MYSQL_ASSOC)
{
array_push($new_arr , $data);
}
foreach($sites as $s){
foreach($new_arr as $d)
{
//some code
}
}
2-
foreach($sites as $s){
while($data = mysql_fetch_array($res , MYSQL_ASSOC)
{
//some code
}
mysql_data_seek($res,0);//set the pointer
}
My question: I think option 2 is more efficient but what if I lose connection to db during the mysql_fetch_array(option 2)? I get allot of results; this will take around 10-20 minutes. Will that affect the query results($res) or are they safe?
The data is mapped into a buffer assigned by the mysql client when you execute mysql_query() therefore losing the connection is irrelevant. The first method you cite will create a further copy of the data as a PHP array - which is not very efficient.
Also, WTF is the nested loop ($sites) doing? It looks like either your data is not mormalized or you've got a very bad algorithm.
I am using the sqlsrv driver for IIS so I can connect to a MS SQL server in PHP.
I've managed to convert a lot of my original mysql_ code and all going well, until I tried to SELECT some DateTime fields from the database. They were coming back as Date objects in PHP rather than strings, I found the fix which is adding this to the connection array:
'ReturnDatesAsStrings'=>1
Since doing that though my code is broken when trying to populate my recordset:
function row_read($recordset) {
if (!$recordset) {
die('<br><br>Invalid query :<br><br><bold>' . $this->sql . '</bold><br><br>' . sqlsrv_error());
}
$rs = sqlsrv_fetch_array($recordset);
return $rs;
}
The error is: sqlsrv_fetch_array(): 16 is not a valid ss_sqlsrv_stmt resource
There is such little amount of help on that error in Google so this is my only shot! I just don't get it.
row_read is called from within a While: while ($row = $db->row_read($rs)) {
Any ideas?
Just to add more code and logic - I do a simple SELECT of all my orders, then as it loops through them, I do another 2 SELECT's on the orders table then the customer table. It's falling down when I try these extra 2 'gets':
$this->db->sql = "SELECT * FROM TicketOrders";
$rs = $this->db->query($this->db->sql);
$this->htmlList->path("skin/search.bookings");
if ($this->db->row_count != 0) {
while ($row = $this->db->row_read($rs)) {
// Load the order row
$this->TicketOrders->get($this->db, $row['Id']);
// Load the customer row
$this->Customers->get($this->db, $row['CustomerId']);
Did you pass this resource variable by another function? If yes, you can try by executing the sqlsrv_query and executing sqlsrv_fetch_array in one function; don’t pass the ss_sqlsrv_stmt resource by another function. Hope that it will help.
Does your program involves a nested query function?
If so, the next question is: are you opening the same database in the inner query function?
Try these changes:
comment out the lines that open the database, including the { and } that enclose the function,
change the name of connection and array variables between the outer loop and the inner loop.
In other words, the outer loop may have:
$tring = sqlsrv_query($myConn, $dbx_str1);
while( $rs_row1 = sqlsrv_fetch_array($tring, SQLSRV_FETCH_ASSOC))
and the inner loop would have:
$tring2 = sqlsrv_query($myConn, $dbx_str2);
while( $rs_row2 = sqlsrv_fetch_array($tring2, SQLSRV_FETCH_ASSOC))
sqlsrv_fetch_array need a ss_sqlsrv_stmt resource. There must be something wrong with your SQL.