PHP Script for Datepicker to select and display database from Mysql - php

After spending 3 days on internet and struggling with so many different forums , i have found a match and similar case of my problem here.
Friends, I am zero in PHP, but still i have managed to do something to fulfill my requirement.
I am stuck with one thing now..So i need help on....
I am using one html+php form to submit database into mysql.
I created a display of that table through php script on a webpage.
Now i want a datepicker option on that displayed page by which i should able to select the date range and display the data of that date range from my mysql table.
And then take a export of data displayed of selected date range in excel.
This displayed page is login protected, so i want after login the next thing comes in should show a sate selection option which should be fromdate to to date , and then records should displayed from the database and i can take export of those displayed results in excel file.
The code i am using on this page is below which do not have any thing included for excel export and date picker script, I am pasting the code here and request you to please include the required code in it as required.
Thanks In advance
<?php
//database connections
$db_host = 'localhost';
$db_user = '***********';
$db_pwd = '*************';
$database = 'qserves1_uksurvey';
$table = 'forms';
$file = 'export';
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} ORDER BY date desc");
if (!$result) {
die("Query to show fields from table failed");
}
$num_rows = mysql_num_rows($result);
$fields_num = mysql_num_fields($result);
echo "$num_rows";
echo "<h1></h1>";
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>";
}
echo "</tr>\n";
// 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>\n";
}
mysql_free_result($result);
?>
</body></html>

This isn't a "write my code for me, please" site, so you're going to need to be a little more engaging and pro-acive. But we can certainly provide some guidance. Let's see...
Currently you have a page which displays all records from a given table, is that correct? And you need to do two things:
Before displaying any records, have the user select a date range. And keep the date range selection on the page so the user can re-select.
Provide a button which lets the user export the selected records to Excel.
For either of these, you're going to need to add an actual form to the page. Currently there isn't one. For the date picker, I recommend (naturally) using the jQuery UI datepicker. So the form for that would look something like this:
<form method="POST" action="myPHPFile.php">
<input type="text" id="fromDate" name="fromDate" />
<input type="text" id="toDate" name="toDate" />
<input type="submit" name="filterDate" value="Submit" />
</form>
<script>
$(function() {
$("#fromDate").datepicker();
$("#toDate").datepicker();
});
</script>
You may have to wrap the JavaScript in a $(document).ready(){} in order to make it work correctly, you'll want to test that. Anyway, this will give you a form to submit the dates to your script. Wrap the parts of your script which output data in a conditional which determines if the form values are present or not. If they're not, don't fetch any records. If they are, do some basic input checking (make sure the values are valid values, make sure fromDate is before toDate, etc.) and construct your SQL query to filter by date range. (Do take care to avoid SQL injection vulnerabilities here.)
For the Excel output, you may be able to find a ready-made solution for you that just needs a little tinkering. If I were to create one from scratch, I'd probably just output to a .csv file rather than a full Excel file. Most users don't know/care the difference. In that case, you'd just want to either create a second script which is nearly identical to the existing one or add a flag to the existing one which switches between HTML and CSV output, such as via a hidden form field.
For the output of the CSV, first make sure you set your response headers. You'll want to write a header to tell the browser that you're outputting a CSV file rather than text/html, and possibly suggest a file name for the browser to save. Then, the form inputs the SQL query will all be pretty much the same as before. The only difference is in the "HTML" that's being output. Rather than HTML tags, you'd wrap the records in commas, double-quotes (where appropriate), and carriage returns.
There's really nothing special to outputting a "file" vs. "HTML" because the HTTP protocol has no distinction between the two. It's always just text with headers.
Now, I'm sure you have more questions regarding this. And that's fine. In fact, we like to encourage asking (and, of course, answering) questions here. So please feel free to ask for clarification either in comments on this answer (or other answers), or by editing and refining your original question, or by asking an entirely new question if you have a specific topic on which you need help. Ideally, a good question on Stack Overflow consists of sample code which you are trying to write, an explanation of what the code is supposed to be doing, a description of the actual resulting output of the code, and any helpful information relevant to the code. As it stands right now, your question provides code somewhat unrelated to what you're asking, and you're just requesting that we add some features to it outright for you.

Related

A web application to allow the user to type SQL queries

I am just wondering, if possible, the best way to go about allowing users to actually input an SQL query from within a web application.
I have so far got a very simple web application that allows users to view the database tables and manipulate them etc etc..
I wanted to give them an option to actually type queries from within the web app too (SELECT * FROM).. and then display the results in a table. (Exactly the same as a search bar, but I don't think that would cut it, would it?).
I am only using PHP at the moment, is what I'm looking to do possible with just HTML/PHP or will I need the help of other languages?
This may be too complex for me, but if someone could give me a starting point that would be great, thank you.
UPDATE:
From my understanding to answer my question, i need something like:
<form action= Search.php method="POST">
<input type="text" name="Search">
<input type="submit" name"">
Search.php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$SEARCH = $_POST['Search'];
if (!isset($_POST)) {
$sql = "'%".$_POST['$SEARCH']."%'";
$results = mysqli_query($con, $sql);
echo "<table border ='2'>";
if (mysqli_num_rows($results) !=0) {
while ($row=mysqli_fetch_array($results)) {
echo "<tr><td></td></tr>";
}
echo "</table>";
}else {
echo "Failed! Try another search query.";
}
}
}
?>
At the moment in returns one error:
Undefined index: Search
It's talking about the $SEARCH = $_POST['Search'];
But I thought I am defining that Search, as that's the Search in the form?
Sounds like you're building your own minimalistic version of phpMyAdmin. That's perfectly doable with just PHP and HTML.
A very basic implementation would be a standard HTML form with a textarea, which submits to a PHP script that executes the query and renders a table of the results. You can get the required table column headers from the first result row's array keys if you fetch the results as an associative array.
You may (or perhaps I should say "will") run into situations where users provide a query that returns millions of results. Outputting all of them could cause browsers to hang for long periods of time (or even crash), so you might want to implement some sort of pagination and append a LIMIT clause to the query.
Since the user is providing the SQL query themselves, they need to know what they did wrong so they can correct it themselves as well so you'll want to output the literal error message from MySQL if the query fails.
Allowing users to provide raw SQL queries opens the door to a lot of potential abuse scenarios. If it were my application, I would not want users to use this feature for anything other than SELECT queries, so I would probably have the user-provided queries executed by a MySQL-user that only has SELECT privileges on the application database and not a single other privilege -- that way any user that tries to DROP a table will not be able to.
Undefined index: Search
This error will show only when the PHP is executed for the first time as it's simply expecting "Search" in $_POST.
$_SERVER['REQUEST_METHOD'] checks if the request method is POST it does not check if $_POST have any post data in it.
(Source :$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST')
But the page is being loading for the first time so it wouldn't have anything in POST.
You can simply avoid it by check if the page is loading for first time, using the "isset()" method.
If its loading for the first time just ignore the further execution of php code and simply show the form to enter the query.
<?php
if(isset($_POST['Search']))
{
`// Query execution code`.
}
?>
<form action= Search.php method="POST">
<input type="text" name="Search">
<input type="submit" name"">
So if the search index is not set in the $_POST it wont execute the php code and will not generate any error.

Can someone explain to me how this appending a table with ajax works?

So I am using Mottie's fork of the tablesorter plug in and it has been working well for me. However I have a couple pages that will have some large records of data that I need to deal with. So I assume the best way of going about this is using AJAX to fill the table. There is an example in the documentation but I do not know javascript or ajax very well so I am not sure exactly how it is working.
http://mottie.github.io/tablesorter/docs/example-ajax.html
A couple specific questions would be.
What would the code on assets/ajax-content.html look like? that is the piece I really wanted to know about. how it is actually getting the records and sending them back.
I also just don't fully understand how the
("#ajax-append").click(function()
is working. how is it receiving the 'html' parameter on the line
$.get("assets/ajax-content.html", function(html) {
Any help is really appreciated. thanks
From the examples, we can determine it's returning HTML. So your back-end script would want to do the same. From the example page, the tbody contains the following:
<tr>
<td>Bruce</td>
<td>Evans</td>
<td>22</td>
<td>$13.19</td>
<td>11%</td>
<td>Jan 18, 2007 9:12 AM</td>
</tr>
So when we click the link (Append new table data) in the example, we append more Table Rows to the Table Body. We can only hope that what it wants is more of the same. An example could be:
<?php
// connect to DB
// run query
// get recordset
// output recordset in Table Row format
while($row = $sql->fetch_assoc($results)){
echo "<tr>\r\n";
echo "\t<td>{$row['fname']}</td>\r\n";
echo "\t<td>{$row['lname']}</td>\r\n";
echo "\t<td>{$row['age']}</td>\r\n";
echo "\t<td>{$row['total']}</td>\r\n";
echo "\t<td>{$row['discount']}</td>\r\n";
echo "\t<td>{$row['date']}</td>\r\n";
echo "</tr>\r\n";
}
$sql->close();
?>

Updating Records with a dynamically generated form

Hello everyone first time comment here so please forgive my poor formatting, I am currently working on a project and have hit a serious wall. Before I show the code please read what I am aiming for here, it is rather complex.
So the form that creates the data that I am trying to update in MySQL is dynamically generated, so users can add or remove input fields as needed. So there can be any number of fields to update. The initial population of the table works just fine but here is were it gets interesting.
The page I am having trouble with is the page where users review the data that was submitted, and can make changes as they see fit.
So, the data I am using, just for the sake of putting names to faces, are requirements that must be met in order to qualify for an evaluation. There can be any number of these. So I query and return all of the requirements tied to the evaluation, and then loop through them and echo input fields with the values the user originally submitted.
Bellow you can see what I am talking about, so what I need to do is create an array of form elements that I can loop through. I have the Primary Key of the requirment that needs to be updated under the $Baseline_Requirements_ID PHP variable in a hidden input field (text field in code below for testing) so I can target the correct record in the table and update it with the content in text area.
So ultimately, I feel I have to have the names of the fields be arrays so I can target them, get the length of the array, and then update the records within that loop. Only issue is I can not figure out how to generate the array.
Thank you in advance, Zach
<form id="requirments" name="requirments" method="post" action="">
<?php
$Baseline_Requirements = array();
$Baseline_Requirements_ID = array();
$bas_count = 1;
mysql_data_seek($BaselineRequirments, 0);
while ($row = mysql_fetch_assoc($BaselineRequirments))
{
$Baseline_Requirments[] = $row['Requirement'];
$Baseline_Requirements_ID[] = $row['Baseline_Requirement_ID'];
}
$Req_index = 0;
foreach ($Baseline_Requirments as $value)
{
echo "<textarea name='requirment[]'
id='requirment$count' cols='45' rows='5'>";
echo $value;
echo "</textarea>";
echo "<input name='Baseline_Requirement_ID[]' type='text'
value='$Baseline_Requirements_ID[$Req_index]'>";
$bas_count = $bas_count +1;
$Req_index = $Req_index +1;
}
Sorry, what array are you trying to generate? The array of column/field names? Could you not also include a hidden field that holds the index of the field in the order you retrieve it from the database table? Or even use the index as say, field numbering?

Use dropdown list selection as mySQL query parameter

I had asked a similar question a few days ago but think I was trying to do to much at one time. I am hoping someone can help get me started on this.
I have two drop down lists, one will be populated with years (2012, 2011 etc) and I have some mySQL databases called "db_2012", "db_2011" etc. In these databases are tables representing months.
I would like the user to select a year and then use that selection to query the correct db and return a list of table names which will be used to populate the second drop down list. Then click a button "See Results" to query the selected table and show the results.
I am putting this on a wordpress website and am using a php template file that I created. This is still new to me and what I have so far doesnt work like I want it too, it is basically setup now that you select a year and select a month (not populated from db) and click a button. It makes the query and my table is displayed, but I need this solution to be more dynamic and work as described above. Thanks for the help.
echo '<form action="" method="post">';
echo'<select name="years" id="years">';
foreach($yearList as $year){
echo'<option value="'.$year.'">'.$year.'</option>';
}
echo'</select><br />';
echo '<select name="monthList" id="months">';
foreach($monthList as $month) {
echo'<option value="'.$month.'">'.$month.'</option>';
}
echo '</select>';
echo '<input type=\'submit\' value=\'See Results\'>';
echo '</form'>
$yearList and $monthList are just pre populated arrays. So now from here I want to click the See Results button and query my sql database using the parameters from the drop down selections.
$database = $_POST['yearList'];
$month = $_POST['monthList'];
$wpdbtest_otherdb = new wpdb('Username', 'Password', $database, 'localhost');
$qStr = "SELECT * FROM $month";
$myResults = $wpdbtest_otherdb->get_results($qStr, OBJECT);
It sounds like you want to send an AJAX call to a separate php page for security and processing, then have the PHP return XML that you parse back into the second selection box via the AJAX callback. It can be a little messy, but it allows you to check for weird form values that users might inject.
Edit: The PHP will receive your AJAX parameters as parts of the $_GET or the $_POST array. From there, you can do your checks and db call (or not), then add header("Content-Type:text/xml"); so the server sends it back with the correct header. After that you'll need to echo the XML-formatted data you want the JavaScript to receive. Just remember not to echo anything other than the XML if the request is supposed to go through.

Creating basic PHP script to add lines to a webpage

I'm predominately a Java guy, which is why I need some assistance on what I assume is rather simple to do in PHP (and rather simple with Java too, although perhaps a bit... verbose).
Simply put, I want to construct a webpage which has a list of string items that users have added. At the bottom of the page would be a place in which a user could type "Hello World" in a box for instance and hit a submit button, adding it to the list of items. Adding to the top or the bottom of the list is irrelevant - I can probably tweak that later.
I'm the kind of guy who doesn't just like answers, but at the same time I have no idea where to even start searching. I've done no PHP development before. What sorts of constructs or functions should I be looking at? I own the physical box it'll be running on (it's literally right next to me now) so permissions aren't a restriction, and neither is getting anything else that might help the situation (although I can't see how it would be needed for such a simple script). What sorts of input validation should I be really wary of? This service will be restricted to people who have be given access to a particular section of an apache-based website, so they have to log in to even see this planned page, but I'd like to cover all possibilities.
Additionally, I would perhaps like output to look like
"Hello World" added by user User1
"This is an additional line" added by User2
"Goodbye World" added by user User1
in the future. What should I be looking at to do this?
Update to answer questions:
When it comes to storage of the actual content, I'd be leaning towards a simple file holding each entry line by line, as Col. Shrapnel suggested. A think a database would be overkill, although I do have the wherewithal to implement it. If a user submits "Hello World!" then adding a line to a file that says
"Hello World!" posted by User1
is sufficient.
With regards to authentication, this is already set up in apache's httpd.conf configuration file. Currently this allows access to a certain group of users through an AuthGroupFile entry. This is where the script will be hosted. To access this script, users will have already authenticated themselves with their credentials. The authentication currently works for that section of the site. Really, this is a secondary concern of mine. It is enough that lines are simply added with no record of who said what. This is just sugar on the PHP cake if it can be done easily with what I already have implemented.
Well, yes, in PHP it's quite short.
Assuming Apache based authorization is used
<?
$file = "messages.txt";
if ($_SERVER["REQUEST_METHOD"]=="POST") {
$_POST['mess'] = str_replace(array("\r","\n"),"",$_POST['mess'];
file_put_contents($file, $_POST['mess']." ".$_SERVER["REMOTE_USER"]);
header("Location:".$_SERVER["PHP_SELF"]);
exit;
}
echo nl2br(htmlspecialchars(file_get_contents($file)));
?>
<form method="POST">
<input type="text" name="mess">
<input type="submit">
</form>
You're going to have a few things to do:
Pick a data store. MySQL is a popular choice when working with PHP. It doesn't sound like this'll be high-volume, so most any persistent store would work.
When accepting input, you'll need to sanitize it for insertion into the DB (again, if using MySQL, check the docs), and then you'll execute an INSERT statement to put it into the database.
When displaying the page, you'll connect to the DB (check the docs), query data from the data store, loop over it, and echo each line after sanitizing it of any potentially malicious data.
A short example might be something like:
<?
// Assuming a database named "my_database" with a table called "chat_lines", which has "username", "line", and "timestamp" fields.
$db = mysql_connect("localhost", "username", "password");
mysql_select_db("my_database", $db);
// If data was posted to the script, scrub it and store it in the database.
if($_POST["username"] && $_POST["line"]) {
mysql_query(sprintf("INSERT INTO chat_lines (username, line, timestamp) VALUES (\"%s\", \"%s\", NOW())",
mysql_real_escape_string($_POST["username"]),
mysql_real_escape_string($_POST["line"])
));
}
// Fetch all lines from the database in reverse chronological order
$result = mysql_query("SELECT * FROM chat_lines ORDER BY timestamp DESC");
while($row = mysql_fetch_assoc($result)) {
echo sprintf("<div>%s said %s</div>", strip_tags($result["username"]), strip_tags($result["line"]));
}
?>
<form method="post">
<div>Username: <input type="text" name="username" /></div>
<div>Line: <input type="text" name="line" /></div>
<input type="submit" />
</form>
That example makes assumptions about users being allowed to enter whatever username they want (that is, it doesn't assume to implement the authentication system), the data store and the existence of the table and all that, but should get you started. The PHP documentation is pretty extensive, and can be very useful. In particular, read Getting Started and the Language Reference.

Categories