Inserting values into form fields --PHP - php

I get values from an HTML form using a post method and store them in my DB through the mysql INSERT command (done in PHP).
something like this:
$value = $_POST['name'];
$value1 = $_POST['age'];
$sql = "INSERT INTO table(name,age) VALUES('$value','$value1')" ;
Now what I want to do is I want to give a link in the same PHP file like:
echo 'To update just entered info click on me';
Now the rascal.php as mentioned in the link above also contains the same form fields (name and age).
The values stored in the database through the INSERT command above should be fetched from the DB and placed in the respective form field area (name and age should be stored in their respective forms of rascal.php).
How can I do this?

Here it is:
<?php
if(isset($_GET['name']) AND isset($_GET['age'])){
$name=$_GET['name'];
$age=$_GET['age'];
}
else{
if(!empty($_POST['name']) AND !empty($_POST['age'])){
$value=mysql_real_escape_string($_POST['name']);
$value1=mysql_real_escape_string($_POST['age']);
$sql = "INSERT INTO table(name,age) VALUES('$value','$value1')" ;
mysql_query($sql);
echo 'To update just entered info click on me';
}
}
?>
<form method="POST">
<input name="name" value="<?php print $name;?>"/>
<input name="age" value="<?php print $age;?>"/>
</form>
This should work if you change 'table' to your table name. You should be happy, because I wrote the entire code for you. Please show it.
Further advice: Make sure your code is save by passing all input variables through a mysql_real_escape_string() function. Add an id field (unique key, self incrament) to your database table so you can select records based on their id's and not some other field (The code I provided only works if you don't have more entries with the same name).
There are some great php tutorials here.

Bobby Jack is exactly right about the danger of this, but I'll try to answer your question anyway.
Why not do it without touching the database? You could modify the link to rascal.php like so:
echo 'To update just entered info click on me';
And then use $_REQUEST['name'] to get that information in rascal.php. This way you are assured the same values are carried over.
Another way could be to use the mysql LAST_INSERT_ID and fetch the information that way, though it would not be 100% reliable, you could use that id for a query to populate the form as well.
EDIT: You could use LAST_INSERT_ID and put that id in the link for rascal.php, or use it in rascal.php itself to query the information you need.

Related

How to use a dropdown to auto fill form with data from mysql db

Hi All I have created a form below (entryform.php)to enter order details.
form contains: part_id, price, model.
I already created connect.php to connect to the database, and custompcorder.php to insert data in order_details table and entryform.php to enter data.
Here is what I will like to do on my entryform.php:
1- make the Part input field as A drop down that get part name and part_id from Parts table value to save is part_id but show part name on the entryform.
2- After the part is picked in the drop down, I want the fields price and model to be automatically filled with appropriate data from part table. Autofill will use the part_id to get the correct data. as you can see on the form below, many rows will be entered at a time.
entryform.php
<?php
<form action="../action/custompcorder.php/" method="post">
<p>Part: <input type="text" name="part_id"/> Price: <input type="text" name="price"/> Model: <input type="text" name="model"/></p>
<p>Part: <input type="text" name="part_id2"/> Price: <input type="text" name="price2"/> Model: <input type="text" name="model2"/></p>
<input type="submit" value="Submit" /></form>
?>
connect.php
<?php
$dbhost = 'localhost';
$dbuser = 'user2';
$dbpass = 'password';
$dbname = 'db3';
$con=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
custompcorder.php
<?php
include_once '../action/connect.php';
$sql="INSERT INTO order_details (part_id, price,model)
VALUES
('$_POST[part_id]','$_POST[price]','$_POST[model]'),
('$_POST[part_id2]','$_POST[price2]','$_POST[model2]')";
?>
First of all, your input fields are text, so it doesn't make sense there. I would write a function for it, so you can simply change the query within it. As an example below here.
Editted after questio in comments
Have you checked with the development tools in google chrome that page? it shows you the lay-out and CSS (part 1, the mark up). and how it's build up. From there on, you can check with what functions you need to use. In your case you need a couple of dropdowns and you need to do some database work.
For instance, say you want to show the RAM memory, and you have a database called models, make sure you have a partId, partPrice, partName and partType. For instance, if you have RAM, and it's a RAM memory part, say you assign the value 1 to it. In your case your query of the dropdown would be (as I explained above)
function LoadRAMParts(){
$query = "SELECT *
FROM models
WHERE partType = '1';
ORDER BY partName DESC;";
$resultaat=mysqli_query($query);
return $resultaat;
}
So you get returned all your RAM Memory parts now, which you can now just simply load into your dropdown menu by using a bit of PHP
function MakeRAMMemoryDropDown(){ // define name of the php function and open the function
echo "<select name='RAMPartId' class='dropdown'>"; // open the dropdown with the name RAMPPartId
$results = LoadRAMParts(); // Load in the query from earlier
while($row = mysqli_fetch_array($results)){ // while lets it loop through your results as long as there are results
echo "<option value='".$row['partId']."'>" // the value for the ID when it's chosen
.$row['partName']."</option>"; // the name of the product the user sees
} // end of the loop
echo "</select>"; // end of the dropdown
} // end of the php function
This you exectue in a seperate file that you include on the top. (I run first my queries first, then create the dropdowns, else it becomes a conflict, because the function i call within my dropdown function has to excist, prior to the dropdown. For me it looks like this.
So as final part, and I hope i explained it to you a bit, you need to call in the function into your PHP page where you want to use it. That just goes simply by the code:
<?php MakeRAMMemoryDropDown() ?>
As example:
And thats called dynamicly loading in your content. Now I use a different type of code placement and different ideas of generating contenct, but to each programmer it's own style. This is how I load in my content.
As for your loading prices question, you have to that with AJAX (Asynchronous JavaScript And XML) but thats not my cup of tea, I cant help you there. Sorry.
I hope I explained it to you, if not, I hope you figure it out another way then.

Website form populated from mySQL database, how to return data

I am trying to write a wordpress plugin and I have hit a bump. I am new to PHP (coded in Java before) and javascript so I am not sure whats the best way to solve my problem.
The Background
I have some data in a mySQL DB that I am using (each row has a unique ID and some other information I have added). I am able to search the DB using
$headss = $wpdb->get_results("SELECT * FROM {$wpdb->prefix}costumesdb WHERE location = 'head'", ARRAY_A);
And display some of the information to the user using (this is one of 5 different drop-downs but they are all created in the same way)
Head: <select name="head">
<?php foreach ($heads as $head) { ?>
<option value="<?php echo $head['pieceName'] ?>"><?php echo $head['shopName'] . " - " . $head['pieceName'] ?></option>
<?php } ?>
</select>
For the moment I want the user to be restricted to choosing information that is already in the system.
The problem
The DB contains 2 pieces of information that the user does not need to know to fill in the form (a website URL and a picture URL). I need these 2 pieces of information once the form is submitted (I need to write some more code for that) to the server which spits out another page with the 2 URL's in it.
Whats the best way to send the data back to a PHP script? Am I able to access the row of data that the user has selected in the drop down and send the unique ID for that row back or do I need to do something else?
Edit:
This is the script that I am using to submit the code:
$('#createacostume').form({
success:function(data){
$.messager.alert('Info', data, 'info');
}
});
'
And then the page to display the information returned is:
$cname = $_POST['cname'];
$head = $_POST['head'];
echo "Data Returned Name $cname head $head
I think this is what you are asking:
User has to choose an item from a drop down and submit a form. You have to display the website URL and the image for that item in a second page. You want to know how this is typically accomplished.
If that's the case, you should pass the row id of the item to the second page like so:
<option value="<?php echo $head['ROW_ID'] ?>"><?php echo $head['shopName'] . " - " . $head['pieceName'] ?></option>
Then use the ROW_ID in the second page to access the data from the database and print out the website URL and the image.
Submit the first form (without the two field), INSERT the data into the database, get the ID of insert.
Pass the ID to the next page which would set the ID into a hidden form field (or GET or POST parameter, plenty of choices) of the new form (with the two fields and just UPDATE the database upon submitting the second form.
If you like to show the original data in the second form, just pull the data from the database and use it to render the form instead of passing just the ID into a hidden field.

Form reviewing in HTML

I hope I'm not posting a duplicate question but I've looked around (and googled as well!) and nothing has given me the answer I'm looking for.
I have a form in HTML. When the user submits the form the values get stored with mysql under their user account for the site.
The issue is, I'd like the user to be able to go back and edit the form any time they like.
I could certainly just populate the form with values from php when the users review the form, but it gets tricky when I try to populate a file input field (and the file has been saved in mysql using the blob type). Not to mention that I'd like to do this as cleanly as possible.
Ideally it would be nice if there was a convenient module for reviewing forms that have already been submitted in JQuery per se.
Can anyone offer any advice? Thanks in advance!
Edit:
Here's a good example of what I mean - in chrome if I fill out a form and redirect to the next page after hitting submit, if I hit back I come back to the form and it's still filled out with the information I entered previously! Could I invoke this behaviour whenever I want to, as opposed to only when the user hits back?
You can't pre-fil an <input type="file" . . but surely when they come back to the form, they want to see the file they've uploaded .. this is what you mean right ..
So if its a picture, you could just do: <img src="loadpic.php?id=$var" />
If it's files they've uploaded, just list the file name / date and other data.. etc in some sort of list.
Then you could still show the <input type="file"> .. but with the label, 'add more pictures' or 'add another file'. .etc
Unless someone has a better way, at the moment I'm using a combination of 2 things:
1) Utilizing the $_SESSION variable
2) Setting the "name" attribute of every input in the form to the name of the field it corresponds to in the database.
This way I can loop through all the values dynamically instead of hardcoding them all in. Some input types (like file) are exceptional and will be handled on their own. Other that I can do something like this:
To insert into mysql:
$fields = array();
$values = array();
foreach ($_POST as $field => $value) {
$fields[] = $field;
$values[] = addslashes($value);
}
$fieldString = 'Table_Name('.implode(', ', $aFields).')';
$valueString = "VALUES('".implode("', '", $aValues)."')";
mysql_query("INSERT INTO $fieldString $valueString");
Reviewing the form is somewhat similar. I am using javascript to hook into document.onload. I need to pass javascript the records from mysql so that it may populate the form. Then it's a simple matter of getting elements by their name and assigning them their values that were passed from php.
The easiest way to do it and not have to go back to the database would be to store the values in a session.
<?php $_SESSION['myvalue'] = $inputvalue; ?>
On the html form use:
<input type="text" name="myName" value="<?php echo $_SESSION['inputvalue']; ?>" />
When completed don't forget to unset the session variable:
<?php session_start(); unset($_SESSION['myvalue']); ?>

filling the form in declared link

I have to declare an html link in my php file, i can do that in the following way
echo "<a href='razz.com'>Update</a>";
the link razz.com has a form fields(text type) in it, what i want to do is that when i open the link the form fields present in the link needs to be filled by the values that i declare in my initial php page.
the values of the form fields that needs to be filled are obtained from database.
How can i do that? Any tutorials or code snippet are appreciated.
Thank you.
Code snippet of what i am looking for:
a user fills form information which needs to go into database for storage:
the form is as follows:
<p>Title:<input type="text" name="title"/></p>
<p>Report No:<input type="text" name="rno"/></p>
<p>URL:<input type="text" name="url"/></p>
now after filling the form, the data will be stored in the database . A page with echo's successful with form information and a link to update the previously entered information will be displayed.
now again this update link contains the form structure , so instead of entering the information which was previously entered. the information already entered needs to be fetched and displayed in the form area.
You would need to use GET request parameters and the $_GET array on the page that is accepting the request to pass values to your link, but only if the http://razz.com/ index page actually accepts your URL parameters.
For instance (see the stuff and otherstuff GET keys in the URL):
echo "<a href='http://razz.com/?stuff=yes&otherstuff=yadayada'>Update</a>";
Then the razz.com index(.php):
$stuff = $_GET['stuff']; // with the link above, equal to yes
$otherstuff = $_GET['otherstuff']; // with the link above, equal to yadayada
echo "
<h2>$stuff</h2>
<p>I got $otherstuff.</p>
";
This would echo on razz.com/index(.php):
<h2>stuff</h2>
<p>I got yadayada.</p>
You could also use the $_POST array, but this would require more work and you would need to have a reason to do this (such as the data you're passing is transitory). You could do this by triggering a form, which you could also do a GET request with.
However, your question is not really that well worded. If you can provide more context and direction, that would help.

Help with deleting items in a list, using PHP

I have a list of email addresses in a table, which is populated via an SQL query. Next to each email address, I've placed a submit button which I want to use to delete the email address that appears in that particular table row.
I thought of appending the email address to the name of each delete button, with the hope that it will take me in the right direction.
while($row = mysql_fetch_array($result))
echo "<tr><td>".$row['email_adress']."</td><td><input type=\"submit\" value=\"Delete\" name=\"delete".$row['email_adress']."\"></td></tr>";
I'm wondering how to use the delete button for each entry. Any help?
I think the issue is that you are attempting to use submit buttons to contain data when submit buttons are not meant to contain data. Well they can and people do use them that way, but I prefer to use submit buttons to determine how to handle the data rather than to be the data in the submit. There are two basic methods that I think would be a fair extension to what you are trying to do.
1.) Use links to issue the delete
2.) Use the submit button to issue the delete, but include a hidden form field to contain the email address to delete.
In the case of using a link you don't have to deal with a form, but I don't know about the rest of the page. If you are sending any other data, then a form is the ideal way. If you are just sending a single piece of data to delete the email, then I suggest a link. My recommendation come from a functional perspective. You might have a UI reason to a button that I don't know about.
In the case of using a form, the hidden field should contain the primary key (untested):
while($row = mysql_fetch_array($result)) {
echo "<tr>
<td>".$row['email_adress']."</td>
<td><form action="some/uri/to/something">
<input type=\"hidden\"
name=\"emailAddress\" value=\"{$row['email_adress']}\"/>
<input type=\"submit\" value=\"Delete\"
name=\"delete".{$row['email_adress']}."\">";
</form>
</tr>
</td>";
}
You have to create a form around each submit else every hidden field in the form would be submitted telling you nothing about which email to delete. You can do many more things with the submit by using Javascript, but the simple method would be to just use a link -- forget about forms.
If a button is absolutely a must, you could output a small form for each button and add a hidden field containing the id (or email, if you insist). The form would submit the id or address in the hidden field, which you pick up in your processing script and run your delete query.
edited to remove a portion of the answer that was determined to be an unwise method
so I've been messing around with this code trying to get a "prefetch browser add-on" to trigger something and kill my database... but I havn't been able to trigger anything yet... but I'd sure like to.
<?php
//CREATE AND POPULATE DB
if(!file_exists('a.sqlite')){
$db = new SQLite3('a.sqlite');
$db -> exec("CREATE TABLE test (idx INTEGER PRIMARY KEY, number INTEGER NOT NULL);");
for($i=0;$i<9;$i++){
$db -> exec("INSERT INTO test (number) VALUES (".(rand(1000,9999)).");");
}
}else{
$db = new SQLite3('a.sqlite');
}
//PERFORM DELETE FROM HREF
if(isset($_REQUEST['delete'])){
$db -> exec("DELETE FROM test WHERE idx = ".$_REQUEST['delete'].";");
}
//SHOW CONTENTS OF BASE OR DELETE DB FILE
$result = $db->query('SELECT * FROM test');
while ($row = $result->fetchArray()) {
echo "<a href='test.php?delete=".$row['idx']."'>".$row['number']."</a></br>";
}
?>
Yes, you could do it like this but that would require to either execute the query again on the form's target page and then check for every combination of "delete".$row['email_adress'] or use a construction like this:
foreach ($_REQUEST as $key => $dummy)
if (substr($key,0,6) == 'delete')
delete_entry(substr($key,6));
However, if you simply swap value and name...
<input type=\"submit\" name=\"Delete\" value=\"".$row['email_adress']."\">
...you can just check $_REQUEST['Delete'] to find out which address button has been clicked.
... I'm still not sure about displaying peoples emails on web pages unless it's company internal.. I gather we are in a secure company back office?
I'd go for the:
<a href=my_page.php?delete_email_id=456>email</a>
probably with some annoying javascript for the confirm
email
and catch it with a
if(isset($_REQUEST['delete_email_id']){ SQL UPDATE ENTRY...}
at the top of my_page.php

Categories