PHP and Mysql check if selected row is last - php

I have been Trying to check if selected row is last in MYSQL data records, if it is last then go back to first record.
Here is what I have done so far:
$fps = #fopen('number.txt', "r+");
$somay = fread($fps, filesize('number.txt'));
fclose($fps);
$num = ($somay+1);
$file = "number.txt";
$fh = fopen($file,'w+') or die("cant open file");
fwrite($fh,$num);
fclose($fh);
$sql = "SELECT #last_id := MAX(id),token FROM `token` where `id` = '".$somay."'";
if (!$result = $mysqli->query($sql)) {
echo "Sorry, the website is experiencing problems.";
echo "Error: Our query failed to execute and here is why: \n";
echo "Query: " . $sql . "\n";
echo "Errno: " . $mysqli->errno . "\n";
echo "Error: " . $mysqli->error . "\n";
exit;
}
if ($result->num_rows === 0) {
echo "We could not find a match for ID, sorry about that. Please try again.";
exit;
}
while ($tokennek = $result->fetch_assoc()) {
$token = $tokennek[token];
$tokenid = $tokennek[last_id];
}
if($somay == $tokenid){
$file = "number.txt";
$fh = fopen($file,'w+') or die("cant open file");
fwrite($fh,1);
fclose($fh);
}
Let me make it more clear here what I am doing is saving a file named number.txt to keep record of token which is already been used and go to next token/row.

Related

CSV file upload with data validation

I'm trying to upload a *.CSV file to the database using PhP.
I can't really make the data validation work with the file upload.
The script should see if the data from certain cells is valid by searching in the db's tables.
The file should not be uploaded if there are errors!
Here's the code!
<form name="import" method="post" enctype="multipart/form-data">
<input type="file" name="file" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
<?php
include ("connection2.php");
if(isset($_POST["submit"]))
{
$file = $_FILES['file']['tmp_name'];
$handle = fopen($file, "r");
$c = 0;
$err = 0;
if ($_FILES["file"]["type"]=='application/vnd.ms-excel')
{
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$query = mysqli_query("SELECT * FROM modele WHERE `model` = '".$model."'");
if (!empty($query)) {
$err ++;
$msg=$msg."Model error on row $c <br>";
}
$query = mysqli_query("SELECT * FROM judete WHERE `nume` = '".$judet."'");
if (!empty($query)) {
$err ++;
$msg=$msg."Judet error on row $c <br>";
}
$query = mysqli_query("SELECT * FROM beneficiari WHERE `nume` = '".$beneficiar."'");
if (!empty($query)) {
$err ++;
$msg=$msg." Beneficiar error on row $c <br>";
}
// if (strlen($tid)!==8){
// $err ++;
// $msg=$msg."TID length error at row $c <br>";
// }
$c ++;
}
if ($err!==0){
echo $msg; echo "ERROR COUNT= ".$err;
break;
}
$c=0;
while(($filesop = fgetcsv($handle, 3000, ",")) !== false)
{
$tid = trim($filesop[0]);
$beneficiar = ucwords(strtolower(trim($filesop[1])));
$locatie = ucwords(strtolower(trim($filesop[2])));
$localitate = ucwords(strtolower(trim($filesop[3])));
$judet = ucwords(strtolower(trim($filesop[4])));
$adresa = ucwords(strtolower(trim($filesop[5])));
$model = trim($filesop[6]);
$qry=mysql_query("SELECT id FROM beneficiari WHERE `nume` = '".$beneficiar."'");
while ($row = mysql_fetch_assoc($qry)){
$id_client=$row['id'];
echo "Beneficiar=".$row['id'];
}
$qry_id_model=mysql_query("SELECT id FROM modele WHERE `model` = '".$model."'");
while ($row = mysql_fetch_assoc($qry_id_model)){
$id_model=$row['id'];
echo "Model=".$row['id'];
}
echo "MODEL2:".$id_model;
$adresa1 = $adresa.", ".$localitate;
if ($c!==0){
$sql = mysql_query("INSERT INTO equipments
(id_client, model, tid, beneficiar, adresa, agentie, judet)
VALUES
('$id_client','$id_model','$tid','$beneficiar','$adresa1','$locatie','$judet')");
}
$c = $c + 1;
}
if($sql){
echo "You database has imported successfully. You have inserted ". $c ." recordes <br>";
}else{
echo "Sorry! There is some problem.<br>";
}
echo "Upload: " . $_FILES["file"]["name"] . "<br />";
echo "Type: " . $_FILES["file"]["type"] . "<br />";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br />";
}
else echo "NOT CSV!";
}
?>
What's wrong here?
When i try to run it the data is not uploaded and no errors are shown, I left errors in the file to test it. Also i uploaded a clean file and also the file is not uploaded. If i break the code in 2 and make 2 separate codes, one to verify and one to upload, the upload works, but i need the verification and the upload to be in the same code. also tried mysql_query in stead of mysqli_query.
The procedural style of mysqli_query takes 2 arguments - the connection and the query. You're only passing the query.
You can read the official documentation for the mysqli_query() method here:
http://php.net/manual/en/mysqli.query.php
A suggestion as to how to approach this would be something like:
$link = mysqli_connect("127.0.0.1", "my_user", "my_password", "my_db");
if(!$link)
{
echo("Unable to connect");
} else {
if($ret = mysqli_query($link, "SELECT id FROM modele WHERE `model` = '".mysqli_real_escape_string($link, $model)."'"))
{
$data = mysqli_fetch_assoc($ret);
echo($data["id"]);
}
mysqli_close($link);
}
Important: Note my use of mysqli_real_escape_string in the example above - your current code leaves you vulnerable to SQL injection attacks.
first of all you should upload this file on a temporary folder and save the file name. Then use getCSV php function to read properly the file.
Finally you can check if it's all OK, insert on database, and, if not, echo an error message and delete the file (remember we saved the name and we know the static route of the temporary folder).
Hope it helps!

How to Validate Employee Id in Importing File in .CSV format to SQL?

How to Validate Employee Id in Importing File in .CSV format to SQL?
*a code that check if the data is already exist.
-->sample: if the Employee Id already exist it promts "Employee ID already Exist"..
if the rows in csv, you can make a array of csv rows.
$list =array();
$id = array();
while( ($rows= getcsv($hande)) !== false)
{
array_push($list, $rows);
array_push($id, $rows['emplyee_id']);
}
then check mysql or database
$check_id = implode(",", $id);
$que = "select employ_id from table where employ_id in ($check_id)";
at this time you can find employ_ids from database.
if you make employee_id column unique, your code would be like this
$result=mysqli_query($db_con", "insert into table (employ_id) values ('$empoy_id')";
if($result == false) // if employ_id alreay exists in table $result is false
{
}
but as i know, the best way using index is checking key is exists before inserting data not after inserting query failed.
This is my code:
`<?php
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br>";
echo "Stored in: " . $_FILES["file"]["tmp_name"];
$a=$_FILES["file"]["tmp_name"];
echo $a;
$connect = mysql_connect('localhost','root','');
if (!$connect) {
die('Could not connect to MySQL: ' . mysql_error());
}
//your database name
$cid =mysql_select_db('cgi_warehouse',$connect);
// path where your CSV file is located
//define('CSV_PATH','C:/xampp/htdocs/');
//<!-- C:\\xampp\\htdocs -->
// Name of your CSV file
$csv_file = $a;
if (($getfile = fopen($csv_file, "r")) !== FALSE) {
$data = fgetcsv($getfile, 1000, ",");
while (($data = fgetcsv($getfile, 1000, ",")) !== FALSE) {
//$num = count($data);
//echo $num;
//for ($c=0; $c < $num; $c++) {
$result = $data;
$str = implode(",", $result);
$slice = explode(",", $str);
$col1 = $slice[0];
$col2 = $slice[1];
$col3 = $slice[2];
$col4 = $slice[3];
$col5 = $slice[4];
$col6 = $slice[5];
$col7 = $slice[6];
$col8 = $slice[7];
$col9 = $slice[8];
$col10 = $slice[9];
$col11 = $slice[10];
$col12 = $slice[11];
$col13 = $slice[12];
$col14 = $slice[13];
$col15 = $slice[14];
$col16 = $slice[15];
$query = "INSERT INTO tools(tools_id, item_description, category_id, sn, qty, price, supplier, frm, location, ref_no, sender, receiver, date_receive, date_added, status, remarks) VALUES('".$col1."','".$col2."','".$col3."','".$col4."','".$col5."','".$col6."','".$col7."','".$col8."','".$col9."','".$col10."','".$col11."','".$col12."','".$col13."','".$col14."','".$col15."','".$col16."')";
$s=mysql_query($query, $connect );
}
}
echo "<script>alert('Record successfully uploaded.');window.location.href='#';</script>";
mysql_close($connect);
}
?>`

How to generate a Log file in my machine when batch file is run as cronjob

Im running a Batch file as cronJob in my windows 7 machine,all I wanted is I want to create a log file ,when the cron Job is run along with the data,which it was displaying in the console.
The data ,is the echo statements which are present in the index.php which i have imported in the batch file.
Help me out to solve this issue.
index.php
<?php
echo "Welcome" ;
$fileD = "Login_".date('Y-m-d').".csv";
$fp1 = fopen($fileD, 'a+');
//Getting the files from below mentioned folder
$iterator1 = new FilesystemIterator("C:/wamp/www/logs1");
$iterator2 = new FilesystemIterator("C:/wamp/www/logs2");
$filelist = array();
foreach($iterator1 as $GLOBALS['entry1'])
{
if (strpos($entry1->getFilename(), "p1") === 0)
{
$filelist[] = $entry1->getFilename();
echo $entry1;
}
}
foreach($iterator2 as $GLOBALS['entry2']) {
if (strpos($entry2->getFilename(), "p2") === 0) {
$filelist[] = $entry2->getFilename();
echo "<br>";
echo $entry2;
}
}
$file1 = file_get_contents($entry1);
fwrite($fp1, $file1);
$file1 = file_get_contents($entry2);
fwrite($fp1, $file1);
fclose($fp1);
echo "<br/>";
echo "Done";
echo "<br/>";
//Deletes log file present in the logs folder
$n1= "$entry1";
if(!unlink($n1))
{
echo ("Error deleting file1 $n1");
}
else
{
echo ("Deleted $n1");
}
echo "<br/>";
$n2= "$entry2";
if(!unlink($n2))
{
echo ("Error deleting file2 $n2");
}
else
{
echo ("Deleted $n2");
}
echo "<br/>";
foreach (glob("*.csv") as $filename)
{
echo "$filename size " . filesize($filename) . "\n";
echo "<br>";
}
echo "<br>";
//$insertionDate = substr($filename,6,10);
$servername = "localhost";
$username = "user";
$password = "";
$dbname = "stat";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$file = file_get_contents($fileD);
$count = preg_match_all("/,Login,/", $file, $matches);
echo "Csv first word ";
$insertionDate = substr($file,1,10);
echo "<br/>";
echo "Total Hits:" . $totalLines = count(file($fileD));
echo "<br/>";
echo "Login:" . $count;
// Insert the Total hits and the corresponding success and failure count
$sql = "INSERT INTO hit_s (HitDate, count, category,success,failure,tcount,ocount)
VALUES ('$insertionDate', $totalLines, 'Hits',$success,$fail,$treeCnt,$oCnt)";
if ($conn->query($sql) === TRUE) {
echo "Total hits record inserted successfully \n";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$iterator = new FilesystemIterator("C:/wamp/www/Fed");
$filelist1 = array();
foreach($iterator as $GLOBALS['entry3'])
{
if (strpos($GLOBALS['entry3']->getFilename(), "*.csv") === 0)
{
$filelist1[] = $GLOBALS['entry3']->getFilename();
}
}
echo $GLOBALS['entry3'];
echo "<br/>";
$entry3="$fileD";
$n3= "$entry3";
if(!unlink($n3))
{
echo ("Error deleting $n3");
}
else
{
echo ("Deleted $n3");
}
echo "<br/>";
$conn->close();
?>
In batch file im calling the index.php file like below
C:\wamp\bin\php\php5.4.16\php.exe C:\wamp\www\Fed\csv\index.php
It looks like syslog will work for you:
$access = date("Y/m/d H:i:s");
syslog(LOG_WARNING, "Unauthorized client: $access {$_SERVER['REMOTE_ADDR']} ({$_SERVER['HTTP_USER_AGENT']);

sqlsrv_fetch_object() not returning results

I have a simple SELECT statement, an optional WHERE clause, and an ORDER BY however while looping through sqlsrv_fetch_object() I am not getting any records:
if (!$conn)
{
echo "no connection!\n";
}
$data = array();
$qry = "SELECT DISTINCT lineid, ord_num, prod_num, description, prod_type, style, color, sizetype, qty1, qty2, qty3, qty4, qty5, qty6, qty7, qty8, qty9, qty10, qty11, qty12, qty13, qty14, qty15, ext_id, decoration1, design1, iposition1, cccode1, decoration2, design2, iposition2, cccode2, decoration3, design3, iposition3, cccode3, '', design4, iposition4, cccode4, decoration5, design5, iposition5, cccode5, decoration6, design6, iposition6, cccode6, decoration7, design7, iposition7, cccode7, last_mod FROM DataLIVE.dbo.sodetail ";
if ($last_run_date)
{
$qry .= "WHERE last_mod > '" . $last_run_date . "' ";
}
$qry .= "ORDER BY last_mod ASC";
fwrite($fp, $qry . "\n");
if ($st = sqlsrv_query($conn, $qry))
{
while ($row = sqlsrv_fetch_object($st))
{
$row->last_mod = $row->last_mod->format('Y-m-d H:i:s');
fwrite($fp, "Last Mod::: " . $row->last_mod . "\n");
$data[] = $row;
}
sqlsrv_free_stmt($st);
unset($row, $st);
}
else
{
$sqlerr = sqlsrv_errors();
foreach ($sqlerr as $key)
{
foreach ($key as $col => $val)
{
echo "Error Key: " . $col . "\nError Msg: " . $val . "\n";
fwrite($fp, "Error Key: " . $col . "\nError Msg: " . $val . "\n");
}
}
$data = FALSE;
}
return $data;
I don't know why sqlsrv_fetch_object() is not returning anything. Also, I can copy and paste the query directly into SQL Server Studio from the log I'm writing, it parses fine. There is nothing in my log file where I am writing out the last_mod date in the while loop.
I posted this with a slightly different question a few minutes ago and someone suggested to remove the selection of an empty string in the SELECT statement, but I need that empty string placeholder there where it is.

MySQL_Query error in PHP script

The goal is that I would like to cycle through ALL of the .CSV files in my directory and run this script for each file so it appends the data into the DB. The issue stems from when I insert the loop below. I have compiled a PHP script that works perfectly when it comes to reading a SINGLE .CSV file into my MySQL DB. Despite this, I get the following error when I call the mysql_query function after inserting the import script into a loop: Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)
$con = #mysql_connect($databasehost,$databaseusername,$databasepassword) or die(mysql_error());
#mysql_select_db($databasename) or die(mysql_error());
//CLEAR old contents from table
$queryDelete = "delete from $databasetable;";
$resultDelete = #mysql_query($queryDelete) or die("Error clearing table of old data: $query<br />" . mysql_error());
//READ directory for CSV files
//path to directory to scan IF NOT IN SAME FOLDER
$directory = "../data/";
//get all files IN CURRENT DIRECTORY with a .csv extension OTHERWISE add $csvfiles = glob($directory . "*.csv");
$csvfiles = glob("*.csv");
$numCSVFiles = count($csvfiles);
//Grab each CSV file and import to DB
for ($i = 0; $i < $numCSVFiles; $i++) {
$csvfile = $csvfiles[$i];
//TEST FILES
if(!file_exists($csvfile)) {
echo "File (" . $csvfile . ") not found. Make sure you specified the correct path.\n";
exit;
}
$file = fopen($csvfile,"r");
if(!$file) {
echo "Error opening data file.\n";
exit;
}
$size = filesize($csvfile);
if(!$size) {
echo "File is empty.\n";
exit;
}
$csvcontent = fread($file,$size);
fclose($file);
$lines = 0;
$queries = "";
$linearray = array();
foreach(split($lineseparator,$csvcontent) as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
//$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto == 1)
$query = "insert into $databasetable values('','$linemysql');";
else
$query = "insert into $databasetable values('$linemysql');";
$queries .= $query . "\n<br />";
//THIS IS WHERE THE ERROR OCCURS WHILE RUNNING INSIDE THE LOOP
$result = #mysql_query($query) or die("Error 1: " . mysql_error() . "<br />Query Attempted: " . $query);
if(!$result) { $resultText = "Failure to execute MySQL queries. Please try again later."; } else { $resultText = "Successfully executed queries."; }
}
#mysql_close($con) or die("Error 2: " . mysql_error());
//LOG mysql queries
if($save) {
if(!is_writable($outputfile)) {
echo "File is not writable, check permissions.\n";
}
else {
$file2 = fopen($outputfile,"w");
if(!$file2) {
echo "Error writing to the output file.\n";
}
else {
fwrite($file2,$queries);
fclose($file2);
}
}
}
}
You're executing mysql_close() INSIDE your loop, so after the first file is inserted, you kill the DB connection, then try to insert the next file.
If your code was properly indented, you'd have seen this problem.
You're closing your database connection inside the loop. Don't close the connection if you want to keep using it.
I think you're missing a closing curly bracket { here...
mysql_close() is called too early: it's called in the for ($i = 0; $i < $numCSVFiles; $i++) loop.

Categories