I'm working on outputting data from MySQL database in XML format, so I made a php file that displays data from database in XML format on the page.
<?php
// Return all existing nid in array (Different types of form);
function nid(){
$query = "SELECT w.nid
FROM webform w";
$result = mysql_query($query);
$table = array();
while ($row = mysql_fetch_row($result)){
$table[] = $row[0];
}
return $table;
}
// Return existing rows of corresponding nid
function sid($nid){
$query = "SELECT ws.sid
FROM webform_submissions ws
WHERE ws.nid = $nid";
$result = mysql_query($query);
$table = array();
while ($row = mysql_fetch_row($result)){
$table[] = $row[0];
}
return $table;
}
// Return corresponding components of nid;
function cid($nid){
$query = "SELECT wc.form_key
FROM webform_component wc
WHERE wc.nid = $nid
ORDER BY wc.cid ASC";
$result = mysql_query($query);
$table = array();
while ($row = mysql_fetch_row($result)){
$table[] = $row[0];
}
return $table;
}
// Return values of fields corresponding to nid and sid
function data($nid, $sid){
$query = "SELECT wsd.data
FROM webform_submitted_data wsd
WHERE wsd.nid = $nid AND wsd.sid = $sid
ORDER BY wsd.sid ASC";
$result = mysql_query($query);
$table = array();
while ($row = mysql_fetch_row($result)){
$table[] = $row[0];
}
return $table;
}
// Define Constants
DEFINE("DB_SERVER", "localhost");
DEFINE("DB_USER", "root");
DEFINE("DB_PASS", "");
DEFINE("DB_NAME", "drupal7");
//Establish Connection
mysql_connect(DB_SERVER, DB_USER, DB_PASS)
or die("Unable to connect to MySQL");
//Select Database
mysql_select_db(DB_NAME)
or die("Could not connect to the database");
$xml_output = "<?xml version=\"1.0\" ?>\n";
$xml_output .= "<schema>";
foreach (nid() as $nid){
$xml_output .= "<form fid=\"$nid\">\n";
foreach (sid($nid) as $sid){
$xml_output .= "<row rid=\"$sid\">\n";
for ($i = 0; $i < count(cid($nid)); $i++){
$tag_array = cid($nid);
$value_array = data($nid, $sid);
$tag_row = $tag_array[$i];
$value_row = $value_array[$i];
$xml_output .= "<$tag_row>\n";
$xml_output .= "$value_row\n";
$xml_output .= "</$tag_row>\n";
}
$xml_output .= "</row>\n";
}
$xml_output .= "</form>\n";
}
$xml_output .= "</schema>";
header("Content-type: text/xml");
echo $xml_output;
mysql_close();
?>
But I can't see to find a way to access the XML data or download it as XML file.
Here's how the output looks like when I run it.
Thanks in advance
Don't use strings to build your xml data. You should be using something like SimpleXMLElement
See How to generate XML file dynamically using PHP?
Instead of:
$table[] = $row[0];
Try using the array_push function:
array_push($table,$row[0]);
Related
I am trying to create a single JSON file displaying data from two different tables. I can manage to fetch them, however I don't understand how to concatenate the two arrays. I am new to JSON. Any suggestions/tutorials would be very helpful. Thanks in advance.
Here the expected JSON:
{
"array1":[
{"days":"1","id":"1","image":"image1.jpg, image2.jpg, image3.jpg, image4.jpg"},{"days":"2","id":"1","image":"elephanta.jpg,image2.jpg,image1.jpg,imagica.jpg"},
{"days":"3","id":"1","image":"image3"},{"days":"4","id":"2","image":"image4"}
],
"array2":[
{"id":"1","image_1":"image1.jpg"},
{"id":"2","image_1":"image2.jpg"},
{"id":"3","image_1":"image3.jpg"}
]
}
but the JSON that I get is this:
{
"array1":[
{"days":"1","id":"1","image":"image1.jpg, image2.jpg, image3.jpg, image4.jpg"},{"days":"2","id":"1","image":"elephanta.jpg,image2.jpg,image1.jpg,imagica.jpg"},
{"days":"3","id":"1","image":"image3"},{"days":"4","id":"2","image":"image4"}
]},
{"array2":[
{"id":"1","image_1":"image1.jpg"},
{"id":"2","image_1":"image2.jpg"},{"id":"3","image_1":"image3.jpg"
}
]}
PHP code:
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from image_data";
$sql1 = "select * from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageArray = array();
$imageArray1 = array();
$imageArray["array1"] = array();
$imageArray1["array2"] = array();
while($row =mysqli_fetch_array($result))
{
$tmp = array();
$tmp["days"] = $row["id"];
$tmp["id"] = $row["place_id"];
$tmp["image"] = $row["image"];
array_push($imageArray["array1"], $tmp);
// $imageArray[] = $row;
}
while($row =mysqli_fetch_array($result1))
{
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["image_1"] = $row["image"];
array_push($imageArray1["array2"], $tmp);
// $imageArray[] = $row;
}
echo json_encode($imageArray);
echo ",";
echo json_encode($imageArray1);
//close the db connection
mysqli_close($connection);
?>
If you want the 2 sub arrays to belong to the same array then use only one array and address the 2 sub arrays like this when loading them
$imageArray["array1"][] = $tmp;
and
$imageArray["array2"][] = $tmp;
Amended code
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from image_data";
$sql1 = "select * from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageArray = array(); // <- removed other arrays
while($row =mysqli_fetch_array($result))
{
$tmp = array();
$tmp["days"] = $row["id"];
$tmp["id"] = $row["place_id"];
$tmp["image"] = $row["image"];
$imageArray["array1"][] = $tmp; // <- address array like this
}
while($row =mysqli_fetch_array($result1))
{
$tmp = array();
$tmp["id"] = $row["id"];
$tmp["image_1"] = $row["image"];
$imageArray["array2"][] = $tmp; // <- address array like this
}
echo json_encode($imageArray); // <- only one json_encode
//close the db connection
mysqli_close($connection);
?>
I would have done it this way using stdObject and selecting the specific data from the tables, and using mysqli_fetch_obect() so there is a lot less you have to do woman-draulically
<?php
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","test") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
// only select what you want
$sql = "select id,place_id,image from image_data";
$sql1 = "select id,image from one";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$result1 = mysqli_query($connection, $sql1) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$imageObject = new stdObject();
while($row =mysqli_fetch_object($result))
{
$imageObject->array1[] = $row;
}
while($row =mysqli_fetch_object($result1))
{
$imageObject->array2[] = $row;
}
echo json_encode($imageObject);
?>
I have been trying to create a PHP function that can display a MySQL table as a HTML table using PHP. So far I am able to output any table I choice, yet I am encountering a problem when the MySQL table contains empty rows, because empty cells result in the HTML tables. My code is as such:
<?php
function getTABLE(){
$db_host = 'HOST.com';
$db_user = 'USER1';
$db_pwd = 'PASSWORD';
$database = 'testdb';
$table = 'FAQTable';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
//// sending query and only result cell that are not NULL
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h3><center>Table: {$table}</h3>";
echo "<table border='1'><tr>";
//// printing table headers
for($i=0; $i<$fields_num; $i++){
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
//// printing table rows
while($row = mysql_fetch_row($result)){
echo "<tr>";
//// $row is array... foreach( .. ) puts every element
//// of $row to $cell variable
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>";
}
print "</TABLE>";
mysql_close();
}
print getTABLE();
?>
My dilemma is in the "printing table rows" section of the code. I am hoping there is a way in the while($row = mysql_fetch_row($result)) to only accept rows that have values in them. Any ideas?
I have already tried using the following lines with no luck:
$result = mysql_query("SELECT * FROM {$table} WHERE * IS NOT NULL");
$result = mysql_query("SELECT COUNT(id) FROM {$table} where answer IS NOT NULL or answer <>'' ");
$result = mysql_query('SELECT COUNT(*) FROM {$table} WHERE answer <> ""');
$result = mysql_query("SELECT * FROM {$table} WHERE CHAR_LENGTH>0");
$result = mysql_query("SELECT * FROM {$table} WHERE val1 is <> '' ");
$result = mysql_query("SELECT * FROM {$table} WHERE col1 is <> '' ");
//// Outputs funky count in a separate table, but not the desired table with no empty cells
$result = mysql_query("SELECT COUNT(answer) FROM {$table} WHERE CHAR_LENGTH(answer)>0");
$result = mysql_query("SELECT COUNT(answer) FROM {$table} WHERE LENGTH(answer)>0");
$reslts = mysql_query("SELECT * FROM {$table}");
while($row = mysql_fetch_row($reslts)){
$empty_count = 0;
$count = count($row);
for($i = 0; $i < $count; $i++)
if($row[$i] === '' || $row[$i] === 'NULL')
$empty_count++;
$result = ($count);
}
So Thanks To Paul Spiegal for helping with this PHP function that can output any MySQL Table into a HTML Table to be displayed on a website... The working function is as follows, just change the values for the variables to access any MySQL data:
function getTABLE(){
$db_host = 'www.host.com';
$db_user = 'user1';
$db_pwd = 'password';
$database = 'testdb';
$table = 'MyTable';
if (!mysql_connect($db_host, $db_user, $db_pwd))
die("Can't connect to database");
if (!mysql_select_db($database))
die("Can't select database");
//// sending query
$result = mysql_query("SELECT * FROM {$table}");
if (!$result) {
die("Query to show fields from table failed");
}
$fields_num = mysql_num_fields($result);
echo "<h3><center>Table: {$table}</h3>";
echo "<table border='1'><tr>";
//// printing table headers
for($i=0; $i<$fields_num; $i++){
$field = mysql_fetch_field($result);
echo "<td>{$field->name}</td>";
}
//// printing table rows
while($row = mysql_fetch_row($result)){
echo "<tr>";
if (strlen(implode('', $row )) == 0) {
continue;
}else {
foreach($row as $cell)
echo "<td>$cell</td>";
echo "</tr>";
}
}
print "</TABLE>";
mysql_close();
}
print getTABLE();
Using implode() function, you can combine all cells into one string. If that string is empty, you skip printing that row.
while($row = mysql_fetch_row($result)){
if (strlen(implode('', $row)) == 0) {
continue; // skip this empty row
} else {
// TODO: print this row
}
}
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.
I have stored the data in a mysql database, I want to know how I can split the data in each different array before output them in php?
<?php
define('DB_HOST', 'localhost');
define('DB_USER', 'myusername');
define('DB_PASSWORD', 'mypassword');
define('DB_DATABASE', 'mydbname');
$errmsg_arr = array();
$errflag = false;
$link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);
if(!$link)
{
die('Failed to connect to server: ' . mysql_error());
}
$db = mysql_select_db(DB_DATABASE);
if(!$db)
{
die("Unable to select database");
}
if($errflag)
{
$_SESSION['ERRMSG_ARR'] = $errmsg_arr;
echo implode('<br />',$errmsg_arr);
}
else
{
$qrytable1="SELECT id, mydata FROM mydb ";
$result1=mysql_query($qrytable1) or die('Error:<br />' . $qry . '<br />' . mysql_error());
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
}
}
?>
On my PHP page it show something like this:
<tr><td>my data 1</td></tr><tr><td>my data 2</td></tr><tr><td>my data 3</td></tr><tr><td>my data 4</td></tr>
I want to split them up by turn into array and output them with each different array to something like this:
mydata1
mydata2
mydata3
mydata4
How I can split the data into array before I could output them in my php?
Are you looking for something like this?
(consider it as an example, but, as #BenM, consider using PDO)
$sql = 'SELECT * FROM country';
$query = mysql_query($sql);
$countries = array();
while ($country = mysql_fetch_assoc($query)){ $countries[] = $country; }
This will allow you to use
foreach ($countries as $country) {
echo $country['name'];
}
Your data is already in an array. That's what this line does:
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
}
If you need to access the array outside of the while loop you could do this..
$myArray = array();
while ($row = mysql_fetch_array($result1)){
echo "<tr><td>".$row['mydata']."</td></tr>";
foreach($row as $key=>$val){
$myArray[$key] = $val;
}
}
actually.. assuming your query returns multiple rows it would be a multidimensional array..
$myArray = array();
$i = 0;
while ($row = mysql_fetch_array($result1)){
echo "<tr><td>".$row['mydata']."</td></tr>";
foreach($row as $key=>$val){
$myArray[$i][$key] = $val;
$i++;
}
}
If I am right than along with getting data in array you want to remove the space in between the data
try this
while ($row = mysql_fetch_array($result1))
{
echo "<tr><td>".$row['mydata']."</td></tr>";
$myArr[] = $row['mydata'];
}
foreach($myarr as $key=>$value)
{
$myArr[$key] = str_replace(" ","",$value);
}
str_replace will remove the spaces.
You can used this,
$db->setQuery($query);
$rows = $db->loadObjectList();
$i=0;
foreach($rows as $row){
//$row;
$image = json_decode($row->images);
// split code
$str = utf8_encode($row->introtext);
$order = array("<p>", "</p>", "\n", "\r");
$replace = '';
$introtext = str_replace($order, $replace, $str);
$introtext_split = explode("|", $introtext);
$data[0]->designation = preg_replace('#<br />?#', "\n", $introtext_split[0]);
$data[0]->description = preg_replace('#<br />?#', "\n\n", $introtext_split[1]);
$data[0]->small_description = preg_replace('#<br />?#', "\n\n", $introtext_split[2]);
}
In data used any tag, Or this tag replace using following section :
$str = utf8_encode($row->introtext);
$order = array("<p>", "</p>", "\n", "\r");
I think its useful to you.
I want to make a Navigation with 2 levels.
My Code so far
<?php
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='' ORDER BY name");
$result = mysql_query($sql);
$list = array();
while ($row = mysql_fetch_assoc($result)) {
$list[] = $row;
}
foreach ($list as $kat) {
echo '<li>' . $kat['name'] . '</li>';
}
?>
Nested Sets are at the moment too tricky for me.
I want at the end this.
<li>$kat['name']
<li>$kat['name'] from PID</li>
</li>
MySQL:
http://i46.tinypic.com/35052m0.png - IMG
No I want to get the things our of the MySQL DB see the image Link.
MySQL:
id—–pid——name
1——0——–name1
2——0——–name2
3——0——–name3
4——3——–name3.1
5——3——–name3.2
<?php
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='' ORDER BY name");
$result = mysql_query($sql);
$list = array();
while ($row = mysql_fetch_assoc($result)) {
$list[$row['id']] = $row;
$sql = ("SELECT name, id, pid FROM tl_table WHERE pid='".$row['id']."' ORDER BY name");
$res = mysql_query($sql);
while($rw = mysql_fetch_assoc($res)){
$list[$row['id']]['sub'][] = $rw;
}
}
echo "<pre>";
print_r($list);
?>