PHP Cycle Through MySQL Table With Submit Button - php

Okay, I've looked for a solution to this question, but to no avail. It could be the way I worded it, but I've tried almost everything I could think of. And I know this is probably something so simple, I just can't wrap my head around it.
The problem I'm having is this:
I have a form that is prepopulated with data from a MySQL database. This part of the form is strictly for viewing the records (that were previously entered by the user). I can get it to work; I have the database linked, and it shows the data for the row of the particular table that I want. But this is what I'm having trouble with.
I want there to be a button that the user can press that cycles through each row of data in the database, and outputs it in the form accordingly.
It's a little complicated, so I'll use a simple example.
Let's say I have a basic table in a MySQL database with three columns: ID, Name,
and EmailAddress.
Here's the query that grabs the data:
$sql = "SELECT * from tbl_Users ORDER BY ID ASC";
$query = mysql_query($sql);
$result = mysql_fetch_array($query);
Now I know this is deprecated, but I am working in an older version of php, and I'm trying to stay consistent other pages/apps in this particular domain.
Now let's say I have a simple form with two inputs and a submit button.
HTML
<form name="button" method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<input type="text" name="Name" value="<?php echo $row[Name]; ?>" />
<input type="text" name="emailAddress" value="<?php echo $row[EmailAddress]; ?>" />
<input type="submit" name="submit" value="Next Record" />
</form>
Now I can get it to echo what I need in the form. It can prepopulate the form with a row, as I want it to. The trouble lies with the submit button.
When the submit button is clicked, I want the next row to populate in the form, and so on until the end of the records.
I've tried the if(isset($_POST['submit']{...}, yet I don't know exactly to get this to work. I've tried loops, etc. I know there is a way, I just cannot comprehend one right now. Thanks in advanced.

Okay, so I DID manage to get it to work with PHP. I found a simple PHP Pagination script and changed the limit of the query to 1. Instead of echoing out the results of the query in the WHILE loop, I just called the variables for the form

Unfortunately in your case, PHP is server side, and it will run any queries before the client side has a chance to catch up and output it. I believe you will need to use javascript for this.
You can do one of two things, 1. Pull all table information on load (slower way) and use javascript to show/hide certain elements of that query. Or 2. You can use AJAX to pull the data on command.
I would suggest learning javascript (e.g. use a framework like jQuery) to perform an AJAX call for this.

Related

Update link based upon customer input

I have the following input field :
<input data-type="customerName" value="<?php echo isset($invoice['Client']['customerName']) ? $invoice['Client']['customerName']: ''; ?>" type="text" class="form-control" id="clientCompanyName" placeholder="Company Name">
When the user types in it, it utilizes autocomplete to pull data from my sql database and display names, and the user picks the name that is pulled from the database.
When the form is saved, the name, and the uuid is saved to the form. I have another code tidbit :
<a target="_blank" href="add-client.php?uuid=<?php echo isset($invoice['Client']['customeruuid']) ? $invoice['Client']['customeruuid']: ''; ?>">
This links to another page to update client information, but it only works after the form is saved.
I am trying to make the link work all the time, immediately after the user selects a customerName. Is there a way to do this?
Yes, you need to use jquery and ajax, php code is run on the server when the page loads, it is not dynamically applied while the page is open. You need to use javascript or jquery to handle user input without reloading the page. If this user input needs to query a database, you will have to use a seperate php page, and access that information using $.ajax with jquery.
I would strongly suggest you to go for the AngularJS way. You can use expressions to dynamically format your link.
Check this: http://www.w3schools.com/angular/angular_expressions.asp
<div ng-app="" ng-init="myName='Foo'">
<input type="text" ng-model="myName">
<a ng-href="http:\\www.{{myName}}.com">{{myName}}</a>
Substitute 'Foo' with your retrieval from the database and you may be good to go.
If you wanna test how it works, I did a JSFiddle: https://jsfiddle.net/ny39728p/

PHP, need refresh current page with additional information from the server, how?

I have a html/php page, which reads file NAMES on the server, collects user inputs, and returns results upon user clicking "submit" button. The returned results will be parsed and displayed in a table in the page. Certain functions are implemented in javascript, btw.
That's how the html/php usually works. Now I need another field that will allow user to specify a name, and I need "refresh" the page with additional info which will be read from file NAMES on the server. Let me call this ShowExtraName function, for the sake of wording.
Before ShowExtraName, I have html/php code like this (sorry for the format, not sure how to write html tags in the post):
<html>
<head>
<javascripts added here>
<table>
<div>
<form>
<continue html layout here>
<checkboxes with php reading file NAMES from server --- line XXYY>
<submit>
<php script to check user input and query server, then display returns in table. This section is blank before submit since certain input fields are not "isset".>
Now my question is how/where I can add the ShowExtraName. I believe it needs to be php, because I need determine not only user-specified name, but also get additional and related information from the server and display it in line XXYY.
Hope I describe it clearly. Thank you for your input!
You have to use JavaScript/jQuery and AJAX calls in order to be able to ask the server to execute some code and then to render the result back to the HTML without refreshing the page.
jQuery is a very simple and yet very powerful tool.
You can do this a number of ways.
Using only html and php, the easiest would probably be to use a form that uses GET with an action of the same page. Then check for get parameters in your PHP and print the extra row of data in your code.
<FORM action="" method="get">
<INPUT type="text" id="name"><BR>
<INPUT type="submit" value="Send">
</FORM>
<?php
if (isset($_GET['name'])) {
//do database query
//echo more stuff
}
?>
If you are doing a database query be sure to use prepared statements
Otherwise if you want to get fancy with a live refresh you will need to use JavaScript. (jQuery AJAX)

generate and save sequential number on POST

I have a form that uses Post to send info to a PHP page.
The PHP page;
Takes the form info.
Rearranges it.
Formats it.
Then turns it into a code string that's ultimately sent to another
page and performs some tasks using that info.
Form Code:
<form method="post" action="_php/buildMyPNR.php" name="GuestInfo"
onSubmit="return validateFormMethod1();">
<input type="text" name="AccountNumber" id="BID"
onkeypress="return isNumberKey(event)" size ="16"/>
<input type="hidden" name="requestID" id="RID" value="" />
..... bunch of other fields
<input type="submit" name="loadURL" id="submit" value="Submit"
onsubmit="return ValidateFields();" />
</form>
What I need to do is;
Generate a sequential number each time the page is used.
Pass that number with the post request (Sort of like a serial number
for the request), to another form say _php/buildMyPNR.php.
When _php/buildMyPNR.php loads, save the values of
AccountNumber and requestID to a database or similar.
Ultimately it would move on to _php/usageSummary.php, where the user can click
a button to return a list of AccountNumbers paired with the
requestID that was generated for the request.
Possibly download the list in an excel spreadsheet format, but it is
not absolutely necessary.
What would be the best way to accomplish this?
Mainly I need help with generating the requestID. I need them to be sequential so I assume that I would need to start with a number in my database like 00001, query that number from my form, add 1 to the returned value, then save the new value along with the AccountNumber when submit is pressed.
I have no experience with databases and any guidance would be greatly appreciated.
Ideally we'd see some schema and examples of code you've already tried...
However, you can use an Auto Increment field in your Database Table, which will accomplish the ID incrementing for you.
If you're using mysqli for your mysql database interaction (as you perhaps should be), then you can then retrieve this autonumber using;
$PassedRequestID = $mysqli->insert_id
Then pass this to your next page.
You will then need to query your database with something like (psuedo code);
SELECT Accounts.*, Requests.*
INNER JOIN Requests ON Requests.AccountID = Accounts.AccountID
WHERE Requests.RequestID = $PassedRequestID
For exporting to Excel, if you search for PHP export CSV using Google, there'll be plenty of examples there to choose from. However, as an example;
http://code.stephenmorley.org/php/creating-downloadable-csv-files/

Using PHP to insert form values

So I have a website on which users can share content. I would like to add a like button to user posts. What would be the smartest/cleanest way to do it?
Right now, I know I could use a submit button with two hidden form fields with values containing the post id and the user id of the poster. Then I would just use my $_SESSION['id'] to insert that into a new row in the LIKES table. Now, that's not very effective. I mean it work and all, but I want to do it so that It is instantly updated both on the page and in the database. What is the logical process to it? Could someone lead me in the right direction as to what I need to learn? Is it javascript? Ajax?
By users I assume you mean registered users with an active session.
To be honest, I know that the best way to do this is ajax as #DarkXphenomenon sugested, but I don't know how so I will put my approach in plain php.
<?php
if (is_int($_POST['postnumber'])) {
mysqli_query($connected,"INSERT INTO likes (userid, postid)
VALUES ('".mysqli_real_escape_string($connected,$_SESSION['userid'])."',".$_POST['postnumber'].")");
echo "Liked";
} else {
?>
<form>
<input type="hidden" name="postnumber" value="3456">
<input type="submit" value="Like">
</form>
<?php
}
?>
NOTE: $connected should be a link as seen in mysqli_real_escape_string() and mysqli_query()
PS, I don't know what else you want to achieve. This code will show 'like' instead of the submit button when you click on it for a single post (only the first time you submit it). Work with it, you can try to think how to adapt the code for several posts, how to count the total number of likes for each post, if you want to display when mouseover which users liked it, add the ability to remove the like, anything you want. That's up to you.

Upload a dynamic page to server

I have a page that contains a table that the user can update. This has been done using javascript.
When the user has finised updating, I want to have the raw HTML page uploaded to the server, and then the user will be redirected to a php page which will do some final processing and spit out a report.
Is this possible or should I come up with another method of reaching the same end... and if so how do I get the dynamically created HTML onto the server to be manipulated?
You could have a form with a hidden input, and load the html into it using jquery.
So, your html may look like this:
<table id="table1">
... (this is the table from which you want to get the html)
</table>
<form id="form1">
<input type="hidden" id="table_html" name="table_html" />
<input type="submit" value="Submit" />
</form>
<script>
$("#form1").submit(function() {
$("#table_html").val($("#table1").html());
});
</script>
I didn't test this or anything, but the idea is that when you submit the form, the script populates the hidden value with the table html.
Now, if you have complex stuff in the table (I assume you do since the user can edit stuff right there), then maybe sending all the html isn't the best thing, you'll get a lot of garbage with the "useful" stuff. The way I'd do it is have the table inside the form, and have everything in inputs. Probably the names of the inputs will be like "first_name[]", so php will get arrays of values when there are several rows with the same cells and stuff like that.

Categories