Goal: Use php to read, parse, & edit and write data from a view into a pipe delimited outfile.
Setup: I have a view “my_view” that has 11 columns/fields. I need data from the first 10 written to the pipe delimited file.
Complicating Factor: The tenth field has a string of text that may contain many comma separated values or it may be blank
Requirement: Output a file that has data separated by exactly 26 pipes
My conceptual solution: Use php to query the view and return the table with fields separated by commas, then find and replace all commas with pipes. Then calculate to ensure that each record/row has a total of 26 pipes even if there is no data to separate.
[I am using nuBuilder and can attach php to a button to initiate an action. I will attach this code to be executed by the button in nubuilder. I am able how to insert the code in nubuilder when I figure out how to write the php]I’ve attempted solving this as a stored procedure in phpMyadmin but I can’t seem to dynamically calculate out the required number of pipes.
My view (which I want the data from) looks like this:
Select
Signals.SignalName
Signals.SddName
Signals.Address
Signals.Word
Signals.MSB
Signals.LSB
Signals.Resolution
Signals.DataType
Signals.Units
Enumerations.TypeName (This is the column containing string of data seperated by colums.
Signals.FK_EnuID
WHERE Signals FK_EnuID = Enumeratiopns.ID
I think I’ve come up with the following code:
<?php
$servername='localhost';
$username = 'user';
$password = 'password';
$dbname = 'database';
//Create a connection
$con = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM my_view";
$result = $conn->query($sql);
if (result->num_rows > 0) {
while ($row = $result->fetch_assoc()){
//string replace commas with pipes
$data = str_replace (',', '|', $row);
//Count number of pipes
$fields = substr_count($row, '|');
//Calculate the number of empty fields & insert pipes
$emptyfields = str_repeat('$|', (26-$fields));
//concatenate data with empty fields
$data .= $emptyfields;
//write data to file
file_put_contents (signals.dat, $data);
}//end while
}
else{
echo "0 results";
}
?>
2
Answers
Why have any PHP code?
Given this query:
It generates the file
xx.txt
:Meanwhile, in your code,
if (...num_rows>0)
is redundant becausewhile(...)
will do nothing if there are no rows. Removing theif
will happen to fix the bug. The bug isresult
instead of$result
.