SAME PAGE RESULTS: (xmain.php)
//FORM (working good)
<form name="search" action="xmain.php" method="post">
code,code,code,
// QUERY (working good)
code,code,code,
<input type="submit" name="doSearch" value="doSearch">
//These are last 2 lines of my 15 line query - I have skipped the rest to save space:
$sql = "SELECT SQL_CALC_FOUND_ROWS * FROM $tableName $qryWhere LIMIT $start, $limit;";
$result = mysql_query($sql);
// Table query results here.....
OK, although all code is working correctly ( Form is submitting variables, database results are correct, etc, there are 2 nagging problems:
1 - ALL database results are echoed when the page is first loaded. The page is refreshing from top to bottom without a stop in between - I would like for NO RECORDS to be shown at first page arrival.
2. Also, because of the top to bottom nature of this page,my option choices are being reset upon form submission. I would like to maintain selections until the RESET button -
that I have on the page for that purpose is clicked.
I realize that the form by always refreshing upon itself, is causing the above problems.
Any suggestions would be greatly appreciated! - see working sample here:
http://www.symbioticmusicpublishing.com/database3/xmain.php
Only show something when something is actually posted, so surround with if(isset($_POST['doSearch']){.. or something.
echo a value <input .... value="'.(isset($_POST['thisinputname'])?htmlspecialchars($_POST['thisinputname']:'')">
On more elaborate forms a session could be handy, not needed for simpler ones/forms always getting the post though. BTW, I prefer using GETs for listing data, makes it easier to share/link. POSTs for alterations, GETs for retrieving (and a few other methods for real REST).
Echo the retrieved values inside a if statement like Wrikken suggested. Check that your form submission button is actually clicked and only then echo the results.
If you're unfamiliar with the syntax take a look at ternary operator.
http://www.php.net/manual/en/language.operators.comparison.php
Also use GET if you are getting data from database. And POST when you are putting data into database. I guess the reason why goes beyond the naming convention but still it's a nice reminder: GET for getting and POST for posting/putting.
UPDATE
Sorry I didn't think this one through. Put the sql query inside a if statement. Put also the echoing of results inside a if statement.
if (isset[$_POST['doSearch']]){
//make the query
}
if ($sql){
//echo the results
}
Related
So on this application I'm working on, it searches for some code in my database, grabs it, opens a new page and places the code (where necessary) onto the new page by getting its id.
Now within that code (from the database) there is another form that is processed based on user's input. The problem that I am getting is that the new form is not processed on the same page. It redirects to a new url that doesn't specify the code from the database. For example...
When the new page is generated with the code from the database, the url looks like this...
localhost/newpage.php?id=1
Then when I submit the form within the code from the database it changes to this...
localhost/newpage.php?input1=blah&input2=blah
But I want something like this...
localhost/newpage.php?id=1&input1=blah&input2=blah
Just FYI this code needs to be dynamic. For example, let's say I don't know what id the user is looking for and within that id I don't know how many input fields there are.
If you guys need some explicit code (obviously I left out the unnecessary things)...
This is searchpage.php which searches db and displays all relevant items. Then the user selects an item which contains an id and generates newpage.php with that id...
//there is a search query then puts all elements in an associative array
$rows = items->fetch_all(MYSQL_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
echo "<a href='newpage.php?id=$id>User clicks to generate a newpage</a>";
}
This is the form retrieved from database and placed in newpage.php...
<form action="newpage.php" method="GET">
<input name="input1"></input>
//there can be an x amount of input tags here depending on what id is pulled
</form>
This is the php at the top of newpage.php when it is generated...
if (isset($_GET['id'])) {
//retrieves data from specified id from database
if(isset($_GET['inputs'])) {
//do something with user inputs
}
}
Is there any way to achieve this? All help is appreciated! Thanks :)
SOLUTION
For this to work, I had to create a session which stores the id. Consequently i had to change all my $_GET varaibles (that dealt with id info) to $_SESSION variables. But it works as long as you're not storing critical/sensitive info!
Here's the code changes...
Changes in search.php ...
//there is a search query then puts all elements in an associative array
$rows = items->fetch_all(MYSQL_ASSOC);
foreach ($rows as $row) {
$id = $row['id'];
$_SESSION['current_id'] = $id;
echo "<a href='newpage.php?id=$id>User clicks to generate a newpage</a>";
}
Changes in newpage.php ...
<form action="newpage.php?id=" method="POST">
<input name="input1"></input>
//there can be an x amount of input tags here depending on what id is pulled
</form>
Changes in php of newpage.php ...
if (isset($_SESSION['current_id'])) {
//retrieves data from specified id from database
if(isset($_POST['inputs'])) {
//do something with user inputs
}
}
ALL THANKS TO...
Sathik Khan
You can get the query string "id" in referred header. Either you can attach that query string in client or in server.
Please use $_SERVER['HTTP_REFERER'] to get referer url and from there you can get the id. If it's id of logged in user, I would recommend store them in session for security reason.
Based on your comments,
You can take any one of these actions,
1. Keep the ID in your form as hidden variable
2. Update your url with id as one of the query string and send back to client for error correction.
3. Keep the ID in session, if applicable
4. Use post and perform form validation before redirecting
Thanks.
Thanks in advance for any suggestions on the following:
I've created a php-page to add works from composers to CDs in a database. It's a combination of two forms and looks like this:
1st form:
Composer : [drop down list] : Select
Some blank space
2nd form:
Title : [drop down list]
Track number : [empty varchar field]
Work : [drop down list]
some other fields
Process button
After selecting a name in the first block (posting to $_SERVER["PHP_SELF"]) I stay on the same page, that name is shown in the blank space in between and the drop down lists are populated with only CD titles and works of the selected composer.
I can then select from the lists and enter other data in the other fields. Hitting the process button posts the data from the second block to another page which will eventually send everything to a table in a MySQL database.
After that I send myself back to the first page with header("Location: the_first_page.php")
So far so good, but upon returning I would like the composer, title and work to be preselected. Now I'm sent to a blank page and have to start from scratch. I think I've seen some solution involving testing $_POST['something'] against <option value> in a drop down list but I can't seem to make that work.
My question is: Is there a way to send $_POST['Title'] and $_POST['Work'] back to the first page somehow? Or is it better to split the two forms over seperate pages?
All help is welcome.
You could use sessions or the post data itself. For using the post data itself, the page where you send the request should be the same and include the script that will process it if there's some data like this:
if (!empty($_POST)) {
include "save.php";
}
// More code...
?>
<select name = "a">
<option <?php if ($_POST['a'] == "test") echo "selected"; ?> value = "test">
<option <?php if ($_POST['a'] == "testb") echo "selected"; ?> value = "testb">
</select>
Of course there are many more ways, but this is just a simple one to get you started. Things to know: you might want to change the variable $_POST and clean it up before using it. In this case it should be fine, but in <input type = "text" value = "<?= $_POST['b']; ?> name = "b">` you have a serious security issue.
For sanitizing the input, you want to sanitize it respect to what you expect. But also, as an EXTRA meassure, you normally want to strip everything that looks like a <script>, onclick ="", ' DROP TABLE users and similar. It's not an easy subject, so I recommend you reading on it, mainly on the XSS attacks which is relevant to showing the text back to the user. While it might seem too much work for this "simple case", it is useful in many more situations.
Use session variables and put conditions for them ... see [ $_SESSION ].
So, here is the page in discussion, DONATION RESULTS
What I did was I used the SQL DB to populate rows by totals, works great. Now, I want when the name is clicked, or the ammount is clicked, for a dialog to pop up with all the individual donations that person has recieved. To do this, I need to use
$eachone = mysql_query("SELECT donor_first,donor_last FROM dc_donations WHERE sponsoring='***'")
where * needs to automatically fill with the data from the name/previous query. So for example, for the sponsor tk, when you click on the link tk, it should run
SELECT donor_first,donor_last FROM dc_donations WHERE sponsoring='tk'
It also needs to be nested inside another while loop. This works, outside of the while loop, just as a test. It retrieves all the names, however, not just the ones for that particular sponsor. But, when I put it inside the other while loop, to put the content inside the div, instead of in some random spot on the page, it doesn't work anymore.
while($row=mysql_fetch_array($eachone)) {
echo $row['donor_first'] . ' ' . $row['donor_last']. ' ';
}
here is my entire code, sorry if its long, shouldnt be too bad.
MY CODE (PASTEBIN)
At Line 71, shouldn't you supposed to close </a> before </td>?
I recommend to check HTML generated to see what happened, if PHP isn't coming with error.
Give us more information to provide a better help.
In line 63 you have opening <tr> tag but it have no closing </tr>
This is the page, its a wordpress powered site:
http://bit.ly/9oJXWV
You select some value, it makes POST to same page and based on value you selected it makes a list pages.
Now before you jump into my code i just want to say that im a newbie and that my main problem here were database queries so i didnt focus on other small stuff(like bunch if's at start inline css and stuff like that).
So this is my template:
http://pastebin.com/HQvMq3Db
This is a function from functions.php which im using in template:
http://pastebin.com/fWKqqzQv
This page works the way i want it and i just finnished putting all the code together but have one issue. Once i get that sorted out i will make the code a lot nicer... :)
So the issue is that if you look at pages that are listed once you make a selection and submit, on a lot of them some values are missing even thought those values are there(open any page from that list which is missing some value and you can pretty much see the same stuff but now it display's all the data).
So that is the part i need help with debugging. I really have no idea how to tackle this.
Second part of this question is simple: how do i paginate this page? Any link, tip, tutorial would be good.
Also one more thing, how can i have links for example like this:
.../hostels/?grad=Beograd
and when user opens up that page he does not have to click to select the town, it would already list all pages from "Beograd"? I guess that is GET request right? Can i do something like that with POST? O_o Not sure what to do here, like i said im newbie.
Thanks for reading, looking forward to answers and comments.
Cheers!
You can set up your functions to enable pagination in WP without have to do any custom logic.
See: http://codex.wordpress.org/Template_Tags/query_posts#Pagination_Parameters
and when user opens up that page he does not have to click to select the town, it would already list all pages from "Beograd"? I guess that is GET request right? Can i do something like that with POST?
yes. yes. no.
GET requests retrieve the variables from the url. so you just run a link with GET variables, the php would suscessfuly display your info. but if you are using POST, the variables are retrieved from "the background", passed by the previous page. so you cannot just run a link, the page must be called from a previous page (trough a form) or the page won't have access to the variables.
1) I fixed pagination simply by implementing &paged='.get_query_var('paged') to my query. Now it looks like this:
$hostels = new WP_Query('post_type=page&meta_key=Grad&meta_value='.$grad.'&posts_per_page=60&orderby=title&order=ASC&paged='.get_query_var('paged'));
#js1568 i gave him +1 for his answer, but he didnt answer my entire question.
Now i can go through pages like so:
/acommodation/hostels/?city=beograd - this is page 1
/acommodation/hostels/page/2/?city=beograd - this is page 2
/acommodation/hostels/page/3/?city=beograd - this is page 3
etc...
2) The issue with missing info from some pages is fixed by putting this below the end of inner loop:
wp_reset_query();
and also i created some custom function which will get all meta values for given post id:
function custom_get_meta_values($id){
$first_array = get_post_custom_keys($id);
foreach ($first_array as $key => $value) :
$second_array[$value] = get_post_meta($id, $value, FALSE);
foreach($second_array as $second_key => $second_value) :
$result[$second_key] = $second_value[0];
endforeach;
endforeach;
return $result;
}
In my inner loop i call that function like this:
$result = custom_get_meta_values($post->ID);
Then i just echo what i need like so:
echo $result['Mail'];
Just put the name of meta field in that $result array and echo it.
3) I replaced POST with GET request so now i can have links like this:
/acommodation/hostels/?city=beograd
which when opened will show every hostel from 'beograd'. I only have 4 possible values for cities so if value of 'city' that i capture from GET request is not one of those 4 values, i do nothing, just show that form. If it is i take that value and show the list from that city.
As per Will instructions, i will mark this answer as accepted.
So I have a form that I post to a page and in the form I'm posting certain variables that I build one of my queries with and then call them on my page. How can I post data and also build a query and display the answer on one call?
Maybe I'm not wording it right and I'm learning this stuff, but I just don't know. Should I post to an intermediate page first?
Example: form (variables A & B) to-> page (A & B used in query) and then result is on that same page.
can this be done and what's the method?
Thanks!
This is the basic priniciple, but you must sanitize you input data from the form. For example using mysql_real_escape_string().
But in a single page you can have code like this (it is not tested, I'm not able to on this computer):
<?php
if(isset($_POST['name']))
{
$query = "SELECT * FROM table WHERE firstname = '"+ mysql_real_escape_string($_POST['name']) +"'";
while($node = mysql_fetch_rows())
{
echo "The result: " . $node['id'];
}
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="name" />
</form>
This will post to it self, run the query and echo the result, and show the form again.
For small tools and the like, this is an ok approach, but for larger websites I would recommend not mixing the request handling code with the html. Look into using a framework for applying the mvc pattern or something like that.
Without specific examples it's hard to write it, but it's fairly simple.
In a very basic way:
File1.php:
--your form submits to file2.php--
File2.php:
function processForm(inputs) [
--MySql query goes here--
]
function displayResults() [
--Process your query results--
]
processForm($_POST['vars']...);
displayResults();
Does that make sense? Simply make a function that processes and then displays the results again.
If you want to get really fancy you can even do it all in a single file, but you should probably master this technique first if you are first learning.