Example I have a code select data in sever
$sql = "SELECT * FROM ..."
$result = mysqli_query($conn,$sql)
$row = array()
if($result){
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
I often use ajax to show data in html . But I see some people render in html by php like
index.html
<div> <?php echo $row ?> </div>
I think it not good but i dont know why . Please explain for me. Many thanks
It's not a 'bad practice' but rather a choice of user experience. It depends on the fact that if or not you have the records to be shows while the page is being rendered by php or not.
Let me give you two use use cases :
You already know that user is on this page to see the records for row-39, you get this details from some other action like a form submit in the previous page or from url which reads example.php?showMe=row-39
In this case, you'll fetch the row 39 while the page is being rendered and add the result then and there like
Your data:
Your database has 10K records and you are not sure which one the user is looking for. In that case,for security reasons (row-39 is not meant to be seen by current user) or for simply speed issues (fetching 10K records take time and so does transferring them to the user) you can't put in those records on the page and later hide what user doesn't have to see.
In such cases, you'd take the row number that user wants to see through some active like a input box, fetch that row with AJAX and show it to the user.
Now, note how 'case 2' takes more time to effectively show the data to user (first user interaction, ajax, network transfer etc) and this is why you'd want to use the 'case 1' whenever you already know what to show user
Related
I have currently have a search form that specifies specific information of the users interest and generates a table with the filtered data.
I want to make this table interactive, specifically by allowing the user to click on the row (entry) of interest and be sent to a page with more detailed information about that entry.
I'm a novice at best and was wondering if anyone knew a way to approach this. I can provide more information if required but my MySQL and PHP search is pretty straightforward: The search locates specific columns in the MySQL table and the data that is filtered provides some - not all - the information in a table that is generated from the query.
Simply output a link that goes to a page that loads based on RowId, but don't forget security involved with passing an ID around.
<?php
foreach($resultset as $row)
echo "<a href='action.php?rowId={$row['id']}'>View Profile</a>";
?>
Then in action.php
<?php
$profile = user_load_profile_function( $_REQUEST['rowId'] );
// do whatever you want to here.
?>
I'm new to post/redirect/get. I'm coding up the first real site that led me to discover the need for PRG.
So I had written and gotten working code that did the following:
1) user enters a search string
2) we search the database and find their desired search results
3) if we found their search results successfully, we alter the database --
a 'frequency of lookups' -- to indicate the user searched and found what
he was looking for
4) then display the results he searched on
What I found was refreshing the page in the browser resulted in the user seeing his same search results again but we incremented the 'frequency of lookup' -- the user is limited in the frequency of lookup in the database -- so if the user refreshed the page too many times, they ran through their hourly ration of database lookups. That's when I discovered Post/Redirect/Get a few days ago.
I am now going through the site and altering all pages that alter the database and display results and switching them over to PRG. Here is the new process:
1) user enters a search string
2) we search the database and find their desired search results
3) if we found their search results successfully, we alter the database --
a 'frequency of lookups' -- to indicate the user searched and found
what he was looking for
4) PRG to a 'results' page
5) then display the results he searched on
And I ran into a problem. I need to somehow 'pass' their search results from step (2) above
to the new 'results' page in step (5) that I created to implement PRG.
So my question is -- is there a 'most common' way to do this? In reading around I've seen 'save the results in a .CSV file' and also 'save the database search results in the SESSION.'
I want to save the search results in the SESSION then on my 'GET' page I added for PRG to display the result, I'll read the search results from the session variable and display them.
By that I mean I want to do this:
$result = mysql_query($query, $theDbServer);
$_SESSION['theSearchResults'] = $result.
Then on the 'display' page, read back the search results from $_SESSION['theSearchResults']
and display them using:
$result = $_SESSION['theSearchResults'];
$row = mysql_fetch_row($result);
Is this a normal approach? And I suspect I cannot save the raw $result in a session variable like the above -- but I'm also not sure how to put the $result above into the $_SESSION -- how is that normally done?
Assuming you don't want to have the final landing page do the querying (without decrementing their quota of course), then you're going to need to use session.
Saving to a CSV is not standard and wouldn't scale very well. I would parse the results of the query into a more user-friendly form (a simple class or list or whatever you need). I'd then store the class and not the reader into the session. You'll probably want to clear out that portion of the session when they leave the results page (especially if it's a huge amount of data).
This is assuming you're using raw php. There are many frameworks with features for this exact case (you want to shuttle a piece of data from one page to the next).
I have a send message form, with a list of recipients populated by a PHP query to the database. I want to be able to include multiple recipients by dynamically adding select boxes to the form, depending on how many people they wish to send the message to.
I don't know javascript all that well and I have been researching the web to see how I can dynamically add a select box to a form with the options populated by PHP, but the only thing I seem to be able to find is how to populate the options depending on what was selected in the previous select box.
This is my Javascript:
<script type="text/javascript">
function add_recipient_field(){
var container=document.getElementById('addanother');
var to_field=document.createElement('select');
to_field.name='to[]';
to_field.type='file';
container.appendChild(to_field);
var br_field=document.createElement('br');
container.appendChild(br_field);
}
</script>
This is my PHP :
$tosql = "SELECT UserID, FirstName, LastName FROM users WHERE Active = 'yes' ORDER BY LastName ASC";
$query = mysqli_query($dbc, $tosql) or die("Error: ".mysqli_error($dbc));
$tobox .= "<option value=\"None\">None</option>\n";
while ($row = mysqli_fetch_array($query)) {
if ($row['UserID'] == $to) {
$tobox .= "<option value=\"$row[UserID]\" selected=\"selected\">$row[LastName], $row[FirstName]</option>";
} else {
$tobox .= "<option value=\"$row[UserID]\">$row[LastName], $row[FirstName]</option>";
}
}
This is my HTML:
<div id="addanother"><li><label for="to">To: </label><select name="to[]" id="to">$tobox</select>add more$toerror</li></div>
When I click on the "add more" link, it adds another select box, however there are no options in the box so it appears empty. I know I'm missing something fairly simple, but if someone could help or point me in the direction of a tutorial I would very much appreciate it.
All add_recipient_field does is add an empty select. I know that's your quandary, but my point is that according to the function you have listed above, adding an empty select is what it SHOULD do since that's what it is written to do. You still have to fill the data somehow.
Keep in mind that PHP ONLY runs on the server and does not interact with the currently loaded page in the browser. You can use Javascript to call PHP on the server and use the returned data to modify the page in place, but PHP itself cannot change the document after it has been loaded.
You have 3 primary options.
You can reload the page every time the user selects "add more" and have php rebuild the page with the new select. Keep in mind that for proper usability, you'll have to pass all your form data every time and refill it as you rebuild the form.
You can build the selects entirely from Javascript, which means the Javasript on the page will need to have all the required data at hand. PHP's json_encode method can be very helpful for doing this quickly. You load all your data into a javascript object at the top of the page and then every time you add a new select, you fill that new select from that data.
You can read up on what's generally referred to as "AJAX" where the javascript on the page interacts with PHP on the server in order to dynamically load your data upon request and change the already loaded page without a refresh. This is something of a mix of the two prior options and is probably the more advanced method, but the most rewarding to learn.
My site has a library full of games, nations, game scenarios, etc.
library.php is given a type=___ & id=___
for example library.php?type=scenario&id=ABCD001
library.php saves the id to a session variable and loads an include appropriate for the type
This all works just dandy. Now, I wanted to give my users the option of pulling up a random scenario. To do that, I added a special id to the logic within lib-scenario.php (the include) such that if given library.php?type=scenario&id=random the include knows to run an alternate query for a random record rather than for the actual id
This also works just dandy... unless someone hits the Random Scenario button two+ times in a row, and decides that the previous random scenario was way cooler, I want to go back to that.
Because the http address is always directory/library.php?type=scenario&id=random no matter how many times you click Random Scenario, as soon as you click back you'll be taken to the last page with an alternate address you visited.
So, if you start at the Home page, and hit Random Scenario 35 times, then decide the 34th one was what you wanted and click BACK, you'll be put back onto the Home page.
I must admit this was not a problem I had anticipated. One of my testers was the first to have the urge to back-up in the random scenario stream and here we are.
How can I add back-up functionality to my script?
Make the 'Random Scenario' button simply link to an actual (but random) scenario id. You'll probably have to construct this with an SQL query to get all the id's of your scenarios.
$result = mysql_query("SELECT id FROM scenarios");
while ($row = mysql_fetch_row($result)) {
$ids[] = $row[0];
}
$randomid = array_rand($ids);
Button:
<a href="directory/library.php?type=scenario&id=<?php echo $randomid; ?>Random Scenario</a>
If your scenario id's are all consecutive numbers you can simply use this instead:
$randomid = rand($min, $max);
you can resolve this by redirecting to the canonical url for the scenario, i.e.: id=random redirects to id=A92831 or whatever was selected. the final url will be stored in the history, rather than the id=random url.
i found it difficult,,,, fetching data from database while a buttons are randomly generated in for each how can i fetch
Without understanding what your question really is, you could go trough the mysql query result like this:
// button_text is a database column in this example
while ($row = mysql_fetch_row($result)){
echo "<button type="button">".$row['button_text']."</button>";
}
But to really help you, you need to rephrase your question!
I'll make some assumptions for what you are trying to do:
1. You have buttons that fetch more info from a db
2. The buttons are "randomly" generated, and each calls different info (pets, cars, etc).
You may or may not be using ajax, but I will describe it basically assuming straight php, and you are using a single page (for clarity in my explanation).
What you need to do is have each button either be a link or a submit for a form. This just depends on whether you want to use GET or POST. The buttons will have php generated links (if GET) or values (if POST). For example, using get the link could be "www.file.php?cat=cars". The button would just have the value of "Cars", and since bother are generated, that shouldn't be an issue keeping them the same.
When the page is now reloaded based on the click, the top of the page has a query in it to get the new info. For example, it would run a query looking for all items that have the car category. Then the new information would be displayed, and the new random buttons would show.
VERY IMPORTANT: Sanitize all GET and POST values before using them in a query