I'm looking at an odd issue with Internet Explorer 9. The below code successfully generates a populated CSV file when ran in Safari, IE8, IE10, IE11, Chrome and Firefox but generates an empty CSV file (Headers only) in IE9. It does not appear to be a data issue considering the bug only appears to happen in IE9. I've been able to test and confirm on 3 different machines running IE9.
It's a legacy script I inherited with SQLSRV instead of MSSQL PDO, though I took the liberty of scooping out mysql and replacing it with PDO and wrapping it in a function and thoroughly commenting it for my own sanity.
# Create a CSV sheet with details we need
# Generate file name based on timestamp
$file = "$_SESSION[user_name]_" . "tutorincomplete_" . date("Y-m-d_H-i-sa");
# 1: Open CSV File
$myFile = ".\csv\\" . "$file.csv";
$fh = fopen($myFile, 'w') or die("can't open file");
# Get list of active classes from MSSQL DB
$sql = "SELECT DISTINCT
static_title,
LEFT(CONVERT(VARCHAR, course_end_date, 120), 150) AS course_end_date,
RTRIM(static_code) as static_code,
RTRIM(session_code) as session_code,
staff_name
FROM
snip";
# Append to query where a school is present
if (ISSET($_SESSION['user_school']) AND $_SESSION['user_school'] != "None")
{
$sql .= "
WHERE
school = ?
ORDER BY staff_name ASC";
$params1 = array($_SESSION['user_school']);
$query = sqlsrv_query($conn, $sql, $params1);
}
else
{
if (isset($_POST['school']) AND $_POST['school'] != "All") {
$sql .= "
WHERE
school = ?
ORDER BY staff_name ASC";
$params1 = array($_POST['school']);
$query = sqlsrv_query($conn, $sql, $params1);
} else {
$sql .= "
ORDER BY staff_name ASC";
$query = sqlsrv_query($conn, $sql);
}
}
$today = date('U');
# Set headers for CSV file
$head = array("Static title", "Course end date", "Static code", "Session code", "Staff name");
fputcsv($fh, $head);
$count = 0;
# Loop through MSSQL results for comparison
while ($obj = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC))
{
$finish = $obj['course_end_date'];
# Strip the time (keep ISO date format intact)
$finishSub = substr($finish, 0, 10);
# Create timestamp from date format
$finishTs = strtotime($finishSub);
# Compare and display <option> tag if valid
if ($today > ($finishTs - 604800))
{
# Fetch information on course; Decide of course is complete or incomplete
# To do this, first check for course entries in the MySQL database
# If they are present, we will use MySQL instead of MSSQL (To reference completed courses)
$sql3 = "SELECT * FROM snip WHERE static = :stc AND session = :sec ORDER BY static ASC";
$query3 = $pdo->prepare($sql3);
$query3->bindParam(':stc', $obj['static_code']);
$query3->bindParam(':sec', $obj['session_code']);
$query3->execute();
$rowCount = $query3->rowCount();
# Check for result count in MySQL
if ($rowCount > 0)
{
$result = $query3->fetch(PDO::FETCH_OBJ);
if ($result->complete == 0) {
$incomplete = 1;
} else {
$incomplete = 0;
$count++;
}
} else {
# No MySQL entry; Mark as incomplete
$incomplete = 1;
}
if ($incomplete > 0)
{
$arr = array($obj['static_title'], $obj['course_end_date'], $obj['static_code'], $obj['session_code'], $obj['staff_name']);
fputcsv($fh, $arr);
}
}
}
echo "
<h1>CSV file generation complete</h1>
<p>Skipped $count classes</p>
<p>File generation complete. File name $file.csv Click here to open</p>";
}
In anything but IE9, it generates "Skipped X classes", CSV file has x number of entries.
But in IE9, "Skipped 0 classes", CSV file only contains column headers.
EDIT: I found out through some experimentation that SQLSRV is passing an empty array ONLY in IE9. It's not affecting any other browser. As such I was able to impress upon the powers that be that I need to switch the system to PDO for MSSQL. Guess I can call this fixed but unresolved.
Related
This question already has answers here:
How to pop an alert message box using PHP?
(9 answers)
Closed 1 year ago.
I have an online software that use php, html, js and MySQL as database.
I have two tables:
1- First table contains [name, imei, object_expire, object_expire_dt] - gs_objects
2- Second table contains [object_id, user_id, imei] - gs_user_objects
The code should be done in php where the user_id is got from the session, then the first query should get the imeis that matches the user_id from second table then it should get the expire date 'object_expire_dt' of each imei from the first table
after that it should check if there is an expire date that will expire within 20 days, if true, it should show alert message
Here is incomplete code that I tried to do
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."' ORDER BY `object_id` ASC";
$r2 = mysqli_query($ms, $q2);
while($row=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row['object_expire_dt'] > date('Y-m-d', strtotime($Date_e. ' - 20 days')))
{
alert("You have objects are going to expire soon");
}
}
}
the code didn't work, I need some help in it.
Thanks in advance
Here's how all this works: Your php program runs on your server, and accesses your database on the server. The purpose of your php program is to create programs to run on your users' browsers. Those programs written by php use the HTML, Javascript, and CSS languages.
If you want something to happen in a user's browser (like an alert box) that thing has to appear in a Javascript program written by your php program and sent to the browser. php doesn't have its own alert() function
Here's an easy, but somewhat sloppy, way to do that in your php program.
echo "<script type='text/javascript'>window.onload=function(){alert('$msg'))</script>";
What's going on here?
echo tells php to write its parameter to the html page
<script> whatever </script> is the way to embed Javascript in html
window.onload = function () { whatever } tells the browser to run a Javascript function when your html page finishes loading.
alert(message), in the function, pops up the alert message.
When you're troubleshooting this kind of thing, View Source ... is your friend.
you can use alert in javascript not in php
also you should use prepared statement.
//notification for objects expiration
checkUserSession();
loadLanguage($_SESSION["language"], $_SESSION["units"]);
// check privileges
if ($_SESSION["privileges"] == 'subuser'){
$user_id = $_SESSION["manager_id"];
}else{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM gs_user_objects WHERE user_id = ? ORDER BY object_id ASC";
if ($r = $connection->prepare($q)) {
// if user_id contains string and is not integer you must use "s"
$r->bind_param("i",$user_id);
if ($r->execute()) {
$result = $r->get_result();
// check if result match one condition
if ($result->num_rows > 0) {
echo "result found";
while ($row = $result->fetch_assoc()) {
echo $row['some_column_name'];
}
}
}
}
Thanks Nikolaishvili and Jones,
Your answers helped me a lot I needed more edit on the if statements,
I did the code and the result is as I expected and it is online now, here the code is below so others can check it
//notification for objects expiration
// check privileges
if ($_SESSION["privileges"] == 'subuser')
{
$user_id = $_SESSION["manager_id"];
}
else
{
$user_id = $_SESSION["user_id"];
}
$q = "SELECT * FROM `gs_user_objects` WHERE `user_id`='".$user_id."' ORDER BY `object_id` ASC";
$r = mysqli_query($ms, $q);
$expiry_flag = 0;
$inactive_flag=0;
while($row=mysqli_fetch_array($r))
{
$q2 = "SELECT * FROM `gs_objects` WHERE `imei`='".$row['imei']."'";
$r2 = mysqli_query($ms, $q2);
while($row2=mysqli_fetch_array($r2))
{
$Date_e = date("Y-m-d");
if ( $row2['object_expire_dt'] < date('Y-m-d', strtotime($Date_e. ' + 20 days')))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$expiry_flag = 1;
}
}
if ( $row2['object_expire_dt'] < date("Y-m-d"))
{
if ($row2['object_expire_dt'] > '0000-00-00')
{
$inactive_flag = 1;
}
}
}
}
if ($expiry_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg1")';
echo '</script>';
}
if ($inactive_flag == 1)
{
echo '<script type="text/javascript">';
echo ' alert("my msg2")';
echo '</script>';
}
Thanks
I wrote an import snippet to populate my Neo4J DB with nodes for towns and related to them counties. The code looks like
<?php
function readCSV($csvFile){
$file_handle = fopen($csvFile, 'r');
$lineCount=0;
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024, ';', '"');
$lineCount++;
}
fclose($file_handle);
return array($line_of_text,$lineCount);
}
// Create an Index for Town and for Country
$queryString = '
CREATE INDEX ON :Country (name)
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString);
$result = $query->getResultSet();
$queryString = '
CREATE INDEX ON :Town (name)
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString);
$result = $query->getResultSet();
// Set path to CSV file
$importFile = 'files/import_city_country.csv';
$completeResult = readCSV($importFile);
$dataFile = $completeResult[0];
$maxLines = $completeResult[1];
for ($row = 1; $row < $maxLines; ++ $row) {
$countryData = array();
if(!is_null($dataFile[$row][0]))
{
// Define parameters for the queries
$params =array(
"nameCountry" => trim($dataFile[$row][0]),
"nameTown" => trim($dataFile[$row][1]),
"uuid" => uniqid(),
);
# Now check if we know that country already to avoid double entries
$queryString = '
MATCH (c:Country {name: {nameCountry}})
RETURN c
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
if(COUNT($result)==0) // Country doesnt exist!
{
$queryString = '
MERGE (c:Country {name: {nameCountry}} )
set
c.uuid = {uuid},
c.created = timestamp()
RETURN c
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
}
# Now check if we know that town already
$queryString = '
MATCH (t:Town {name: {nameTown}})
RETURN t
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
if(COUNT($result)==0) // Town doesnt exist!
{
$queryString = '
MERGE (t:Town {name: {nameTown}} )
set
t.created = timestamp()
RETURN t
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
// Relate town to country
$queryString = '
MATCH (c:Country {name: {nameCountry}}), (t:Town {name: {nameTown}})
MERGE (t)-[:BELONGS_TO]->(c);
';
$query = new Everyman\Neo4j\Cypher\Query($client, $queryString,$params);
$result = $query->getResultSet();
}
} // Excel Last Line is not Null - go on
} // Next Row
?>
A typical CSV line looks like
Country City
Albania Tirana
This all works fine - but it takes more than 30 minutes on a pc to import 9.000 lines. I know the system needs to check each record if already existing and also do a relation between town and country but it seems quite long though for such an amount of CSV-lines.
Do you have maybe suggestions how to improve the import code?
Thanks,
Balael
BTW: Any chance to insert here code without editing every row and adding 4 spaces - kinda boring for longer code.....
Use LOAD CSV inside of the neo4j-shell if at all possible, and don't write your own code to process the CSV.
What this will do for you primarily is to allow you to batch many items into a single transaction USING PERIODIC COMMIT.
If you want to use the REST API remotely (as I assume you're doing here) then look into your language binding's support for batch operations. Your code as written is going to spend a lot of time going back and forth to the server, probably turning each line of the CSV into a request/response, which will be slow. Better to batch up many at a time and run them as one operation, which will help minimize how much protocol overhead you have.
I have php code with two queries. One is in an Oracle database, with the result being about 100 rows of data (within the data there are SKU numbers). The other is in a mysql database with about 30 rows of data (with the data there are also SKU numbers).
I need to compare each SKU in the first query to the second query, line by line. If the SKU in the first query also appears in the second query, then I need it to echo the SKU.
All SKUs in the second query are in the first query, so I would expect the result to echo all 30 SKUs, but it does not. Depending on how I change the syntax, it echos 17 rows, 100 rows, or no rows at all.
It's worth noting that both queries work fine. The Oracle query is insanely long and has a lot of sub-queries in it, so I will not include that full query below. The Oracle query returns the results perfectly in SQL Developer, and the MySQL query returns the results perfectly in HeidiSQL. Both queries have been tested and echoed as tables in other php files to make sure that they were working fine.
Below is what the php file that I am trying to fix looks like so far;
<?php
$conn = oci_connect($user, $pswd, $hst);
$sql = oci_parse($conn,"[Really long Oracle Query]");
while ($row = oci_fetch_assoc($sql))
{
$sku = $row['SKU'];
$con = mysql_connect("[database host]", "[database user]", "[database password]");
mysql_select_db("[database_name]");
$sqls = "SELECT * FROM [table_name] WHERE [this_date_column] BETWEEN
DATE_SUB(NOW(), INTERVAL 14 DAY) AND NOW()";
$result = mysql_query($sqls);
$mailer = NULL;
while($rows = mysql_fetch_assoc($result))
{
$m_sku = $rows['sku'];
if ($m_sku == $sku)
{
$mailer == 'false';
}
}
if ($mailer == 'false')
{
echo $m_sku;
echo "<br>";
}
}
?>
Again; there are only 30 SKUs in the MySQL query, but over 100 SKUs in the Oracle query. All SKUs in the MySQL query are definitely in the Oracle query.
Anyone see what I am doing wrong?
Thanks in advance,
-Anthony
You have basic sintacsis errors:
= is used to assign values
== compares 2 variables (not counsidering there type *)
=== compares 2 variables including there types.
your code should look something like this:
while($rows = mysql_fetch_assoc($result))
{
$m_sku = $rows['sku'];
if ($m_sku == $sku)
{
$mailer = false; // == is for comparison, = is for assign
}
}
if ($mailer === false)
{
echo $m_sku;
echo "<br>";
}
if($member == 'false'){...}
when 'false' is compared with == to a falsefull value (0, null, false, array(), '') .. it will NOT be mach it as it is parsed as a "not empty string" so it is not falsefull .
Here is your code with the MySQL connect moved outside the loop and the == assignment fixed.
<?php
//Connect to databases
$oracle = oci_connect($user, $pswd, $hst);
$mysql = mysql_connect("[database host]", "[database user]", "[database password]");
mysql_select_db("[database_name]");
//Get rows from Oracle
$oracle_result = oci_parse($oracle, "[Really long Oracle Query]");
$oracle_rows = array();
while ($row = oci_fetch_assoc($oracle_result)) $oracle_rows[] = $row;
//Get rows from MySQL
$mysql_sql = "SELECT * FROM [database_name] WHERE this_date_column BETWEEN
DATE_SUB(NOW(), INTERVAL 14 DAY) AND NOW()";
$mysql_result = mysql_query($mysql_sql);
$mysql_rows = array();
while ($row = mysql_fetch_assoc($mysql_result)) $mysql_rows[] = $row;
foreach ($oracle_rows as $oracle_row) {
$oracle_sku = $oracle_row['SKU'];
foreach ($mysql_rows as $mysql_row) {
$mysql_sku = $mysql_row['sku'];
$mailer = null;
if ($mysql_sku == $oracle_sku) {
$mailer = false;
echo $mysql_sku . "<br>";
}
}
}
I've been a lot around this site the last couple of days, and found a lot of useful tips for a newbie to php as I am (this is my second day :) ) Therefore I'll sure hope you gurus can help me finishing this script.
What do I have:
I have this table within my Mysql:
------------------------------![Sql Tabels][1]
----------------------
Would should it do:
The script have to get some table rows where the "diemensions" field is emty IS NULL
Now the script have to find the image size and spit it out in this format widthxheight the x between the width and height is important.
Where the image is not to be grabt, it should just pass by, and take the next one.
When it's done:
It have grabt the image size and updated the "dimensions" field in the DB
Sources for my code:
How to determine the picture size, then selectively insert into the database? php
Update MySql Field (if field is not empty, go to next one)
http://dk1.php.net/manual/en/function.getimagesize.php
The PHP it self
<pre><code>
<?php
# first we check, if gd is loaded and supports all needed imagetypes
function gd_get_info() {
if (extension_loaded('gd') and
imagetypes() & IMG_PNG and
imagetypes() & IMG_GIF and
imagetypes() & IMG_JPG and
imagetypes() & IMG_WBMP) {
return true;
} else {
return false;
}
}
$username = "";
$password = "";
$database = "";
$db_hostname = "";
mysql_connect("$db_hostname","$username","$password") or die(mysql_error());
mysql_select_db("$database") or die(mysql_error());
//check if the starting row variable was passed in the URL or not
if (!isset($_GET['startrow']) or !is_numeric($_GET['startrow'])) {
//we give the value of the starting row to 0 because nothing was found in URL
$startrow = 0;
//otherwise we take the value from the URL
} else {
$startrow = (int)$_GET['startrow'];
}
// Retrieve all the data from the "example" table
$result = mysql_query("SELECT * FROM tx_gallery_previews WHERE dimensions IS NULL ORDER BY gallery_id ASC LIMIT $startrow, 10") or die(mysql_error());
// store the record of the "example" table into $row
while($row = mysql_fetch_array($result)){
//$row = mysql_fetch_array($result))
$pid = $row['preview_id'];
$gid = $row['gallery_id'];
$imgfile = $row['preview_url'];
$dimens = $row['dimensions'];
/*
echo $row['gallery_id'];
echo $row['preview_url']. "\r\n<br />"; */
extract($row);
//print $pid. " ".$imgfile." ";
//print "".$dimens."<br />";
$blah = getimagesize("$imgfile");
$type = $blah['mime'];
$width = $blah[0];
$height = $blah[1];
if (isset($width)) {
echo $pid. " ".$imgfile." ".$width. "x".$height. "\n"."<br />";
mysql_query("UPDATE into tx_gallery_previews (preview_id,gallery_id,preview_url,dimensions) VALUES ($pid,$gid,$imgfile,$width."x".$height)
ON DUPLICATE KEY UPDATE dimensions=VALUES('"$width."x".$height"')");
}
else{ echo "$pid <img src=\"$imgfile\" width=\"90\">Image not found"."<br />"; }
}
// close connection
mysql_close($connection);
$prev = $startrow - 10;
//only print a "Previous" link if a "Next" was clicked
if ($prev >= 0)
echo 'Previous ';
//now this is the link..
echo 'Next';
?>
</pre></code>
Seen but couldn't make it work
http://dk1.php.net/manual/en/function.getimagesize.php
Post by "james dot relyea at zifiniti dot com 07-Feb-2009 08:49"
But seems to be the right ideer for my script.
XXXXXXXXXXXXXXXXX
When you answer this topic, please explane wich part does what.
Best Regards
Joakim
So here is what I am doing.
Read a row each in for loop. (Because all at once is going to take some resources since I am in a shared hosting.)
2.Get the right field data to a variable.
3.Manipulate the req datas dependant on the extracted field.
4.update the new fields where filed=extracted data.
Bit of addition, I am adding the current position to a file, so that the script can continue from there next time it is run.
Problem : It doesnt seem to work. The counter.txt gets values like 3-4, but it simply resides there. my db has like 1000k rows.
my code :
require ("dbconnect.php");
header("refresh:29;url=process.php"); // so it doesnt ever end. I cant use max_execution_time here for some reason.
$count = mysql_query("SELECT COUNT(*) FROM collection ");
$data = mysql_fetch_array($count);
$count = $data[0];
echo $count;
$countfile = fopen("counter.txt", "r");
$counter = fgets($countfile);
echo fgets($countfile);
while (fgets($countfile) <= $count)
{
$i = fgets($countfile);
$takeword = mysql_query("SELECT word FROM collection WHERE id='$i'") or die();
$wd = mysql_fetch_array($takeword);
$data = $wd[0];
$d1 = hash($algorith='md2',$data);
$d2 = hash($algorith='md4',$data);
$write = mysql_query("UPDATE collection SET md2='$d1', md4='$d2' WHERE id='$i'") or die(mysql_error());
//opens, empties and write the new pointer to the file. closes, and open the file in readmode for the next read at the loop.
$counts = fopen("counter.txt", "w+");
fwrite($counts, $counter + 1);
fclose($counts);
$countfile = fopen("counter.txt", "r");
}
Any help would be appreciated :) Looking for code optimization and killing the error. Suggestions would do.:)
Alright I'd do something like this (sorry about the delayed response, I kept forgetting)
<?php
//main execution
$sql = mysql_connect(...);
if (!$sql)
die ("No database connection");
if (!mysql_select_db(..., $sql))
die ("Database does not exist in this schema");
//Run the query for this iteration.
processQuery();
//---
function getQueryOffset($file)
{
$offset = 0; //default offset
if (file_exists($file)) //check if the counter file exists
{
$contents = file_get_contents($file); //get the contents of the counter
if ($contents !== FALSE && is_numeric($contents)) //check if an appropriate counter value
$offset = intval($contents);
}
return $offset;
}
function processQuery()
{
$table = "collection"; //table to update
$counter = "counter.txt"; //where to look for the last execution's offset.
$maxrows = 10000; //update 10,000 rows each time this file is loaded.
$sql = $GLOBALS['sql'];
//calculate the number of rows in the table
$qCount = mysql_query("SELECT COUNT(*) max FROM $table", $sql);
$aCount = mysql_fetch_assoc($qCount);
mysql_free_result($qCount);
$max = $aCount["max"];
$offset = getQueryOffset($counter); //calculate the offset (or a default 0)
if ($offset < $max) //if offet >= max, we're done.
{
$qUpdate = mysql_query("SELECT word, id FROM $table LIMIT $offset, $maxrows", $sql); //get the next "maxrows" rows from the table.
if ($qUpdate)
{
$assoc = NULL;
while (($assoc = mysql_fetch_assoc($qUpdate)) != NULL)
{
$md4 = hash("md4", $assoc["word"]); //calculate the hashes
$md2 = hash("md2", $assoc["word"]);
$id = $assoc["id"]; //id the row
mysql_query("UPDATE $table SET md2='$md2', md4='$md4' WHERE id=$id", $sql); //update the table columns
}
//update the offset in the counter file.
file_put_contents($counter, ($offset + mysql_num_rows($qUpdate)));
mysql_free_result($qUpdate);
}
}
}
mysql_close($sql);
?>
1 issue that I am seeing here:
Check your update query - that seems to be wrong. According to me, it should be "SET md2='$d1' AND md4='$d2'"
Another issue that I am not sure about:
I am unsure if md2 and md4 are valid names of hashing algorithms
A better way of doing this:
1. Dont write to file!
2. Create an additional column in your SQL by the name 'status', default value to 0. On update, change that value to 1.
3. Search for rows to edit based on query "SELECT word FROM collection WHERE status=0 limit 0,1"
4. OR if the columns md2 and md4 are empty in the original table, query could also be "SELECT word FROM collection WHERE md2='' and md4='' limit 0,1"
Hope this helps.