I have a tests.php web page that successfully creates and populates a html table using data from a mysql database on an online server. Next I want to make the web page interactive by adding html select to limit the number of rows the sql query returns. I've added the html select code and amened my sql query to use a variable for LIMIT. The issue I have is how to make the query run when the select dropdown is changed. I'm assuming some kind of page refresh needs to be called but unsure how to go about this. For example would I need to enclose the html as a from and have a submit button to make this work? This IS NOT what I want, ideally the user presses html select and then the page refreshes or re runs the sql database query.
Please be kind this is the first php code I've written.
My select code
<select name="limit" id="limit">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
The php code
</body>
</html>
<?php
$limit = 10;
if(isset($_POST["limit"])) $limit = $_POST["limit"];
$con=mysqli_connect("localhost","user","password","database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM TableName WHERE Region='Home' ORDER BY TeamName ASC LIMIT $limit");
echo "<table class='sample' style='width:50%'>
<tr>
<th>Team Name</th>
<th># Players</th>
<th>Venue</th>
<th>Date</th>
<th>Score</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['TeamName'] . "</td>";
echo "<td>" . $row['NumPlayers'] . "</td>";
echo "<td>" . $row['Venue'] . "</td>";
echo "<td>" . $row['Date'] . "</td>";
echo "<td>" . $row['Score'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
UPDATE
I think I may have a simpler solution using javascipt although it's not working correctly.
Using javascript function:
window.location.reload(true);
and change my html select
<select onchange="refresh.call()">
However when the page re loads it's using the typed $limit value
$limit =10;
instead of the select value.
The page refresh is working but is there a way to inject the html select value somehow?
Sanitizing Input
First off, you need to sanitize your limit variable as it's insecure to allow input directly into the SQL.
see:
What's the best method for sanitizing user input with PHP? AND
https://www.shift8web.ca/2015/06/securing-your-mysql-queries-from-sql-injection-in-php/
Single Page App Approach
Secondly, you need to decide if you will re-write the html notes using javascript ( in which case you will make an ajax/jquery request). Then you will rewrite the html using some framework or javascript ( innerHTML = '') or editing the DOM tree.
See:
Ajax tutorial for post and get
AND
https://stackoverflow.com/a/19527642/1688441
Reloading the page
If you decide you don't want to use javascript to rewrite the Dom tree, then the only solution is to refresh the entire page using either a GET or POST with the limit parameter.
So you will use an onChange listener, and call the page again with a limit parameter.
See: Reload page after user clicks on combobox (with some rules)
Related
I'm new to PHP programming and working with backend. I know what I am doing, but having trouble finding a proper solution online which matches my case.
Basically, I have a form (2 text fields, 3 dropdowns) that filters the data that I am getting from SQL Server (that works). However, when I press the "filter" button and I get the desired results, the page reloads and resets the form. Now I have the filtered records but I don't know what filters I used to get that. I could insert a <?php ... ?> if else, but the thing is I already am using php to get the dropdown values. Don't think I can put php inside php.
By including if-else I mean this:
echo '<option value="' . $row['status'] . '"' . if($prod_status == $row['status']): echo ' selected="selected"' . '>' . $row['status'] . '</option>';
Here's the code:
<label for="prod_status_filter">Prod Status</label>
<select class="form-control" id="prod_status_filter" name="prod_status_filter">
<?php
$query_status = 'select DISTINCT status FROM analytics.laborrecords ORDER BY status ASC';
$result = sqlsrv_query($conn, $query_status);
while ($row = sqlsrv_fetch_array($result, SQLSRV_FETCH_ASSOC))
{
echo '<option value="' . $row['status'] . '">' . $row['status'] . '</option>';
}
?>
</select>
This is one of the dropdowns.
I want:
1. Either stop the page from reloading so the filter dropdowns remain the same. (AJAX won't work, I have 3 dropdowns with a lot of options and it's doesn't seem like a good practice to make so many getElementById lines)
2. Let the page reload but keep the values as I set until I want to reset them, with a "reset" button.
You have to populate the form using the submitted form data. It should be either in $_POST or $_GET.
Check if the value of $_POST['prod_status_filter'] matches the value in $row['status'] and if it does, echo selected.
Be sure to sanitize the form data. Never trust user input.
I have an html homepage which has a form. The form submit button sends the query to a single php page called First.php which gives the necessary data from the database in a tabular format. A single column from the table contains links as the contents of the column are too large to display on the same page. Once the link is selected, it gives the exact column information of only that query which I submitted on the homepage.
My general idea was to give two actions to the form action which can be used on two different pages but that to no result.
Here's the homepage :
<form action="First.php" action ="Second.php" method="POST">
<input type="text" size="90" name="search1">
<input type="hidden" size="90" name="search1">
<input type="submit" name="submit" value="Search..">
</form>
First.php after connecting to database and the firing the sql query :
if($ant>0)
{
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td><b href='Second.php'>Link</b></td>";
echo "</tr>";
}
}
Please do help me for the Second.php.
Any help would be deeply appreciated.
Thank you!
This is common pagination problem. You should use extra parameter in your form.
do something like
if($ant>0)
{
while($row=mysql_fetch_array($res))
{
echo "<tr>";
echo "<td>" . $row['A'] . "</td>";
echo "<td>" . $row['G'] . "</td>";
echo "<td><b href='First.php?page=2'>Link</b></td>";
echo "</tr>";
}
}
You do not need a second action at all (and you cannot have one). What you need is to pass the id of the row to Second.php as a GET parameter. If you are not familiar with the concept, look it up because you will need it. A lot.
In Second.php you do not need the search parameters anymore because you are showing the details about a single row and you have its id. You just make a query to the DB to retrieve it by id and the old search becomes irrelevant.
In good conscience I have to say that the mysql_-something functions are a BAD idea. They have been removed in newer versions of php and are dangerous to use in the old ones. I strongly suggest that you use PDO and prepared statements ot at least the mysqli_ family of functions.
Hello I have a drop down list with options that a get from a table in my database and I want when the user select on of the options to store it in another table of the database. I have the code for the select by a cant find the way to get the correct value in order to store.
Here is the code for the drop down list ...
<select id="SelectDisease" name="disease">
<?php
$sql = mysql_query("SELECT name FROM disease");
while ($row = mysql_fetch_array($sql))
{
echo "<option value=$disease>" . $row['name'] . "</option>";
}
?>
</select>
And here is the insert into code ...
queryMysql("INSERT INTO patient (fname,lname,username,email,password,gender,age,disease,spid) VALUES('$fname','$lname','$username','$email', '$password','$PatientG','$PatientAge','$disease','$PatientSPID')");
die("<h4>Account created</h4>Please Log in.<br /><br />");
I'm not sure if I understand your question correctly, but here is a method:
Include the <select/> tag within a <form/> tag with an action to another PHP page.
In the second PHP page, read the variable out $disease = $_POST['disease']
Call your SQL Insert Statement
Side Note:
Perhaps change:
echo "<option value=$disease>" . $row['name'] . "</option>";
to
echo "<option value=\"" . $row['name'] . "\">" . $row['name'] . "</option>";
Is this helpful?
This is a bit of a mess, so this might be a messy post, but I'll try to clarify what I think you're trying to do. For your select input:
<select id="SelectDisease" name="disease">
<?php
$sql = mysql_query("SELECT name FROM disease");
while ($row = mysql_fetch_array($sql)){
echo "<option value='".$row['name']."'>".$row['name']."</option>";
}
?>
</select>
That way, your select's options each have a different value, and not $disease, whatever that equated to.
Next, where you process your POST request:
$fname = $_POST['fname'];
$lname = $_POST['lname'];
... // Etc for each input you have.
$disease = $_POST['disease'];
Then your query should work correctly:
queryMysql("INSERT INTO patient
(fname,lname,username,email,password,gender,age,disease,spid)
VALUES('$fname','$lname','$username','$email', '$password','$PatientG','$PatientAge','$disease','$PatientSPID')");
If that doesn't work, comment with any errors and we'll try to sort them out.
NOTE
This is INCREDIBLY insecure. I would never recommend doing this on a live application, as SQL Injections would be quite easy. Also, please note that MySQL functions are being deprecated. Look up MySQLi or PDO and learn to implement those.
Best of luck.
I have this codes so far:
This form is generated during a query loop
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['age'] . "</td>";
echo "<td>" . $row['breed'] . "</td>";
if($row['neuteredOspayed']=="1"){
echo "<td>" . "neutered" . "</td>";
}else
echo "<td>" . "spayed". "</td>";
echo "<td>" . $row['priceFee'] . "</td>";
if($row['housebroken']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
if($row['goodwithdogs']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
if($row['goodwithcats']=="1"){
echo "<td>" . "yes" . "</td>";
}else
echo "<td>" . "no". "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "</tr>";
}
echo "</table>";
Now, is there a way to put a link saying "delete" next to every result? For example next to the status field?
Here is what it's looking like:
To get this deleted I guess that I need to spot the record somehow. What I need is to take the name of the animal. For example, how can I get the value "Sparky" from the table and assign it to a variable? If I have the name I would be able to make the checks and run a query witch will delete the record.
You will have to use Javascript and AJAX.
Basically, you'll want to put a button in a cell, one per row, and when it's clicked, pass the id of the record to be deleted back to a PHP script via AJAX, then remove the record from the database. It should also hide the row when it is clicked.
I'd recommend using jQuery's .ajax(), as raw XHR is painful at best.
There is no way to do this with just PHP, because HTTP is stateless. Once your web page is loaded, the HTML and PHP parts are done, and fixed. You'll HAVE to use Javascript to make consecutive requests.
Alternatively, as bcmcfc points out, you can also just have a hyperlink to a script that will delete a record from your database.
You'd need something like this in your while loop:
echo '<td>Delete</td>';
Using the table's primary key would be better than the name though - is the name unique in the db? Assuming there is a PK and it's called id:
echo '<td>Delete</td>';
Php just is for page generation, once you have generated that table you cannot modify it.
You could, however, make a new get request, specifying a parameter with the row name to delete, you have to change your server php code to take in account this parameter, though.
The best, according to me, is using javascript: you assign a td id to each row and then you write a simple function in which you delete that row.
You have to submit the form and do this action....
<input type="submit" name="submit" value="Delete" />
After submit the form will redirected to some page. In that page you got all the posted values. In that you can delete the record by using the record id otherwise you use the name for appropriate record.
$query = "DELETE FROM table_name WHERE name='$_POST['name']'";
(or)
$query = "DELETE FROM table_name WHERE id='$_POST['id']'";
After this execution you have to redirect the URL to that page.
(or)
Delete
In this file you have to written like this...
$id = $_REQUEST['id'];
$query = "DELETE FROM table_name WHERE id='$id'";
//Add this form before the end of the while loop
<form action="#" method="post">
<input type="hidden" name="name" value="<?php echo $row['name']?>">
<input type="submit" name="delete" value="delete">
</form>
//Add this at the end of the coding
<?php
if(isset($_POST['delete']))
{
//database connection
$sql="DELETE FROM `table_name` WHERE `name`='{$_POST['name']}'";
$queryEXE=mysql_query($sql);
}
?>
You add a "elemID" attribute to each of your <tr>s and a new class that would be individual for each row (for example, elem+the id):
<tr elemId="12" class="elem12">...</tr>
Then, for the Delete link, you use AJAX to call the page that deletes the row from your DB, passing the elemID as an argument to this function:
function deleteRow(thisElemID) {
$.ajax({
url: yourURL,
data: {'elemID', thisElemID },
success: function() {
$('.elem'+thisElemID).remove();
}
});
}
More on $.ajax here.
Create another cell in your table and call ajax onclik of that button. Inside your ajax call delete the pecific row
Use a 'delete' form for each row.
The best way would be to add, for each row, a form with a submit button. Each form has a hidden field containing the id (or name, if you must) of the record to delete. Set the method of the form to 'post'.
Reasons why:
A delete link (a href) can be indexed and bookmarked easily. You
don't want pets to be deleted everytime Google drops by or a user is
browsing through their history.
A method='get' form also can cause
the url to be bookmarked and/or show up in the history. The method
with a form will work without Javascript altogether.
Apart from that,
Any solution (both forms and links) can easily be 'upgraded' to a solution with Ajax for a better user experience, but that's always an extra and no core functionality.
If you like, you can style the submit button to look like a link.
Use the post-redirect-get pattern if you implement this solution.
That is, assuming you want to actually remove the record from the database. If you just want to alter the HTML, a Javascript soliution would make more sense.
I'm building a website where users can view eachother's profile. When a person clicks on another user's name they are directed to their profile page. The URL would look as follows:
http://www.mywebsite.com/profile.php?id=21
In ASP.NET this was trivial to do since I could call controls from C# and edit their text after I've retrieved user information from the database, but i can't seem to find a way how to do the same thing using PHP and jquery. This is how I would like the procedure to go:
User A clicks name of User B
User A is redirected to profile page of User B
Server retrieves information about User B and sends it to jquery
Page is loaded and the HTML fields are filled with the variable contents which were just sent from the server
I guess what i'm finding most hard is how to pass information from php to jquery within the same page.
In PHP you can mix server side code with HTML. You don't really need to involve jQuery to fill the HTML fields (unless you're using AJAX).
You would execute your mysql query and then use that result set to populate the page like so:
This isn't the best code (from w3Schools) but it illustrates the point:
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons");
echo "<table border='1'>
<tr>
<th>Firstname</th>
<th>Lastname</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['FirstName'] . "</td>";
echo "<td>" . $row['LastName'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
Notice the echo statements. This will output the value from the database into your HTML page.
As I said this is not an example of good code but you can easily change this to add the parameter from the query string (remember to escape the string) to the select statement and output into a profile page.