How read data from file and execute to MYSQL? - php

I create form to load sql file and used fopen function top open file and read this but when want to execute this data to database not work?
What is wrong in my code?
$ofile = trim(basename($_FILES['sqlfile']['name']));
$path = "sqlfiles/".$ofile;
//$data = settype($data,"string");
$file = "";
$connect = mysql_connect('localhost','root','');
$selectdb = mysql_select_db('files');
if(isset($_POST['submit']))
{
if(!move_uploaded_file($_FILES['sqlfile']['tmp_name'],"sqlfiles/".$ofile))
{
$path = "";
}
$file = fopen("sqlfiles/".$ofile,"r") or exit("error open file!");
while (!feof($file))
{
$data = fgetc($file);
settype($data,"string");
$rslt = mysql_query($data);
print $data;
}
fclose($file);
}

maybe you should use fgets instead of fgetc while youre reading lines.

Your script assumes that there is exactly one SQL statement per line, with no blanks or comments. If this is not the case then you'll need to either read and parse the file manually, or redirect the file to the mysql executable and let it handle the SQL statements.

Related

Bug fread in a txt file, read only one time

I'm creating a code to display the name of a server with enterprise rules, So for don't use Mysql i try a new things (for me) use php to read and rewrite files, that work perfectly for one part of my code and work perfectly but for the second he only read one time, and when i do a f5 the code don't increment.
He rewrite correctly because my file was at 000 and become 001
I try to use file() but he is disable since 7.0, try to use SplFileObject but it don't want to display anything and i don't like it because i understand nothing when i use it so i come back to fopen(),fread() and fwrite() and that don't work. I'm inPHP 7.3.1
The code that works :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$nom = "./config.txt";
$filez = fopen($nom, "r") or die("Unable to open file!");
$i = fread($filez,filesize($nom));
$year = getdate();
$idy = substr($year[year], 2);
$fichier = fopen("./resultsrv.txt", "w") or die("Unable to write file!");
for ($z; $z<$_POST['nbr']+1 ; $z++) {
$id = sprintf("%04d", $i+$z);
$nome = $_POST['type'].$_POST['OS'].$idy.$id."<br>" ;
echo $nome;
$nomewout = str_replace("<br>", ";", $nome);
fwrite($fichier,$nomewout);
}
$handle = fopen("./config.txt", "w") or die("Unable to write file!");
fwrite($handle,$id);
fclose($fichier);
fclose($handle);
}
?>
and the one that doesn't work because he doesn't increment :
<?php
if ( isset($_POST) AND !empty($_POST) ) {
$fileName = 'confchass.txt';
$read = fopen($fileName,"r");
$fn = fopen($fileName,"w+");
$i = fread($read,filesize($fileName));
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $_POST['Marque'].$_POST['DC'].$id;
echo "</div>";
fwrite($fn,$id);
fclose($read);
fclose($fn);
}
?>
I want he output a thing like XXXXXX001 and when i refresh or do a new POST from my forms he output XXXXXX002 and XXXXXX003 .... But he actualy output only XXXXXX001
The problem is that you open the file for reading and then for writing. But from the manual...
'w+' Open for reading and writing; place the file pointer at the
beginning of the file and truncate the file to zero length. If the
file does not exist, attempt to create it.
So this will blank out the file before you read the value from it.
To fix this (using your current method, you should read the value, then open it for writing and write the new value...
$read = fopen($fileName,"r");
$i = fread($read,filesize($fileName));
fclose($read);
$id = sprintf("%03d", $i+1);
echo "<div align='center'><h1>Le Chassis</h1>";
echo $id;
echo "</div>";
$fn = fopen($fileName,"w+");
fwrite($fn,$id);
fclose($fn);
You could shorten this by using file_get_contents() and file_put_contents().

Trying to write Php fwrite XML file from mysql query

I am trying to write some code that grabs a CSV file pulls the relevant postcode column then looks up that postcode in a MySql database which has longitude and latitude fields then save them to an XML file so it can be used in a different program
I think this code piece is all working, but for some reason, it only outputs the last field of the query :
//Open the file.
$fileHandle = fopen("test.csv", "r");
$postcode = array();
while (($row = fgetcsv($fileHandle, 0, ",")) !== FALSE) {
array_push($postcode, $row[40]);
}
$postcodefil = (array_unique($postcode));
$postcodefil = str_replace(' ', '', $postcodefil);
$postcodefil = preg_replace('/\s+/', '', $postcodefil);
//print_r($postcodefil);
foreach ($postcodefil as $value) {
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT postcode, latitude, longitude FROM postcode WHERE postcode='$value' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$myfile = fopen("test.xml", "w") or die("Unable to open file!");
$lat = $row["latitude"];
$lng = $row["longitude"];
fwrite($myfile, $lat."testss".$lng."\n");
echo $lat;
echo $lng;
echo "<br />";
}}
} // end of foreach
$conn->close();
however when i run it, it echo's correctly
50.822398-0.139938
51.444908-1.295341
50.841951-0.842508
51.308504-0.551835
etc.... etc...
but the Fwrite just outputs the last line
51.120916testss-0.599545
I' m totally confused by this. Please forgive me if it's something basic that I've over looked and thanks in advance.
The problem is that you open the file in each loop, this overwrites the previous data...
$myfile = fopen("test.xml", "w") or die("Unable to open file!");
while($row = $result->fetch_assoc()) {
So move the open outside the loop.
The second issue is that you aren't writing XML at all. You need to do something like...
$xml = simplexml_load_string("<coords />");
while($row = $result->fetch_assoc()) {
$newCoord = $xml->addChild("coord");
$newCoord->addChild("latitude", $row["latitude"]);
$newCoord->addChild("longitude", $row["longitude"]);
}
$xml->saveXML("test.xml");
This will generate a simple XML file, you will need to set the element names as appropriate.
First thing put the connection outside of the foreach loop, and the fopen outside the while
loop.
You open the xml file in the 'w' mode means according to the doc
Open for writing only; place the file pointer at the beginning of the
file and truncate the file to zero length. If the file does not exist,
attempt to create it.
You need append mode 'a'
Open for writing only; place the file pointer at the end of the file.
If the file does not exist, attempt to create it. In this mode,
fseek() has no effect, writes are always appended.
This will work for you. But you still making a db request per postalcode, i would suggest to collect all the postal code you need to query and make one db request to database with sql IN operator.

PHP: INSERT a header on Fputcsv

Hi guys I know I am asking a common question but in my case I have the following code:
if (!isset($_SESSION['countRows']) && empty($_SESSION['countRows']))
{
$_SESSION['countRows'] = $_POST['countRows'];
}
$data = date("dmY");
$filename = "EstrazioneParziale_del_" . $data;
$estensione = ".csv";
$fileOpen = fopen($filename.$estensione, "a") or die("Impossibile aprire il file");
$arrayData = ['Operation','Nome Servizio','ID Servizio','S.O.','Patch Level','N° Apparati'];
fputcsv($arrayData, array_keys($_POST['arrayFiltrato'][0]));
foreach ($_POST['arrayFiltrato'] as $fields) {
fputcsv($fileOpen, $fields);
}
fclose($file);
The first fputcsv doesn't insert an header to the csv file and I only can see the csv file will all the datas without the header (I use $arrayData to get the headers). Can somebody help me? Many thanks! :-)
Your call to put the headers out doesn't use the right parameters, the first is the file handle and the second is the data. So...
fputcsv($arrayData, array_keys($_POST['arrayFiltrato'][0]));
should be
fputcsv($fileOpen,$arrayData);
Also you probably want to open the file in write mode instead of append (otherwise your new content will be added to the end of the existing content)...
$fileOpen = fopen($filename.$estensione, "w") or die("Impossibile aprire il file");
Your close is using the wrong file handle as well...
fclose($file);
should be
fclose($fileOpen);

cannot insert contents of text files into database

i want to insert the contents of some text files into database, but it failed. please help me, thank you very much. :)
<?php
function saveContent($url){
set_time_limit(0);
foreach ($url as $file =>$files) {
$handle= fopen($files, "r") or die ('can not open file');
$content = file_get_contents($files);
//insert into database
$q0 = mysql_query("INSERT INTO tb_document (doc_id, namefiles, content) VALUES('','$files','$content') ");
fclose($handle);
}
}
$path_to_check = 'C:/Appserv/www/textsumm2/textsumm/try/';
$url = glob($path_to_check.'*.txt');
$a = saveContent($url);
?>
You have to escape the content of your files to prevent characters that cause an invalid SQL syntax.
You can use real-escape-string for that.
maybe you can use mysql_real_escape_string() :
$content = mysql_real_escape_string(file_get_contents($files));

Appending data to a csv file from a php form but also adding static data every time

Ok I almost have it working but am having trouble escaping the html to preserve the link I'm missing something here .. I'm sure it's simple
if($_POST['formSubmit'] == "Submit")
$varUserName = $_POST['username'];
$varPW = $_POST['PW'];
$varEmail = $_POST['email'];
{
$fs = fopen("testcsv.csv","a");
fputcsv($fs, array($varUserName,$varPW,$varEmail,"admin","title",",category","some text here site.com",));
fclose($fs);
exit;
}
?>
I am not sure what you're having trouble with. Are you familiar with fopen();? Are you familiar with CSV?
You will need to open the file for appending and append to your file using fwrite(). Once done, close the file with fclose().
$fp = fopen("./filename", 'a'); //Open file for append
//fwrite($fp, $row1.",".$row2); //Append row,row to file
fputcsv($fp, array($name,$password,"http://$name.whatever.com")); //#Optimist
fclose($fp); //Close the file to free memory.

Categories