Jump to content

Search the Community

Showing results for tags 'csv'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (Dreamweaver, Zend, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

Found 18 results

  1. i was working on a mini project that imports csv file to the database through ajax and it's working fine <?php if(!empty($_FILES["marks_file"]["name"])) { $connect = mysqli_connect("localhost", "root", "", "dbname"); $output = ''; $allowed_ext = array("csv"); $extension = end(explode(".", $_FILES["marks_file"]["name"])); if(in_array($extension, $allowed_ext)) { $file_data = fopen($_FILES["marks_file"]["tmp_name"], 'r'); fgetcsv($file_data); while($row = fgetcsv($file_data)) { $name = mysqli_real_escape_string($connect, $row[0]); $Physics = mysqli_real_escape_string($connect, $row[1]); $Maths = mysqli_real_escape_string($connect, $row[2]); $Chemistry = mysqli_real_escape_string($connect, $row[3]); $Biology = mysqli_real_escape_string($connect, $row[4]); $SST = mysqli_real_escape_string($connect, $row[5]); $query = " INSERT INTO csv (name, Physics, Maths, Chemistry, Biology, SST) VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST') "; mysqli_query($connect, $query); } $select = "SELECT * FROM csv ORDER BY id DESC"; $result = mysqli_query($connect, $select); $output .= ' <table class="table table-bordered"> <tr> <th width="25%" >name</th> <th width="15%" >Physics</th> <th width="15%" >Maths</th> <th width="15%" >Chemistry</th> <th width="15%" >Biology</th> <th width="15%" >SST</th> </tr> '; while($row = mysqli_fetch_array($result)) { $output .= ' <tr> <td>'.$row["name"].'</td> <td>'.$row["Physics"].'</td> <td>'.$row["Maths"].'</td> <td>'.$row["Chemistry"].'</td> <td>'.$row["Biology"].'</td> <td>'.$row["SST"].'</td> </tr> '; } $output .= '</table>'; echo $output; } else { echo 'errorx'; } } else { echo "errory"; } ?> however the imported csv files inserts null values in the tables because the format of all csv files assigned to me are in the exact same format: ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,,,,,, ,,,Fields,Physics~75,Maths~50,Chemistry~65,Bio~85,SST~100 ,,,Name1,10,25,35,42,62 ,,,Name2,80,45,45,45,25 ,,,Name3,63,25,63,36,36 ,,,Name4,82,36,75,48,42 ,,,Name5,45,45,78,25,24 ,,,Name6,36,36,15,75,36 ,,,Name7,99,45,24,24,45 ,,,Name8,45,85,85,85,96 i changed my code a bit modified the functions to espace blank spaces and not return null values in the data tables while (($row = fgetcsv($file_data, 1000, ",")) !== FALSE) { if ((string) $row[0] != '0' and empty($row[0])) { continue; } $name = mysqli_real_escape_string($connect, $row[0]); $Physics = mysqli_real_escape_string($connect, $row[1]); $Maths = mysqli_real_escape_string($connect, $row[2]); $Chemistry = mysqli_real_escape_string($connect, $row[3]); $Biology = mysqli_real_escape_string($connect, $row[4]); $SST = mysqli_real_escape_string($connect, $row[5]); $query = " INSERT INTO csv (name, Physics, Maths, Chemistry, Biology, SST) VALUES ('$name', '$Physics', '$Maths', '$Chemistry', '$Biology' , '$SST') "; mysqli_query($connect, $query); } But it doesn't work with the specified csv files i think the ajax call breaks and that's why nothing happens.However it works fine with csv files without blank spaces
  2. After searching postings on multiple forums, I am officially now "Freaking OUT" trying to understand something that is probably very simple, but cannot seem to grasp. I simply want to read basic .csv data that is sent/uploaded directly to a PHP page, and to then append each record that shows up to a single .csv file on the server. The incoming data is supposed incoming via $_POST['csv'] ... at least that's what I was told. Each.csv record line being sent/uploaded is very simple (either single or multiple records in one small file): text1,text2,text3,text4,text5 For additional processing I know about 'explode', etc., but right now I am stuck even trying to do an 'echo' to display the simple incoming data "as is". One option I tried was: $postdata = file_get_contents("php://input"); echo $postdata; In the Java App monitoring I get the following after 3 records are sent/uploaded to the PHP URL: Server response status line: HTTP/1.1 200 OK I find this strange since I did not include... http_response_code(200); ... in the page code. Obviously, I do NOT know what I am doing here {SIGH}. Any assistance or guidance is appreciated. Thank you ! - FreakingOUT
  3. 0 What is the best way to store this data coming from the api into a csv file to later put into the db. Output: rank, level, xp, rank, level, xp, etc. This api produces about 60 rows of data per name ran and x that by about roughly 300 names that equals a lot of data. Pretty much with my current code I am pretty much creating a endless loop almost that would take a long time to execute so updating said data would be a nightmare i would think. Is there a way to accomplish the same thing without the loop or I am not sure how to go about this. My current code is a mess that much I know I am gonna be told. This code works, just not efficiently. I am thinking there may be a better way to do this. $query = $conn->prepare("SELECT name FROM users LIMIT 1"); $query->execute(); while($row = $query->fetch(PDO::FETCH_ASSOC)){ $name = $row['name']; $url = 'https://secure.runescape.com/m=hiscore/index_lite.ws?player='. $name . '';//api that the csv data is coming from $highscores = file_get_contents($url); $fields = array("Name", "Rank", "Level", "Xp");//this is to add the headers // for the csv files $implode1 = implode($fields, ",");//turn into csv format, not sure this is //even needed $implode1 .= "\n";/*this is to add a line break so that the explode below will properly put it into its own element*/ //otherwise data starts joining togather $extra_data = array("$name");/*This is to add the name that the data pertains too*/ $implode2 = implode($extra_data, ",");//turn into csv format $highscores = $implode1 . $implode2 . $highscores;//join as one array $highscores = explode("\n", $highscores);//turn each csv into an element of //its own element a bunch of unsets to remove unwanted data. Omitted them to condense the code $i = 1; header('Content-Type: text/csv'); header('Content-Disposition: attachment; filename="name.csv"'); $data = $highscores; $fp = fopen('highscores/' . $name . '.csv', 'wb'); foreach ( $data as $line ) { $val = explode(",", $line); fputcsv($fp, $val); } fclose($fp); The pdo part I was gonna include but the way I have it setup now wouldn't work. I was thinking that I would use mysql's LOAD DATA INFILE to insert the csv data to database. The end goal here is to be able to search for player stats and to use said data to keep track of xp earned during a xp competition. I PRAY that i have included enough info... I would really appreciate any feedback if possible.
  4. when i input this code it only uploads a single column into my database <html> <head> <title>MySQL file upload example</title> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> </head> <body> <form action="try2.php" method="post" enctype="multipart/form-data"> <input type="file" name="uploaded_file"><br> <input type="submit" name="submit"value="Upload file"> </form> <p> <a href="list_files.php">See all files</a> </p> </body> <?php $con=mysqli_connect("localhost","root","","book"); // Check connection if (mysqli_connect_errno()) { echo "Failed to connect to MySQL: " . mysqli_connect_error(); } if(isset($_POST['submit'])) { $fname = $_FILES['uploaded_file']['name']; $chk_ext = explode(".",$fname); if(strtolower($chk_ext[1]) == "csv") { $filename = $_FILES['uploaded_file']['tmp_name']; $handle = fopen($filename, "r"); while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')"; $result=mysqli_query($con,$sql) or die(mysql_error()); } fclose($handle); echo "Successfully Imported"; } else { echo "Invalid File"; } } ?> </html>
  5. I have a form that is populated by a CSV file, always 229 fields but anywhere up to 10 or 12 rows. The form populates correctly, but I'm having issues saving it all. The loop seems like it's missing something or maybe something is mismatched. Here is the form code: **page-confirm.php** $connect = mysqli_connect($server, $user, $pw, $db); if ($connect->connect_error) { die("Connection failed: " . $conn->connect_error); }else{ //echo'success!'; } if(isset($_POST['preview'])) { ini_set('auto_detect_line_endings', true); $file = $_FILES["file"]["tmp_name"]; $handle = fopen($file, "r"); $maxPreviewRows = PHP_INT_MAX; // this will be ~2 billion on 32-bit system, or ~9 quintillion on 64-bit system $hasHeaderRow = true; echo "<form method='post' action='/form-submit' >"; echo '<table>'; if ($hasHeaderRow) { $headerRow = fgetcsv($handle); echo '<thead><tr>'; foreach($headerRow as $value) { echo "<th>$value</th>"; } echo '</tr></thead>'; } echo '<tbody>'; $rowCount = 0; while ($row = fgetcsv($handle)) { $colCount = 0; echo '<tr>'; foreach($row as $value) { echo "<td><input name='row[".$rowCount."][".$colCount."]' type='text' value='$value' /></td>"; $colCount++; } echo '</tr>'; if (++$rowCount > $maxPreviewRows) { break; } } echo '</tbody></table>'; echo "<input type='submit' name='confirm' value='confirm'>"; echo '</form>'; } ?> Here's the code for the submission page with the insert loop: **page-formsubmit.php** $connect = mysqli_connect($server, $user, $pw, $db); if ($connect->connect_error) { die("Connection failed: " . $connect->connect_error); }else{ echo'success!'; } //var_dump($_POST); $sql = $inserts = $binds = []; foreach ($_POST['row'] as $rowValue){ if(is_array($rowValue) && count($rowValue) > 0 ){ foreach($rowValue as $rowData){ /*** * Stupidly, I had missed that row contains arrays * rather than values, so you need a foreach, inside the * foreach as so: ***/ foreach ($rowData as $columnKey => $columnValue){ //$columnValue will now equal $value //$columnKey will be the column number (1...229) /*** * This is the area you can construct your SQL query values. * db_connection is assumed to be setup. ***/ $sql[] = "`column_name_".$columnKey."`"; $binder = "value".$columnKey; $inserts[] = ":".$binder; $binds[$binder] = $columnValue; unset($binder); } unset($columnKey,$columnValue); } unset($rowData); /*** * This is the area the SQL query is set on a per row basis ***/ $sqlFull = "INSERT INTO staging (".implode(",",$sql).") VALUES(".implode(",",$inserts).")"; $connect->prepare($sqlFull); /*** * EDIT: bind param MUST come after the prepare call ***/ foreach($binds as $bindKey=>$bindRow){ $connect->bind_param(":".$bindKey, $bindRow); } unset($bindKey,$bindRow); var_dump($binds); $sql = $inserts = $binds = []; //reset arrays for next row iteration. /*** * db_connection then executes the statement constructed above ***/ $connect->execute(); } //close if. } unset($rowValue); ?> You can see in the submission page where I comment out the var_dump for post data. When it's active, it prints out this for the array: success!array(1) { ["row"]=> array(5) { [0]=> array(229) and continues printing the 229 elements for all 7 rows. There is something that's not quite working in this loop because even a debug statement within the loop to print the query won't work. I just need to make sure it iterates all 229 fields of every row to the end of the form and puts them into my staging table. My staging table, which is temporary, has 229 named fields in the exact order as the CSV, so I shouldn't have to declare each field I don't believe.
  6. ajoo

    CSV hinderance

    Hi all ! i have been trying to implement the CSV policy in my files. I have a bit of code that I am not sure how I can change it to suit the policy. Here's the code snippet : if(isset($_SESSION['msg'])) { // The script below shows the sliding panel on page load $script = ' <script type="text/javascript"> $(function(){ $("div#panel").show(); $("#toggle a").toggle(); }); </script>'; } As can be seen the script is loaded conditionally here. So how can I remove javascript embedded from this code so that this may be compatible with the CSV policy. NOTE: the javascript functions are in a separate js file loaded in the header. Thanks all !
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> <title>Import a CSV File with PHP & MySQL</title> </head> <body> <form action="" method="post" enctype="multipart/form-data" name="csv" id="csv"> Choose your file: <br /> <input name="csv" type="file" id="csv" /> <input type="submit" name="Submit" value="Submit" /> </form> </body> but i keep having this error Notice: Undefined index: csv in C:\wamp\www\youngsoul\upload\file.php on line 7
  8. Hi All, I have 4 tables each with only 2 columns (except for one that has 3) and they all have in common a date/time field. I am trying to export all 4 tables together as one CSV file and to have the records matched together where they have the same date/time. My tables are structured like so (which originally came from 4 individual CSV files): So as an exported CSV I would want the matching records (based on the date/time) to be part of the same record like so: Time, heartrateValue, Intensity, minutesleepValue, minutesleepLogId, steps 3/01/2018 0:01, 45, 0, 1, 17396451215, 0 3/01/2018 0:02, 45, 0, 1, 17396451215, 0 etc. A secondary issue is changing the date format to D/MM/YYYY from M/DD/YYYY. However, if I can get this CSV file export I can probably just loop through it in PHP and fix up the date format. Thank you kindly for your assistance
  9. I have a php script which runs a sql query and writes it to a CSV, which works perfectly. However, I created a second modified version of the script because I want to write the same CSV, but with an additional row beneath each group of data for totals. Currently, the results are ordered by User Extension (CSRs and phone numbers). So for extension 7200 I want, let's say, all 10 of their calls and then another row to total the calls and the individual columns. I currently have the query returning an 'x' for indicators. So one user might have 10 calls and 4 'x's in the 'inbound' column. I would want that to say 4. Anyway, I started the second version of the script to use an array to do this. The first problem is it's telling my fputcsv() expects parameter 1 to be resource. It looks like this could be an error for the type of array I'm using, but I'm not sure. I feel like I'm on the right track but I'm not familiar with using arrays and CSV files together like this. Any help is much appreciated. ```$result = mysqli_query($conn2, "SELECT DISTINCT firstn , lastn , extension , Recieved , RecievedKnown , Outbound , outboundKnown , Missed , MissedKnown , CallingNumber , CalledNumber , starttime , endtime , duration , HOLDTIMESECS , TERMINATIONREASONCODE FROM ( SELECT u.firstn , u.lastn , c.extension , CASE WHEN LEGTYPE1 = 2 AND ANSWERED = 1 THEN 'x' ELSE '' END AS Recieved , CASE WHEN LEGTYPE1 = 2 AND answered = 1 AND CALLINGPARTYNO = k.phone_number THEN 'x' ELSE '' END AS RecievedKnown , CASE WHEN ANSWERED = 1 AND LEGTYPE1 = 1 THEN 'x' ELSE '' END AS Outbound , CASE WHEN LEGTYPE1 = 1 AND FINALLYCALLEDPARTYNO = k.phone_number THEN 'x' ELSE '' END AS outboundKnown , CASE WHEN Answered = 0 THEN 'x' ELSE '' END AS Missed , CASE WHEN ANSWERED = 0 AND CALLINGPARTYNO = k.phone_number THEN 'x' ELSE '' END AS MissedKnown , a.CALLINGPARTYNO AS CallingNumber , a.FINALLYCALLEDPARTYNO AS CalledNumber , b.starttime AS starttime , b.endtime AS endtime , b.duration , a.holdtimesecs , a.terminationreasoncode FROM ambition.session a INNER JOIN ambition.callsummary b ON a.NOTABLECALLID = b.NOTABLECALLID INNER JOIN ambition.mxuser c ON a.RESPONSIBLEUSEREXTENSIONID = c.EXTENSIONID INNER JOIN jackson_id.users u ON c.extension = u.extension LEFT JOIN ambition.known_numbers k ON a.callingpartyno = k.phone_number WHERE date(b.ts) >= curdate() AND LEGTYPE1 <> 12 -- This keeps the report from having blank spaces due to the 12 legtype. AND c.extension IN (7276,7314,7295,7306,7357,7200,7218,7247,7331,7255,7330,7000,7215,7240,7358,7312) ) x ORDER BY lastn") or die(mysqli_error( $conn2)); $userDetails = array(); while ($row = mysqli_fetch_assoc($result)){ $userDetails[] = $row; $extension = $row['extension']; if(!isset($userDetails[$extension])){ $userDetails[$extension]['missedCallCounts'] = 1; /* First time count */ }else{ $userDetails[$extension]['missedCallCounts'] += 1; /* Sum up the count */ } } echo $userDetails; $fp = fopen('TESTCSV.csv', 'w'); foreach($userDetails as $userDetail){ /* In the following line dump the respective userdetails to csv which will show summary */ fputcsv($fp, array_values($userDetails)); }```
  10. Hi guys, What I'm trying to accomplish sounds like fairly easy task but due to my poor knowledge of php this turned to be quite a challenge. What I'm trying to do is to make a php script that will search the keywords on the multiple websites. Websites that I will search are all web shops, selling spare part for home appliances and keywords used are usually original spare part codes. When searching, script is searching these websites using their own search functions and not Google or other search engines. Input for this script should be a CSV file containing list of keywords and URLs of the web shops that needs to be search for all these keywords. Here is the example: http://prntscr.com/4ebhxh Script should perform like this: It picks up the 1st keyword, browse to the URL1, uses its search, searches for the product, if it finds it, copy its price and write it back to original input CSV. If it doesn't find match (search results appear empty) it should write "no match found" and continue to URL2, URL3 and so on... When all URLs from the list are checked for the 1st keyword, scripts picks up 2nd keyword and continues on through all these keywords are not checked. This would be a resulting CSV file after the 1st keyword is checked: http://prntscr.com/4ebj52 After all data from the input CSV file are processed, script should prompt a msg and create a download link for that CSV file to be downloaded. If there are multiple matches, in other words if for one keyword some of the website searches find 2 or more products, something like "More then one match" should be written in the file. Example: http://prntscr.com/4ebkcx Please note that non of the website is using SSL and non of them requires login in order to display the prizes. This fact should make this script easier to build. Its not important for this script to run fast (its better I think to run it with some timeouts because of the server glitches and bottlenecks). What is more important is to make it automatic so one can start it over the night, over the weekends. Number of the URLs would be around 10, and list of keywords from few tens, to a few hundred. If I can provide some additional clarification and info I'm available. Of course I would be willing to pay someone to help me accomplish this task. Cheers Dean
  11. I'm trying to after submission 1. create a csv 2. insert record into db 3. send email that's created in form submission - $msg. 4. send email with attachment to only the email I specify (if possible) if not attach it to the email that's created at submission. I've search and search and found different methods but doesn't work with my code. I kept 3 lines at the top but can't get them to work ... either I don't get an email after submission or don't get an attachement. Can some one help? <?php $random_hash = md5(date('r', time())); $csvString = "..."; // your entire csv as a string $attachment = chunk_split(base64_encode($csvString)); $to = "email@email.com"; if(isset($_POST['submit'])) { // VALIDATION if(empty($_POST['firstName'])) { "First Name Required"; } if(empty($_POST['lastName'])) { "Last Name Required"; } if(empty($error)) { $to = "$to"; $subject = 'The Form'; $headers = "MIME-Version: 1.0 \r\n"; $headers .= "Content-Type: text/html; \r\n" ; $msg .="<html> <head></head> <body> <table width='100%' cellspacing='0' border='0' cellpadding='0'> <tr><td> <table width='100%' cellspacing='0' border='0' cellpadding='0'> <tr><td>This is the email sent.</td></tr> </table> </body> </html>"; include('con.php'); $con = mysqli_connect($host,$user,$pass,$dbName); if (!$con) { die('Could not connect: ' . mysqli_error($con)); } mysqli_select_db($con,"thetable"); $firstName = mysqli_real_escape_string($con, $_POST['firstName']); $lastName = mysqli_real_escape_string($con, $_POST['lastName']); $sql = "SELECT * FROM thetable WHERE `firstName` = '{$firstName}' OR `lastName` = '{$lastName}'"; $result = mysqli_query($con,$sql); if(($result->num_rows)>= 1) { $theerror = "You exist"; } else { $sql="INSERT INTO thetable(firstName, lastName) VALUES ('$_POST[firstName]','$_POST[lastName]'"; $success = "Sent ... Insert it!!!"; if (!mysqli_query($con,$sql)) { die('Error: ' . mysqli_error($con)); } $result = @mail($to, $subject, $msg, $headers); } mysqli_close($con); { } } } ?>
  12. cobusbo

    getting info from csv file

    Hi Ive currently developed a script that connects via an API to send a message, and tested it with one user and it works perfectly. But now im bit stuck to send it to multiple users. All my visitors unique IDs are being stored into a file called unique.csv all in 1 column under each other. But what im currently trying to do is to recall the info from the csv and make a contact list to broadcast the message to. The csv file looks like: Here is my current script <?php $f_pointer=fopen("unique.csv","r"); // file pointer while(! feof($f_pointer)){ $ar=fgetcsv($f_pointer); } require_once ('MxitAPI.php'); /* Instantiate the Mxit API */ $key = '****'; $secret = '*****'; $visitor = '****'; $api = new MxitAPI($key, $secret); $api->get_app_token('message/send'); $api->send_message('guniverse', '$ar[0]', '*test message*', 'true'); echo 'Success'; ?>
  13. Hi all, PHP newbie here. I've been trying to integrate Gravity Forms with Gravity View's Import Entries from CSV plugin. Unfortunately, it needs a bit of tweaking to get everything connected properly. I used a code snippet from David at Gravity Whiz, (HERE) that gets integrated into my Wordpress site's functions.php file, and have been trying to customize to to suit my needs. From what I understand in looking at the code, the only bit I need to tweak (I think) is the bottom portion: # Configuration new GW_Value_Exists_Validation( array( 'target_form_id' => 1, 'target_field_id' => 3, 'source_form_id' => '/RSVPcodes.csv', 'source_field_id' => 'rsvp', 'validation_message' => 'Hey! Don\'t be a villain! Provide a legit RSVP code to reserve your spot at the Smackdown.' ) ); My main question here: how to get the validation code to see the database that I've uploaded via the Import Entries plugin? I know ignorance is making me miss something that should be pretty simple. Right now, I've got it to validate a test word that I know is not in my database, and also a code that I know is in the database. It's coming back with both items as not valid. The end result will be a RSVP form that will be used to accept RSVPs only from people who have an RSVP code from their invitation, a lot like a license key validation system. The live site (and form I'm trying to tweak) is HERE. Thanks in advance for any help.
  14. kimjessen

    explod csv file

    Hello yes so I let myself be carried away, and then came a new small challenge. In the graph code is the csv file opened and soteret with a "explod" function. and it work fine as long as I only have one column with y data and one with x data. but when I start to get more column's it does not work. I've created a short example below. <?php define("LOG_FILE", "./data/test111/test111-2015-01-17.csv"); $times = array(); $values = array(); $values_test1 = array(); $file_lines = file(LOG_FILE , FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES); foreach($file_lines as $line_num => $line_value) { $line_elements = explode(",", $line_value); $times[] = date($line_elements[0]); $values[] = $line_elements[1]; $values_test1[] = $line_elements[2]; } echo $values[2]; ?> the control echo I make "echo $values[2];" works fine, there is be the expected value. but if I try to "echo $values_test1[2];" so there is nothing. the CSV file looks like this. Date,temp1,temp2 2015-01-23-12-00,54,59 2015-01-23-12-01,54,59 2015-01-23-12-02,54,59 2015-01-23-12-03,54,58 2015-01-23-12-04,54,58 2015-01-23-12-05,54,58 2015-01-23-12-06,54,58 2015-01-23-12-07,54,58 2015-01-23-12-08,54,58 2015-01-23-12-09,54,58 2015-01-23-12-10,54,58 2015-01-23-12-11,53,58 2015-01-23-12-12,53,58 2015-01-23-12-13,53,58 2015-01-23-12-14,53,58 why can I not get the temp2 values into $ values_test1 [] thank you very much
  15. I have multiple CSV files (example file.csv) that need to be read, and the data needs to be compared to the data in another csv file (data.csv) by an ID key which is in the first column of the file There are multiple rows and columns with data. First rows of the file is header column info so the first row needs to be skipped the data which is in the selected row of the file (file.csv) needs to be compared to data in data.csv by the ID key when the same ID key is found in a row, the data needs to be appended to the end of the row of that same ID key row in data.csv (everything except the ID key is copied to file.csv) CSV files are delimited by ; data is UTF-8 - Croatian I've made a script to parse through a file (data.csv) and print it but ain't that good with working multiple files and arrays to make it check the data from file.csv and append it...help? <?php $row = 1; if (($xxa = fopen("data.csv", "r")) !== FALSE) { echo "<meta charset=\"UTF-8\">"; while (($data = fgetcsv($xxa, 1000, ";")) !== FALSE) { if ($row==1) { $row++; continue; } $num = count($data); echo "<p>$row. <i>red: <br /></p>\n"; $row++; for ($c=0; $c < $num; $c++) { echo $data[$c] . "</br>\n"; } } fclose($xxa); } ?> ----- I've googled and found this other script online (other.php) which is awesome because it puts all the data in arrays but I have no idea how to select that first cell with an ID key in one file, and copy that row and append it to another csv file at the end of that ID key row :/ <?php /** * Convert a comma separated file into an associated array. * The first row should contain the array keys. * * Example: * * @param string $filename Path to the CSV file * @param string $delimiter The separator used in the file * @return array * @link http://gist.github.com/385876 * @author Jay Williams <http://myd3.com/> * @copyright Copyright (c) 2010, Jay Williams * @license http://www.opensource.org/licenses/mit-license.php MIT License */ function csv_to_array($filename='', $delimiter=',') { if(!file_exists($filename) || !is_readable($filename)) return FALSE; $header = NULL; $data = array(); if (($handle = fopen($filename, 'r')) !== FALSE) { while (($row = fgetcsv($handle, 1000, $delimiter)) !== FALSE) { if(!$header) $header = $row; else $data[] = array_combine($header, $row); } fclose($handle); } return $data; } /** * Example */ print_r(csv_to_array('example.csv')); ?>
  16. i want a situation where, when i upload something into my database, it creates a new table, everytime, i saw this $forum = "CREATE TABLE IF NOT EXISTS for_".$id." ( `id` int(11) NOT NULL AUTO_INCREMENT, `stud` int(11) DEFAULT NULL, `course` int(11) DEFAULT NULL, `message` varchar(1000) DEFAULT NULL, PRIMARY KEY (`id`) ) "; but don't know how to implement it into this query $sql = "INSERT into data(name,Groups,phone_number) values('$data[0]','$data[1]','$data[2]')";
  17. Background: I work on an application that tracks server information. The data comes from 10 tables in a database that are exact replicas of 10 CSV files that insert daily into their specific tables. The database is nowhere near normalized and is a straight dump from the CSV to the db tables. (CSV headers match the table fields) Problem: I need to figure out a way to get the data from the CSV data into a normalized database for the application to read instead of a straight dump of the CSV data to the table. I have little control over the CSV's, but do have control over what happens with them afterwards. What would be the best way to get logical data into a normalized database from a set of CSV's? Thanks!
  18. Hi I have a script which picks up CSV files and inserts into a table (mysql). I am a beginner and finding it difficult to get the script to add an additional column to existing CSV, and add value to column, for each row... Here is the script.... How can I manipulate $csv and add a column (including separator) and value ($filedate) for each row? Help much appreciated. for example: CSV contains: Number, Name, LastName 1, John, Thomas 2, Jeffrey, James I need to add: Number, Name, LastName, Date 1, John, Thomas, 2014-10-31 2, Jeffrey, James, 2014-10-31 <?php #! /usr/bin/env php $databasehost = "localhost"; $databasename = "****"; $databasetable = "****"; $databaseusername="****"; $databasepassword = "****"; $fieldseparator = ","; $lineseparator = "\n"; $files = glob("*ETF_*.csv"); $filedate = "2014-10-31"; if (empty($files)) { die("No records were loaded."); } else foreach($files as $csv) $etf_array = array( PDO::MYSQL_ATTR_LOCAL_INFILE => true, PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION); { try { $pdo = new PDO("mysql:host=$databasehost;dbname=$databasename", $databaseusername, $databasepassword, $etf_array ); } catch (PDOException $e) { die("database connection failed: ".$e->getMessage()); } $affectedRows = $pdo->exec(" LOAD DATA LOCAL INFILE ".$pdo->quote($csv)." INTO TABLE `$databasetable` FIELDS TERMINATED BY ".$pdo->quote($fieldseparator)." LINES TERMINATED BY ".$pdo->quote($lineseparator)." IGNORE 1 LINES"); echo "Daily - Loaded a total of $affectedRows records from $csv.\n"; } ?>
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.