Write in html file with PHP - php

I want to write in html file with PHP but is written only the last:
Please help me:
<?php
$link = mysql_connect('my_server', 'user', 'password')
or die("Can't");
$db = mysql_select_db('database')
or die ("Can't select");
$sql = 'SELECT * FROM News LIMIT 3';
$retval = mysql_query($sql,$link);
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//echo "<pre>"; print_r($row); echo "</pre>";
$content = '<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<div class="block">';
$content .=''.$row['Title'].'';
$content .='<div class="date">';
$content .=$row['Date'];
$content .='</div>';
$content .= '</div>';
$filename ="footer.html";
#unlink($filename);
$handle = fopen("footer.html", 'w+');
echo $row['Title'].'<br>';
if ($handle)
{
if (!fwrite($handle, $content))
die("cant' write");
}
}
?>
Write only the last query..
I tried but did not receive...

You need to put initial $content variable & file write part outside for loop.
$content = '';
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//echo "<pre>"; print_r($row); echo "</pre>";
$content .= '<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<div class="block">';
$content .=''.$row['Title'].'';
$content .='<div class="date">';
$content .=$row['Date'];
$content .='</div>';
$content .= '</div>';
}
$filename ="footer.html";
#unlink($filename);
$handle = fopen("footer.html", 'w+');
echo $row['Title'].'<br>';
if ($handle)
{
if (!fwrite($handle, $content))
die("cant' write");
}

Related

Change format JSON output in file?

I have the next PHP code that makes me a JSON file with data from my SQL table:
<?php
$mysqli = new mysqli('localhost','root','xxxx','xxxx');
$myArray = array();
$result = $mysqli->query("SELECT CONCAT(Datum , ' ', Tijd) as Datum, KleurL FROM metingen order by Datum ASC limit 20");
if ($result) {
$tempArray = array();
while ($row = $result->fetch_object()) {
$tempArray = $row;
array_push($myArray, $tempArray);
}
echo json_encode($myArray,JSON_NUMERIC_CHECK);
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, json_encode($myArray,JSON_NUMERIC_CHECK));
fclose($fp);
}
$result->close();
$mysqli->close();
?>
The ouput of the JSON file looks like this.:
[{"Datum":"17-01-2019 10:31:39","KleurL":17.68},{"Datum":"17-01-2019 11:10:59","KleurL":71.76},{"Datum":"18-01-2019 08:40:41","KleurL":70.7},{"Datum":"18-01-2019 10:30:01","KleurL":71.03},{"Datum":"18-01-2019 12:05:46","KleurL":70.56},{"Datum":"18-01-2019 14:31:58","KleurL":16.2}]
But I would like to see that the output of that file looks like this.:
[
[
17.68,
17-01-2019 10:31:39
],
[
18.11,
17-01-2019 11:15:20
]
]
How can I get this output in the JSON file?
The following code should achieve what you are trying to do. This code was tested on my pc and seems to be working perfectly.
<?php $mysqli = new mysqli('localhost', 'root', 'xxxx', 'xxxx');
if ($result = $mysqli->query("SELECT CONCAT(Datum , ' ', Tijd) as Datum, KleurL FROM metingen order by Datum ASC limit 20")) {
$current_row_number = 0;
$output = "[";
while ($row = $result->fetch_object()) {
if ($current_row_number > 0) {
$output = $output . ","; //add comma between each row
}
$output = $output . "[" . $row->KleurL . "," . $row->Datum . "]"; //add each row
$current_row_number++;
}
$output = $output . "]";
echo $output;
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, $output);
fclose($fp);
}
$result->close();
$mysqli->close();
If you want to format the output nicely, use the following code:
<?php $mysqli = new mysqli('localhost', 'root', '244466666', 'tkd');
if ($result = $mysqli->query("SELECT CONCAT(Datum , ' ', Tijd) as Datum, KleurL FROM metingen order by Datum ASC limit 20")) {
$current_row_number = 0;
$output = "[";
while ($row = $result->fetch_object()) {
if ($current_row_number > 0) {
$output = $output . ","; //add comma between each row
}
$output = $output . "\n\t" . "[" . "\n\t\t" . $row->KleurL . "," . "\n\t\t" . $row->Datum . "\n\t" . "]"; //add each row
$current_row_number++;
}
$output = $output . "\n]";
// echo $output; //if you want to see the output in the terminal/command prompt
echo "<pre>" . $output . "</pre>"; //if you want to see the output in a browser
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, $output);
fclose($fp);
}
$result->close();
$mysqli->close();
You can use the json_encode() JSON_PRETTY_PRINT options:
json_encode($myArray,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
edit:
if you are using windows, you need to change the carriage return using something like this:
$myArray = array("test" => "data");
$buffer = json_encode($myArray,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
echo str_replace("\n", "\r\n", $buffer);
// or
$fp = fopen('resultsv2.json', 'w');
fwrite($fp, str_replace("\n", "\r\n", $buffer));
fclose($fp);
If you are printing this into the browser you need to use <pre> tags
<pre>
echo json_encode($myArray,JSON_NUMERIC_CHECK | JSON_PRETTY_PRINT);
</pre>

Check and set array to null

I am trying to set result_array to null if there are no existing data in the database. The result should be shown in a table format but I cannot get the result_array as null and keep getting error on the line $result_array[] = null;
global $db;
$db = new mysqli();
$db->connect("localhost", "root", "", "databasename");
$db->set_charset("utf8");
if ($db->connect_errno) {
printf("Connection has failed: %s\n", $db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="url">';
$html .= '<h3>name</h3>';
$html .= '</a>';
$html .= '</li>';
$search = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search = $db->real_escape_string($search);
if (strlen($search) >= 1 && $search !== ' ') {
$query = 'SELECT * FROM tablename WHERE name LIKE "%'.$search.'%"';
$result = $db->query($query) or trigger_error($db->error."[$query]");
if(!$results = $result->fetch_array()){
$resultArray[] = null;
}
else{
while($results = $result->fetch_array()) {
$resultArray[] = $results;
}
}
if (isset($resultArray)) {
foreach ($resultArray as $result) {
$show_name = preg_replace("/".$search."/i", "<b class='highlight'>".$search."</b>", $result['name']);
$show_url = 'index.php';
$out = str_replace('name', $show_name, $html);
$out = str_replace('url', $show_url, $out);
$_SESSION['result']= $result['name'];
echo($out);
}
}else{
$out = str_replace('url', 'javascript:void(0);', $html);
$out = str_replace('name', '<b>No Results.</b>', $out);
echo($out);
}
}
?>
why aren't you using this?
...
$result_array = array();
if(!$results = $result->fetch_array()){
//do nothing
}
else{
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
...
Also please use either $result_array or $resultArray

First array from query PHP

I have a problem with my code. I want to get the first array from query and show it, after what show the next 2.
For the first Array in query I want to show img for the next 2 only the title
My code:
$link = mysql_connect('server', 'user', 'password')
or die("Can't");
$db = mysql_select_db('database')
or die ("can't");
$sql = 'SELECT * FROM News LIMIT 3';
$retval = mysql_query($sql,$link);
$filename ="footer.html";
$handle = fopen("footer.html", 'w+');
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
//echo "<pre>"; print_r($row); echo "</pre>";
$content = '<meta http-equiv="content-type" content="text/html;charset=UTF-8"/>
<div class="block_articles">
<div class="block_header" >
<div class="headerlink" >
<a href="'.$sitelink.'" target="_blank"></div></div>';
$content .= '<img src="'.$sitelink.'news/'.$row['ImageName'].'" alt="'.htmlspecialchars($row['Title']).'" >';
$content .= ''.$row['Title'].'';
$content .= '<div class="date">';
$content .= $row['Date'];
$content .= '</div>';
$content .= '</div>';
echo $row['Title'].'<br>';
if ($handle)
{
if (!fwrite($handle, $content))
die("can't");
}
}
Based on your comments, you want to use a basic loop counter and change the behavior based on the counter:
theCurrentRow = 0;
while ($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
theCurrentRow++;
if (theCurrentRow == 1) {
//show the images
}
else {
// show the title
}
}
Also to reiterate #AmalMurali's comment: don't use mysql_* functions, they're deprecated: http://php.net/manual/en/mysqlinfo.api.choosing.php

How to create a new file in every iteration of a PHP program?

I am creating a file using PHP but I am unable to create a new file in every execution of the application. I am generating an XML file using a database. I want a new file in every execution of my code, how can I do that?
This is my code:
<?php
$config['mysql_host'] = "localhost";
$config['mysql_user'] = "root";
$config['mysql_pass'] = "root";
$config['db_name'] = "dcu";
$config['table_name'] = "readingsThreePhase";
//$config['table_name1'] = "miosD1";
mysql_connect($config['mysql_host'],$config['mysql_user'],$config['mysql_pass']);
#mysql_select_db($config['db_name']) or die( "Unable to select database");
function writeMsg()
{
//echo "Hello world!";
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $config['table_name']."D1";
$xml .= "<$root_element>";
$sql = "SELECT * FROM dcu.readingsThreePhase where meterId=3 order by recordTime DESC limit 1";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
//$xml .= "<".$config['table_name'].">\n";
$xml .= "<".$config['miosD1'].">\n";
foreach($result_array as $key => $value)
{
if($value==NULL)
{
continue;
}
$xml .= "<$key>";
$xml .= "$value";
$xml .= "</$key>\n";
}
$xml.="</".$config['miosD1'].">";
}
}
$xml .= "</$root_element>";
header ("Content-Type:text/xml");
echo $xml;
$file=fopen("xmlfilefirst.xml","a");
fwrite($file,$xml);
fclose($file);
}
writeMsg();
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
$root_element = $config['table_name']."s";
$xml .= "<$root_element>";
$sql = "SELECT * FROM dcu.readingsThreePhase where meterId=3 order by recordTime DESC limit 1";
$result = mysql_query($sql);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
if(mysql_num_rows($result)>0)
{
while($result_array = mysql_fetch_assoc($result))
{
$xml .= "<".$config['table_name'].">\n";
foreach($result_array as $key => $value)
{
if($value==NULL)
{
continue;
}
$xml .= "<$key>";
$xml .= "$value";
$xml .= "</$key>\n";
}
$xml.="</".$config['table_name'].">";
}
}
$xml .= "</$root_element>";
header ("Content-Type:text/xml");
echo $xml;
$file=fopen("xmlfilefirst.xml","a");
fwrite($file,$xml);
fclose($file);
?>
use file_put_contents
This function is identical to calling fopen(), fwrite() and fclose() successively to write data to a file.
If filename does not exist, the file is created. Otherwise, the existing file is overwritten, unless the FILE_APPEND flag is set.
To create a new file every time, you need a way to generate a unique filename. You can either create this name with some sort of gibberish, such as:
do {
$filename = 'my_file_' . substr(md5(time( ), 0, 8 ) . '.xml';
} while( file_exists( $filename ) );
Or, you can attempt with some sort of numeric naming convention ('myfile1.xml', 'myfile2.xml', 'myfile3.xml' etc). This would mean getting a listing of the current directory. If no files are present, start with 1. Otherwise, start with the count of files + 1 and name your file with that.
See also the documentation for fopen. Most of the modes will attempt to create a file if the specified filename does not exist, so just coming up with a unique filename is the trick.

how to use foreach inside while loop?

Currently I am using following code to get data sorted by starting letter of name, if you run this code you will get what i am trying to create
<?php
$dirs = array('Aname1','Aname2','Aname3','A Nmae','Bname ','Cname','Cardiff','Dname','Dname',);
$cur_let = null;
foreach ($dirs as $dir) {
if ($cur_let !== strtoupper(substr($dir,0,1))){
$cur_let = strtoupper(substr($dir,0,1));
echo "<li class=\"title\">".$cur_let."</li>";
}
echo "<li class=\"clear\">
<div class=\"name\">".$dir."</div>
<div class=\"mobile\"></div>
<div class=\"telephone\"></div>
<div class=\"email\"></div>
<div class=\"action\">edit | delete</div>
<div class=\"clear\"></div>
</li>";
}
but how to use above loop inside following to get vales from database and it should be display like (I want highlight first letter) http://i.stack.imgur.com/bLHVD.jpg
$query = "SELECT * FROM phone_number";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$names = $row['name'].",";
}
?>
With MySQLi:
$last_letter = null;
$query = "SELECT name FROM phone_number ORDER BY name";
$sql = $mysqli->query($query);
while($row = $sql->fetch_assoc()) {
$first_letter = substr(ucfirst($row['name']), 0, 1);
if($last_letter != $first_letter) {
$last_letter = $first_letter;
echo '<div class="letter">', $first_letter, '</div>';
}
echo ucwords($row['name']), '<br />';
}
With mysql_* deprecated functions:
$last_letter = null;
$query = "SELECT name FROM phone_number ORDER BY name";
$sql = mysql_query($query);
while($row = mysql_fetch_array($sql)) {
$first_letter = substr(ucfirst($row['name']), 0, 1);
if($last_letter != $first_letter) {
$last_letter = $first_letter;
echo '<div class="letter">', $first_letter, '</div>';
}
echo ucwords($row['name']), '<br />';
}
Try something like this:
$query = "SELECT * FROM phone_number ORDER BY name DESC";
$result = mysql_query($query) or die(mysql_error());
$lastLetter = '';
$html = '<ul>';
while ($row = mysql_fetch_array($result)) {
$name = $row['name'];
if (strtoupper($name[0]) !== $lastLetter) {
if ($lastLetter !== '')
$html .= '</ul></li>';
$lastLetter = strtoupper($name[0]);
$html .= '<li class="title">' . $lastLetter;
$html .= '<ul>';
}
$html .= '<li>' . $name . '</li>';
}
$html .= '</ul></li></ul>';

Categories