Export MSSQL Query To CSV File From PHP - php

I am using the below syntax within my joomla article and I am in need of a way to add a php button (I know the syntax or this) - and on the button press event fire off exporting the SQL Query Results (header and data) to a csv file. This is the syntax i am using to populate a table. Is this easily ammendable to add in a function to export to .csv also?
<html>
<body>
<form method="POST">
</form>
</body>
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'IP Address';
$option['user'] = 'username';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance($option);
$query = $db->getQuery(true);
$query = "Select height, weight, userID, name from personelinfo;";
$db->setQuery($query);
$query = $db->loadObjectList();
if ($query)
{
?>
<table border="1">
<thead>
<tr>
<th>height </th>
<th>weight </th>
<th>userID </th>
<th>name </th>
</tr>
</thead>
<?php
foreach ($query as $res)
{
print "<tr>";
print "<td>" . $res->height . "</td>";
print "<td>" . $res->weight . "</td>";
print "<td>" . $res->userID . "</td>";
print "<td>" . $res->name . "</td>";
print "</tr>";
}
}
?>
</table>
</html>

You want to have much more separation between your PHP and HTML output. This will serve you well when you want to output other formats such as CSV. Here I get the database results at the top of the file and load them into an array, before any output is done — ideally this would be done in a separate file.
Then we can check if CSV output is desired. I've changed the database code to return an associative array instead of an object, this makes it trivial to pass each row to fputcsv().
Note I've also used alternative syntax and short echo tags to reduce PHP/HTML intermixing. This is a good practice to get into. Finally, your HTML was a mess; you were closing the body before outputting the table, and omitting the <head> and <tbody> elements.
<?php
$option = array();
$option['driver'] = 'mssql';
$option['host'] = 'IP Address';
$option['user'] = 'username';
$option['password'] = 'password';
$option['database'] = 'database';
$option['prefix'] = '';
$db = JDatabase::getInstance($option);
$query = "Select height, weight, userID, name from personelinfo;";
$db->setQuery($query);
$resultset = $db->loadAssocList();
if (!empty($_GET["csv"])) {
$out = fopen("php://stdout");
header("Content-Type: text/csv");
foreach ($resultset as $res) {
fputcsv($out, $res);
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<?php if(count($resultset):?>
<table border="1">
<thead>
<tr>
<th>height </th>
<th>weight </th>
<th>userID </th>
<th>name </th>
</tr>
</thead>
<tbody>
<?php foreach($resultset as $res):?>
<tr>
<td><?= $res["height"] ?></td>
<td><?= $res["weight"] ?></td>
<td><?= $res["userID"] ?></td>
<td><?= $res["name"] ?></td>
</tr>
<?php endforeach;?>
</tbody>
</table>
<form method="get">
<button type="submit" name="csv" value="1">Export to CSV</button>
</form>
<?php endif;?>
</body>
</html>

Related

how to display an sqli database

I need to be able to display the contents of my database but I am not sure how to do this using sqli, any help provided will be appreciated
<?php
ini_set("display_errors",1);
error_reporting(E_ALL);
$servername = "server";
$username = "username";
$password = "password";
$dbname = "sql1702520";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
I tried to use a mysql query bellow to extract the data from the database, however i have been told that it is not possible to use mysql and sqli
/*
$result = mysql_query("SELECT * FROM sql1702520 ");
*/
$conn->close();
?>
Html to display the database
<html>
<table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
<thead>
<tr>
<th>id</th>
<th>Name</th>
<th>image</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<?php
Tried using this to display the table data however mysql would be required to do it this way
while( $row1 = mysqli_fetch_assoc( $result ) ){
foreach ($row1 as $row){
?>
<tr>
<td><?php $row['id'] ?></td>
<td><?php $row['hname'] ?></td>
<td><?php $row['himage'] ?></td>
<td><?php $row['hdesc'] ?></td>
</tr>
<?php
}
}
?>
</tbody>
</table>
<?php mysql_close($connector); ?>
</body>
</html>
assuming that your tablename (what looks suspiciously like your database name) for mysqli you would have to use the mysqli_query function to send your query.
$result = mysql_query($conn,"SELECT * FROM sql1702520 ");
and mysqli_fetch_assocfor your loop
$row = mysqli_fetch_assoc($result);
you can ditch the for-each loop. the while loop is sufficient.
for further help an error message would help.

Update MySQL database using HTML/PHP table (inline)

I'm trying to update my database using the html/php table with save button to confirm the changes and save in database.
Here's my Table
How can I edit the 'Quantity' row like text field and save with the button to confirm.
this is my table
<table class=" table-responsive table table-striped table-bordered table-hover ">
<thead>
<tr>
<th>Item #</th>
<th>Description</th>
<th>Unit</th>
<th>Quantity</th>
</tr>
</thead>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "db";
$port = "3306";
$conn = new mysqli($servername, $username, $password, $dbName, $port);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$sql = "SELECT * FROM product";
$result1 = $conn->query($sql);
$result2 = $conn->query($sql);
?>
<tbody>
<?php
while ($row = mysqli_fetch_array($result1)) {
echo "
<tr>
<td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td>" . $row[2] . "</td>
<td>0</td>
</tr>";
}
?>
</tbody>
</table>
Please help. Thanks!
Put your table inside a form.
<form action="give_your_action_page" method="post">
<table class=" table-responsive table table-striped table-bordered table-hover ">
<thead>
<tr>
<th>Item #</th>
<th>Description</th>
<th>Unit</th>
<th>Quantity</th>
</tr>
</thead>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbName = "db";
$port = "3306";
$conn = new mysqli($servername, $username, $password, $dbName, $port);
if($conn->connect_error)
{
die("Connection Failed: ".$conn->connect_error);
}
$sql = "SELECT * FROM product";
$result1 = $conn->query($sql);
$result2 = $conn->query($sql);
?>
<tbody>
<?php
while ($row = mysqli_fetch_array($result1)) {
echo "
<tr>
<td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td>" . $row[2] . "</td>
<td><input type='number name='".$row[1]."' value='".$row[3]."'/></td>
</tr>";
}
?>
</tbody>
</table>
Now at your action page you can access the form values using $_POST array using the value in "Description" field.
For eg : $_POST["banana"] will give the quantity of banana.
Update the database using these values.
You're going to change a field that is not in the database?
because
<tr>
<td>" . $row[0] . "</td>
<td>" . $row[1] . "</td>
<td>" . $row[2] . "</td>
<td>0</td> ----------------> ? (empty) ?
</tr>
You must first create a field called Quantityin your database, then try again if it was a difficult ask questions.
Ok your Code is a really bad , well most of it , and your Q was really hard to understand , but its ok , try to be more accurate next time =) , this answer that i came with is depends on my understanding to what you tried to ask .
I suggest that you topic from w3shool : Select data from database
In my answer or in my Code if we can say that , I used PDO , Whats PDO ?
PDO is an acronym for PHP Data Objects. PDO is a lean, consistent way
to access databases. This means developers can write portable code
much easier. PDO is not an abstraction layer like PearDB. PDO is a
more like a data access layer which uses a unified API (Application
Programming Interface).
Search for it on Google and read some info about how it works and try to learn it , its simple and its the same as ( MYSQLI ) .
This is my Code which i tested it many times and it works , this code can be written in many ways but i tried to make it as simple as i can .
<?php
// Start of the first part ( connect to the database usnig PDO
$servername = "localhost";
$username = "root";
$password = "";
$database = "your database name";
try {
$conn = new PDO("mysql:host=$servername;dbname=$database", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
echo "Connection failed: " . $e->getMessage();
}
// END of the first part
// second part : bring the new quantity from the field
if(isset($_POST['update']))
{
$newquantity = $_POST['newQu'];
$itemName = $_POST['item'];
$UpdateOnQuantity = $conn->prepare( "UPDATE hr SET Quantity = ? WHERE Item = ?");
$UpdateOnQuantity->execute(array($newquantity,$itemName));
if($UpdateOnQuantity)
{
}
else
{
echo "error";
}
}
$FetchNewQuantity = $conn->prepare("SELECT * FROM hr");
$FetchNewQuantity->execute();
?>
<html>
<head>
</head>
<body>
<table class=" table-responsive table table-striped table-bordered table-hover ">
<thead>
<tr>
<th>Item #</th>
<th>Description</th>
<th>Unit</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<?php
while($FetchedData = $FetchNewQuantity->FETCH(PDO::FETCH_ASSOC))
{
?>
<tr>
<td><?php echo $FetchedData['Item']; ?></td>
<td><?php echo $FetchedData['Description']; ?></td>
<td><?php echo $FetchedData['Unit']; ?><td>
<td><?php echo $FetchedData['Quantity']; ?></td>
<td>
<form action="test2.php" method="POST">
<input type="hidden" name="item" value="<?php echo $FetchedData['Item']; ?>">
<input type="text" name="newQu">
<input type="submit" name="update">
</form>
</td>
</tr>
<?php } ?>
</tbody>
</table>
</body>
</html>
This is my code hope it help you , i tested many times as i said so if it did not work with you let me know , and if you did not like PDO just replace PDO code with the normal Mysqli code .
Edit : i edited the code again , did not noticed that you linked your table . i added a while loop so it can show all the data in your table .

How to apply for loop to container in PHP

I am trying to run PHP code in WAMP server using MySQL. I am creating one container,
I don't know how many containers I need. Somehow I have the count of containers generated dynamically.
I want as many containers as count. I want to apply the for loop to the below code based on count of containers.
Also I need to create CSS container classes based on count.
In the query where i am using where clause(Where Entity='ATA'), i have array of data to apply in where clause, here i have shown only one(ATA), i need the containers based on count.
<form>
<div id="container">
<div id="content">
<!-- all you need with Tablecloth is a regular, well formed table. No need for id's, class names... -->
<table cellspacing="0" cellpadding="0">
<tr >
<th class="lightcolor" style="width:60px; height:30px;"><h2>Server Name</h2></th>
<th class="lightcolor" style="width:60px; height:30px;"><h2>IP Address</h2></th>
</tr>
<?php
$user_name = "root";
$password = "";
$database = "atssautomationgnoc";
$server = "localhost";
$con = mysqli_connect($server, $user_name, $password);
$db_found = mysqli_select_db($con,$database);
$query = "SELECT Servername,IPAddress FROM t_applicationstatus Where Entity='ATA' order by FIELD(LiveStatus,'RTO','OK')";
$result=mysqli_query($con,$query);
$Names = array();
if($result == FALSE)
{
die(mysql_error());
}
$i=0;
while ($row = mysqli_fetch_array($result))
{
$rowsA[] = $row;
}
foreach($rowsA as $row)
{
$rowsA[$i]=$row['Servername'];
$rowsA[$i] = $row['IPAddress'];
echo "<tr>";
echo "<td id=health>" ;
echo $row['Servername'] ;
echo " </td>";
echo "<td id=health>" ;
echo $row['IPAddress'];
echo " </td>";
echo " </td>";
echo "</tr>";
}
?>
</table>
</div>
</form>
Say, all of the criterias you wish to specify in where clause are stored in array $entityArr.You then should add an extra loop on top of the <table> element. Try the following code.
<div id="container">
<div id="content">
<?php
$user_name = "root";
$password = "";
$database = "atssautomationgnoc";
$server = "localhost";
$con = mysqli_connect($server, $user_name, $password);
$db_found = mysqli_select_db($con,$database);
$entityArr = array("ATA", "ANOTHER", "AND_ANOTHER");
$rowsA = array(); //define rowsA
foreach ($entityArr as $entity)
{
?>
<table cellspacing="0" cellpadding="0">
<tr>
<th class="lightcolor" style="width:60px; height:30px;"><h2>Server Name</h2></th>
<th class="lightcolor" style="width:60px; height:30px;"><h2>IP Address</h2></th>
</tr>
<?php
//use $entity below in where condition
$query = "SELECT Servername,IPAddress FROM t_applicationstatus Where Entity='".$entity."' order by FIELD(LiveStatus,'RTO','OK')";
$result=mysqli_query($con,$query);
$Names = array();
if($result == FALSE)
{
die(mysql_error());
}
//clear array
unset($rowsA);
while ($row = mysqli_fetch_array($result))
{
$rowsA[] = $row;
}
foreach($rowsA as $row)
{
$rowsA[$i]=$row['Servername']; //You'd better comment this line out
$rowsA[$i] = $row['IPAddress']; //And this one
echo "<tr>";
echo "<td>" ;
echo $row['Servername'] ;
echo " </td>";
echo "<td>" ;
echo $row['IPAddress'];
echo " </td>";
echo " </td>";//This is extra, simply remove this line
echo "</tr>";
}
?>
</table>
<?php
}
?>
</div> <!-- close #content -->
</div> <!-- close #container -->
There are various ways to do this, especially without executing sql statements in the loop. Hope that helps.

How to use bootstrap css tables to display data from MySQL tables?

I'm trying to make it so that when a button is clicked on my main page, a php script takes action and fetches the information from the SQL tables, and displays it in a HTML/CSS table.
Here's the code of my main page -
<form id="myForm" action="select.php" method="post">
<button type="submit" class="btn btn-info" >
<span class="glyphicon glyphicon-tint"></span> View
</button>
<br /> <span class="badge alert-info"> Find out what is currently in the database. </span><br />
</form>
<br />
<br />
And here's what I currently have in my select.php -
<?php
/*** mysql hostname ***/
$hostname = '192.xx.xxx.xx';
/*** mysql username ***/
$username = 'Mitchyl';
/*** mysql password ***/
$password = 'root1323';
/*** database name ***/
$dbname = 'test';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
/*** The SQL SELECT statement ***/
$sql = "SELECT * FROM increment";
}
catch(PDOException $e)
{
echo $e->getMessage();
}
?>
I just don't know how to take the data from the SQL query and put it inside a HTML table.
Any suggestions would be great!
Thanks!
Try this
<?php
$hostname = '192.xx.xxx.xx';
$username = 'Mitchyl';
$password = 'root1323';
$dbname = 'test';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$sql = $dbh->prepare("SELECT * FROM increment");
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
}
catch(Exception $error) {
echo '<p>', $error->getMessage(), '</p>';
}
?>
<div id="content">
<table>
<?php while($row = $sql->fetch()) { ?>
<tr>
<td><?php echo $row['column1_name']; ?></td>
<td><?php echo $row['column2_name']; ?></td>
<td><?php echo $row['column3_name']; ?></td>
...etc...
</tr>
<?php } ?>
</table>
</div>
Let's say your sql returns an array named $data and its format is sth like $data = [['name' => 'name1'], ['name' => 'name2'], ...];.
//First declare your data array
$data = [];
// Then execute the query
$result = $mysqli->query($sql)
// Then read the results and create your $data array
while($row = $result->fetch_array())
{
$data[] = $row;
}
Now that you have your data check if it is empty or not and then use foreach to present the results.
<?php if(empty($data)): ?>
<h1>No results were found!</h1>
<?php else: ?>
<h1><?= count($data) ?> results were found!</h1>
<table class="table">
<thead>
<th>#</th>
<th>Name</th>
</thead>
<tbody>
<?php foreach ($data as $key => $value): ?>
<tr>
<td><?= ++$key ?></td>
<td><?= $value['name'] ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php endif; ?>
Of course you can add any class you like to the table apart from the default one that bootstrap uses (.table).

HTML table with sql data in php (table row depend by sql columns)

Hello i got this sample data in sql
$data = array(
array('id' => '1','name' => 'name1','surname' => 'surname1'),
array('id' => '2','name' => 'name2','surname' => 'surname2'),
array('id' => '3','name' => 'name3','surname' => 'surname3'),
array('id' => '4','name' => 'name4','surname' => 'surname4')
);
I want to dispplay in in html table but my code didnt work :
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
}
?>
<tbody>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
</tbody>
</table>
</body>
</html>
But i wann't also that the numer of rows in html table depends by number of columns in sql table. For example in this case i want to display only three rows (three columns in sql table). When i add the column's to sql table i want to rows in html output table increses dynamicly.
Could someone help me with this code ?
Change your code to this:
<tbody>
<?php
$result = mysql_query($select_data);
while ($data = mysql_fetch_row($result)) {
?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php
}
?>
</tbody>
You are closing your while loop before displaying the results
You close your while-loop not correct:
<?php
mysql_connect("localhost", "root", "");
mysql_select_db("test");
$select_data = "SELECT * FROM dane ORDER BY `id` DESC";
$result = mysql_query($select_data);
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<th align="left" valign="middle">id</th>
<th align="center" valign="middle">name</th>
<th align="center" valign="middle">surname</th>
</tr>
</thead>
<tbody>
<?php while ($data = mysql_fetch_row($result)):?>
<tr>
<td align="center" valign="middle"><?php echo $data['id']; ?></td>
<td align="center" valign="middle"><?php echo $data['name']; ?></td>
<td align="left" valign="middle"><?php echo $data['surname']; ?></td>
</tr>
<?php endwhile;?>
</tbody>
</table>
</body>
</html>
Using the the "while(cond):" and "endwhile;" command you can see better where something starts and where it ends than using the encapsulation with braces.
Please consider to switch your Database Wrapper from mysql_ to PDO or mysqli, since mysql is not anymore actively supported.
You could also use instead:
<?php echo $data['id']?>
rather the shortform:
<?=$data['id']?>
Which is also avaiable w/o php short open after 5.3 (I think it was 5.3)
If I understand your question correctly, you would like to have the number of returned rows match the number of columns in your table dane. The following code should do just that and I'm using mysqli which I strongly recommend. The mysql_query extension is deprecated as of PHP 5.5.0.
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to the database ' . $db->connect_error);
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$result = $db->query($select_cols)){
die('There was an error running the query.');
}
while($row = $result->fetch_assoc()){
$cols[] = $row['column_name']; // Store the columns to an array. It will be further used.
}
// Implode the column names to a comma delimited string to use in the next select. It's also a good practice not to use asterisk in your select statements
$table_headers = implode(',', $cols);
// Query for records with a limit to number columns in the $table_name
$select_data = "SELECT $table_headers FROM $table_name ORDER BY `id` DESC LIMIT 0 , $result->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query ' . $db->error);
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into an array to be used in the html table
}
$db->close(); // Close our connection
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<meta charset="utf-8">
<title></title>
</head>
<body>
<table style="width: 100%;" border="1" cellspacing="5" cellpadding="5">
<thead>
<tr>
<?php foreach ($cols as $k) : // Loop through columns ?>
<th align="center" valign="middle"><?php echo $k; ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
<?php foreach ($data as $k) : // Loop through each $data array() ?>
<tr>
<?php foreach ($k as $v) : // Let's display the records ?>
<td align="center" valign="middle"><?php echo $v; ?></td>
<?php endforeach; ?>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</body>
</html>
I also took the liberty to dynamically display the column names as table headers which should eliminate the need to manually add them later when your columns increase. If you would like to manually create them simply replace the top php portion with this one:
<?php
$db = new mysqli('localhost', 'root', '', 'test'); // server, user, pass, database
$table_name = 'dane'; // table
// Let's make sure we could establish a connection
if($db->connect_errno > 0){
die('Unable to connect to database [' . $db->connect_error . ']');
}
// Build our select to return column names only
$select_cols = "SELECT column_name FROM information_schema.columns WHERE table_name='$table_name'";
if(!$num_cols = $db->query($select_cols)){
die('There was an error running the query.');
}
$select_data = "SELECT * FROM $table_name ORDER BY `id` DESC LIMIT 0 , $num_cols->num_rows";
if(!$result = $db->query($select_data)){
die('There was an error running the query [' . $db->error . ']');
}
while($row = $result->fetch_assoc()){
$data[] = $row; // Store the data into array to be used in the html table
}
$db->close(); // Close our connection
// print_r('<pre>');
// print_r($data);
// print_r('</pre>');
?>
and adjust the html code between <thead></thead>. This entire sample was put together pretty quickly so it could definitely be improved and adjusted to whatever needs. Please inspect it for any typos as well.

Categories