get NULL to be saved to file - php

I have a table that I am trying to save to an sql file using php.
The table has fields with NULL.
However when I try and loop through the table rows to save to file, the NULLs become blank strings, is there anything I can do to prevent this?
Below is a snippet of the code
$sql="SELECT * FROM myTable";
$sql_result=mysql_query($sql);
while ($row = mysql_fetch_array($sql_result,MYSQL_ASSOC)){
$saveSql.=$row['myId'].",";
$saveSql.="'".$row['myName']."',";
$saveSql.=$row['myAge'].",";
}
$handle = fopen('database.sql', 'w');
fwrite($handle,$saveSql);
If there are NULL values, then they are not saved to file, they are saved as empty strings.

PHP stringifies null as "" (empty string).
If you want to save to file while keeping fidelity use a serializer like seralize or json_encode.
Writing:
fwrite($handle, serialize($saveSql));
Reading
$import = unserialize(fread($handle));

People forget the power of if statements....
if ($row['myId'] == "") { $saveSql .= "NULL"; }
Etc...

That's to be expected. An SQL null is mapped to a PHP null, which gets converted to an empty string when you output it. If you want the literal letters n, u, l, l, to be output, then you'll have to do that conversion yourself, e.g.
$text = isnull($row['myName']) ?: 'NULL';

try this
$sql="SELECT * FROM myTable";
$sql_result=mysql_query($sql);
while ($row = mysql_fetch_array($sql_result,MYSQL_ASSOC)){
if(isNull($row['myId']){$saveSql.="NULL".",";}else{$saveSql.=$row['myId'].",";}
if(isNull($row['myName']){$saveSql.="NULL".",";}else{$saveSql.=$row['myName'].",";}
if(isNull($row['myAge']){$saveSql.="NULL".",";}else{$saveSql.=$row['myAge'].",";}
}
$handle = fopen('database.sql', 'w');
fwrite($handle,$saveSql);

Related

What happens to binary files in file_get_contents?

I'm trying to read a file in php and store it as a varbinary in sql server. The process works for text files, but I'm still having trouble with images.
I'm using the following lines to read the file contents into a string, but I'm not sure that that's not where my problem lies:
$data = NULL;
$validators = NULL;
if($file = file_save_upload('file', $validators, FALSE, 0)){
$data = file_get_contents($file->getFileUri());
$filename = $file->getFilename();
}
Then I pass the $data string to a prepared statement:
$conn = $this->_get_connection();
$sql = "
EXEC JC_Update_Document_SP
...
?,
...;
";
$file_input = [
[$data, NULL, NULL, SQLSRV_SQLTYPE_VARBINARY],
];
$stmt = sqlsrv_prepare($conn, $sql, $file_input);
if(sqlsrv_execute($stmt) === false){
die(print_r(sqlsrv_errors(), true));
}
where the $data field feeds into a varbinary column in a stored procedure in the database.
Another method I tried involved converting the $data varchar to a varbinary(max) field in the database, but either way, I get back a broken image.
So my question is this... is file_get_contents messing up my binary data? How would I read the image file and upload it to the database for later retrieval?
I found the bin2hex function. I'm still unclear on why this is needed, but it gets the job done.

Writing into csv with php problems

I have a problem. I'm trying to get some data from a database into a .csv table.
$fn=fopen($path.$filename, "w");
$addstring = file_get_contents($path.$filename);
$addstring = 'Azonosito;Datum;Ido;Leiras;IP-cim;allomasnév;MAC-cim;Felhasznalonev;Tranzakcioazonosito;Lekerdezes eredmenye;Vizsgalat ideje;Korrelacios azonosito;DHCID;';
/*$addstring .= "\n";*/
$sql="select * from dhcpertekeles.dhcpk";
$result =mysqli_query($conn, $sql);
if ($result=mysqli_query($conn,$sql))
{
while ($row=mysqli_fetch_row($result))
{
$addstring .= "\n".$row[0].";".$row[1].";".$row[2].";".$row[3].";".$row[4].";".$row[5].";".$row[6].";".$row[7].";".$row[8].";".$row[9].";".$row[10].";".$row[11].";".$row[12].";";
};
};
/*file_put_contents($path.$filename, $addstring);*/
fwrite($fn, $addstring);
fclose($fn);
The data is in the following format:
The first addstring contains the column names, and has no issues
the second (addstring .=) contains the data:
ID($row[0]), Date($row[1]), Time($row[2]), Description($row[3]), IP($row[4]), Computer name($row[5]), MAC($row[6]), User($row[7])(empty), Transactionid($row[8]), query result($row[9]), query time($row[10]), correlation id($row[11])(empty), DHCID($row[12])(empty)
It is basically daily DHCP server data, uploaded to a database. Now, the code works, it does write everything i want to the csv, but there are 2 problems.
1, the code for some inexplicable reason, inserts an empty row into the csv table between the rows that contain the data. Removing $row[12] fixes this. I tried removing special characters, converting spaces into something that can be seen, and even converting empty string into something that can be seen. Yet nothing actually worked, i even tried file_puts_content(same for the second problem) instead of fwrite, but nothing. The same thing keeps happening. If i remove \n it will work, but the 2nd row onwards will be misplaced to the right by 1 column.
2, For some reason, the last 2 character is removed from the csv. The string that is to be inserted into the csv still contains said 2 characters before writing it to the file. Tried both fwrite and file_puts_content.
As for the .csv format, the data clumns are divided by ; and rows by \n.
Also tried reading the file with both libre office and excel thinking it might be excel that was splurging but no.
Try using fputcsv() function. I didn't test following code but I think it should work.
$file = fopen($path . $filename, 'w');
$header = array(
'Azonosito',
'Datum',
'Ido',
'Leiras',
'IP-cim',
'allomasnév',
'MAC-cim',
'Felhasznalonev',
'Tranzakcioazonosito',
'Lekerdezes eredmenye',
'Vizsgalat ideje',
'Korrelacios azonosito',
'DHCID'
);
fputcsv($file, $header, ';');
$sql = "select * from dhcpertekeles.dhcpk";
$result = mysqli_query($conn, $sql);
if ($result = mysqli_query($conn, $sql)) {
while ($row = mysqli_fetch_row($result)) {
fputcsv($file, $row, ';');
}
}
fclose($file);
The $addstring = file_get_contents($path.$filename) doesn't does nothing because you're overwriting that variable in the next line.
To remove the extra row on 12 did you tried removing the \n AND the \r with something like:
$row[12] = strtr($row[12], array("\n"=>'', "\r"=>''));
You can also check which ascii characters are you receiving in the $row[12] with this function taken form the php site:
function AsciiToInt($char){
$success = "";
if(strlen($char) == 1)
return "char(".ord($char).")";
else{
for($i = 0; $i < strlen($char); $i++){
if($i == strlen($char) - 1)
$success = $success.ord($char[$i]);
else
$success = $success.ord($char[$i]).",";
}
return "char(".$success.")";
}
}
Another tip can be the database it's returning UTF-8 or UTF-16 and you're losing some characters in the text file.
Try looking at that with the mb_detect_encoding function.

How to make select queries repeatedly with php?

Basically what I need is to make queries that depend on the values ​​of a text file that I'm reading.
This is the code that I have.
$con = mysqli_connect($host,$name,$pass,$db);
$file = fopen($_FILES["file"]["tmp_name"], "r") or die("Unable to open file!");
while(!feof($file))
{
$codigo = fgets($file);
$result = mysqli_query($con,"SELECT column FROM table WHERE column='". $codigo."'");
$row = mysqli_fetch_array($result);
echo $row;
}
fclose($file);
mysqli_close($con);
But I can´t get that I want. I have some values in my text file but when I excecute this I only get the query of the last value of my text file.
Any suggestion?
If I add this line inside the while:
echo $codigo . "<br>";
All the content of my text file are printed, so I think the problem is in the result variable. All the values of the text file return a null value when I make the query except the last.
Try
print_r($row);
or
echo $row["column"];
instead of
echo $row;
Otherwise you will always have "Array" returned.
The solution is someting stupid, when I read a file line by line, PHP also read the newline (\n) so when I make a query the where condition never is true.
A quick solution is make a substring.
What you are doing wrong is this line:
$row = mysqli_fetch_array($result);
And that's why you only see the last result. You keep overwriting that value with the new result. Instead of rewriting the string, keep adding to the array, then after the loop var_dump or print_r the array.
$row[] = mysqli_fetch_array($result);
It also might help you to use mysqli in an object-oriented fashion, the way it was designed:
$result = $con->query($query);

Pulling data from mysql based on Array

I have a file file.php and inside my file I am using the code bellow to pull some data from my database and display some information.
My code is
$array = $_GET['theurl']; // My url looks like myfile.php?theurl=1,2,3 (id,s)
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sql);
$tc4a = mysql_fetch_assoc($rsdt4);
$mycomma4 = ",";
if ($tc4a['a_youtube'] == "#"){
}else{
while ($tc4 = mysql_fetch_assoc($rsdt4))
{
echo $tc4['a_youtube'];
echo ",";
}
}
I expect to echo the infos of the two id's (in array) inside my while function, but it returns the results only from the first.
Any ideas?
I am confusing on $sql :
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sql);
Can you take a look after changing below:
$sqlnt4 = "select * from mytable WHERE `id` IN ($array)";
$rsdt4 = mysql_query($sqlnt4);
First that's extremely vulnerable to security issues - I hope this isn't used in production and just for playing around.
I recommend switching to PDO, or at the very least securing your variables.
To put that array into the query, you need to implode it into a list, as such.
$list = implode(',', $array);
You can then use the list in the statement, which will look like 1,2,3.
Edit:
I've just realized your $array value isn't actually an array - have you missed code out or is it badly named?
mysql_fetch_assoc: "Returns an associative array that corresponds to the fetched row and moves the internal data pointer ahead." http://pt2.php.net/mysql_fetch_assoc
Try mysql_fetch_rows to return all matching rows into an array.

Automatically build mySql table upon CSV upload

Automatically build mySql table upon a CSV file upload.
I have a admin section where admin can upload CSV files with different column count and different column name.
which it should then build a mySql table in the db which will read the first line and create the columns and then import the data accordingly.
I am aware of a similar issue, but this is different because of the following specs.
The name of the Table should be the name of the file (minus the extension [.csv])
each csv file can be diffrent
Should build a table with number of columns and names from the CSV file
add the the data from the second line and on
Here is a design sketch
Maybe there are known frameworks that makes this easy.
Thanks.
$file = 'filename.csv';
$table = 'table_name';
// get structure from csv and insert db
ini_set('auto_detect_line_endings',TRUE);
$handle = fopen($file,'r');
// first row, structure
if ( ($data = fgetcsv($handle) ) === FALSE ) {
echo "Cannot read from csv $file";die();
}
$fields = array();
$field_count = 0;
for($i=0;$i<count($data); $i++) {
$f = strtolower(trim($data[$i]));
if ($f) {
// normalize the field name, strip to 20 chars if too long
$f = substr(preg_replace ('/[^0-9a-z]/', '_', $f), 0, 20);
$field_count++;
$fields[] = $f.' VARCHAR(50)';
}
}
$sql = "CREATE TABLE $table (" . implode(', ', $fields) . ')';
echo $sql . "<br /><br />";
// $db->query($sql);
while ( ($data = fgetcsv($handle) ) !== FALSE ) {
$fields = array();
for($i=0;$i<$field_count; $i++) {
$fields[] = '\''.addslashes($data[$i]).'\'';
}
$sql = "Insert into $table values(" . implode(', ', $fields) . ')';
echo $sql;
// $db->query($sql);
}
fclose($handle);
ini_set('auto_detect_line_endings',FALSE);
Maybe this function will help you.
fgetcsv
(PHP 4, PHP 5)
fgetcsv — Gets line from file pointer
and parse for CSV fields
http://php.net/manual/en/function.fgetcsv.php
http://bytes.com/topic/mysql/answers/746696-create-mysql-table-field-headings-line-csv-file has a good example of how to do this.
The second example should put you on the right track, there isn't some automatic way to do it so your going to need to do a lil programming but it shouldn't be too hard once you implement that code as a starting point.
Building a table is a query like any other and theoretically you could get the names of your columns from the first row of a csv file.
However, there are some practical problems:
How would you know what data type a certain column is?
How would you know what the indexes are?
How would you get data out of the table / how would you know what column represents what?
As you can´t relate your new table to anything else, you are kind of defeating the purpose of a relational database so you might as well just keep and use the csv file.
What you are describing sounds like an ETL tool. Perhaps Google for MySQL ETL tools...You are going to have to decide what OS and style you want.
Or just write your own...

Categories