so I've finally figured out how I can get values from my mySQL-db into a dropdown form in PHP. My problem is, how can I use/work with the option that was selected by the user?
My goal is a functioning email-signature generator. I want the user to be able to insert unique data like their name, and select the office where they work from the dropdown form. After they hit the submit button, they should then be lead to the next site that displays their name with the signature for the selected office.
The name is no problem, that is only a simple html-form with a post method, I know how I can retrieve and access that.
But how can I work with the option that was selected by the user in the dropdown?
After selecting an option and hitting submit, the whole "row" in the mySQL-db should be displayed, in formated form.
My current situation is that the dropdown shows the correct values from the mySQL-db, and the two name fields, that are also working as they should.
The name of the mySQL database is "firmen", the name of the column I use is "niederlassung".
I'm happy to provide more information if needed.
My code:
[...]
<form action="php-verarbeitung.php" method="post">
<div>
<label for="1">Vorname: </label>
<input type="text" name="vorname" id="1" value=""><br><br>
</div>
<div>
<label for="2">Nachname: </label>
<input type="text" name="name" id="2" value=""><br><br>
</div>
<input type = "submit" name = "button" value = "Senden"><br><br>
<?php
// Establish mySQL PDO Connection
$server='mysql:host=*****.com.mysql;dbname=*****'; // Host and DB-Name
$user="******"; // Username
$password="*****"; // Password
$pdo=new PDO($server, $user, $password);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Write out the query
$query = "SELECT niederlassung FROM firmen";
// Execute it, or let it throw an error message if there's a problem
$stmt = $pdo->query($query);
$dropdown = "<SELECT name='firmen'>";
foreach ($stmt as $row) {
$dropdown .= "\r\n<option value='{$row['niederlassung']}'>{$row['niederlassung']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
?>
</form>
</body>
</html>
Thanks for any help in advance!
you are passing the variables through the form to php-verarbeitung.php. On that page you can load the content based on the $_POST variables that are sent through the form. so you can query the DB again on the second page to get the info you need, and present formated html using the values from the form passed through the post array, in your case
$_POST['vorname'], $_POST['name'] and $_POST['firmen'] should all be accessible when the php-verarbeitung.php page is called using your script above.
Related
So, I have a form with some field in my page. For example - auth.php. The data in fields of this form recieved by calling some php function, that gives this data from MySQL DB. The code:
<?php
include 'functions.php';
$result=array();
$result = GetEntries();
$json = json_encode($result);
?>
The data inserting in fields by this code:
<script type="text/javascript">
function nextFunc(){
var name2 = <?php echo $json;?>;
document.getElementById("rname").value = name2[currententry]['Name'];
}
</script>
But how to realize mechanism of insertion some entry to my MySQL DB. For example, user pressed the ADD button on my Form, fill the field "Name" by his own data and press SAVE button - i want to save this user data directly in my MySQL DB.
Please help!
To achieve this, you'll need to follow a few steps:
create the html form
form.html
<form action="submit.php" method="post">
<label>
Name <input type="text" name="name" />
</label>
<input type="submit" value="Save" />
</form>
create submit page
submit.php
<?php
$name = strip_tags($_POST['name']);
// connect to database
$con = new mysqli('localhost', 'db_username', 'db_password', 'db_name');
if ($con->connect_errno) {
printf("Failed to connect to mysql: %s", $con->connect_error);
}
// prepare the query
$sql = sprintf("INSERT INTO my_table SET name = '%s'", $name);
// insert into database
$query = $con->query($sql) or die($con->error);
// view ID of last inserted row in the database
print_r('Last inserted ID: '.$con->insert_id);
Now you should be able to have your data in database.
Please have a look at this example on how to connect to database http://docs.kisphp.net/database-connect/
Instead of mysqli you may/should use PDO.
P.S.
In your code:
include 'functions.php';
$result=array(); // this line should not be here
$result = GetEntries(); // is overwritten by this one
$json = json_encode($result);
Is always a good practice to follow some principles:
function names starts with lowercase
class names starts with uppercase
do not use ?> in php files that contains only PHP code
indentation of all code is not necessary.
and so on.
you may find here more details http://www.php-fig.org/psr/psr-2/
P.P.S.
This is basic usage. Once you understand the principle you can extend it to ajax. Create an ajax function that will submit the form data to submit.php file.
Being new to PHP and SQL, I have build a simple HTML form with 20 inputs, allowing users to enter specific data through input type=text or file. I have built a mysql database where this user data is inserted / saved. All is working, this is a major accomplishment for me.
I'm asking for help on this next step, I think this step would be called “edit”?
This step would allow users to recall the mysql data they entered, at a later time, to edit and save. Would like to have this recalled data injected directly into the original HTML form. Now, it seems necessary to have a method, (possibly a HTML form ”id “input), that calls from the data base, the specific record (including all 20 data inputs) that is associated with this user. Am I thinking correctly?
I'm asking for help / direction with simple yet detailed approach to solve this step. Note, my few attempts at this “edit” step, using some examples, have failed. I do not have a firm grasp of this PHP, yet have strong desire to become proficient.
This is a model, stripped down version of my current working code. I eliminated the $connection = mysql_connect.
This is the PHP I built, working great!
<?php
require('db.php');
if (isset($_POST['first_name'])){
$first_name = $_POST['first_name'];
$favorite_color = $_POST['favorite_color'];
$trn_date = date("Y-m-d H:i:s");
$query = "INSERT into `form_data` (first_name, favorite_color, trn_date) VALUES ('$first_name', '$favorite_color', '$trn_date')";
$result = mysql_query($query);
if($result){
echo "<div class='form'><h1>First Name & Favorite Color POST to db was successfull.</h1>
<br/><h3>Click here to return <a href='https://jakursmu.com/tapcon_builder/tb_form_data_1.1.php'>TapCon Builder</a></h3>
</div>";
}
}else{
?>
This is the HTML user form, works great with the PHP script:
<div class="form">
<h1>First Name & Favorite Color "POST" to db Test</h1>
<form target="_blank" name="registration" action=" " method="post">
<p> First Name<input name="first_name" type="text" placeholder="First Name" /> </p>
<p> Favorite Color <input name="favorite_color" type="text" placeholder="Favorite Color" /> </p>
<p> <input type="submit" name="submit" value="Submit / Update to db" /></p>
</form>
</div>
Suppose the user queries the database using their “first_name”, when this “edit” step is completed, the final result will render / inject the users “first_name” and “favorite_color” back into the original HTML form. Does this make sense?
The database I created for this help post, looks like this:
database image
When a user wishes to edit their data, they can enter their "first_name", in a form text input, (im assuming?) where their "first_name" will be found in the data base. The ouutput result of this database query will be injected into the original form, ready for any user edit.
User Edit for: Results (in origingal form):
Jack Jack Black
Jeff Jeff Green
Randall Randall Red
So on.........
I hope this explanation makes sense where any experienced help or direction is offered.
Thanks for viewing!
just for practice purposes, but can look into prepared statements at you liesure time.
first create ur php file
<form method="post" action="edit.php">
<?php
//in ur php tag. select items from the row based on an id you've passed on to the page
$sql = "select * from 'form_data' where blah = '$blah'";
$result = mysqli_query($connection, $sql);
if($result){
$count = mysqli_num_rows($result);
if($count > 0) {
while($row = mysqli_fetch_assoc($result)){
$name = $row['firstname'];
$lname = $row['lastname'];
//you can now echo ur input fields with the values set in
echo'
<input type="text" value="'.$name.'" >
';//that how you set the values
}
}
}
?>
</form>
Finally you can run and update statement on submit of this you dynamically generated form input.
Also please switch to mysqli or pdo, alot better that the deprecated mysql.
look into prepared statements too. Hope this nifty example guides you down the right path...
I am trying to make a webpage that connects to my SQL database and fetches information from a table and place it into a text box. The information it fetches is dependent on what is entered into another text box. Essentially its an "autofill" of information. I was curious whether this was possible.
To create a better understanding here is a layout of text boxes:
<html>
<head>
<?php
$con = mssql_connect("abc", "123", "password");
if (!$con)
{
die('Could not connect: ' . mssql_get_last_message());
}
mssql_select_db("db1", $con);
$result = mssql_query("SELECT * FROM FormData");
<head>
<title>test</title>
</head>
<body>
<h1>test</h1>
<form action="#">
<p>Enter ID</p>
<input type="text" name="ID"/>
<input type="text" name="NAME"/>
<input type="text" name="LASTNAME"/>
<input type ="button" value="submit" onclick="check(ID)" />
</form>
</body>
Here an ID would be entered into a text box and then once the submit button was pressed, it would fetch the rest of the information from my sql database into the next boxes. I don't even know whether this is possible, whether I can use Javascript in conjunction with this or something. I searched but couldn't find much help on the subject.
I'm not even sure if its possible to do "if" statements within SQL - whenever I try I end up with a 500 error due to improper syntax.
If I understand you correctly, all you need to do is on the submission of the form capture the ID they entered.
If the ID has not been submitted yet (either their first time hitting the page, or they failed to enter an ID) you should not perform any query and create a blank $row array like so:
$row = array("ID" => "", "NAME" => "", "LASTNAME" => "");
You should then fill your form fields using this array <input type="text" name="NAME" value="<?php echo $row['NAME']; ?>"/>.
If the ID has been submited you then use this ID in your SQL query "SELECT * FROM FormData WHERE ID = $_POST['ID']" (Note: This is an example. You will need to escape the POST data to prevent SQL injection).
You need to then pull this result into your $row array $row = mysql_fetch_row($result) which in turn is used by your fields to populate the value.
This entire procedure could be done with AJAX so that you don't have to perform a full page submit however based on your example the solution I have provided should be good enough.
This code works. I can't figure out how to insert data into db If user pressed "SAVE" button for the first time or update data.
The php side
<?php
require '../../core/includes/common.php';
$name=filter($_POST['name'], $db);
$title=filter($_POST['title'], $db);
$parentcheck=filter($_POST['parentcheck'],$db);
if(isset ($_POST['parent'])) $parent=filter($_POST['parent'],$db);
else $parent=$parentcheck;
$menu=filter($_POST['menu'], $db);
$content = $db->escape_string($_POST['content']);
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('$parent', '$name', '$menu')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', '$title', '$content')") or die($db->error);
if ($new_id>0){
echo "{";
echo '"msg": "success" ';
echo "}";
}else{
echo "{";
echo
'"err": "error"';
echo "}";
}
?>
UPDATE
Thanks to #jmlsteeke i found the way
Place this piece of code in html part
<?php
$result=$db->query("INSERT INTO menu (parent, name, showinmenu) VALUES ('555', 'new', '0')") or die($db->error);
$new_id = $db->insert_id;
$result2=$db->query("INSERT INTO pages (id, title, content) VALUES ('$new_id', 'new', 'new')") or die($db->error);
?>
And added following code into form
<input type="hidden" name="id" value="<?=$new_id?>"/>
In serverside script used
$result=$db->query("UPDATE pages AS p, menu AS m SET m.parent='$parent', m.name='$name', m.showinmenu='$menu', p.id='$id', p.title='$title', p.content='$content' WHERE m.id='$id' AND p.id=m.id") or die($db->error);
Thank you #jmlsteeke
A common way would be to store the id as a hidden field when you are editing the page. This way when the user submits the page, if there is an id present, you issue the UPDATE commands, and if there isn't one present, you know it's a new page, and issue the INSERT commands.
If you need me to be more thorough let me know.
Edit: Being More Thorough
I'll make a simple, complete, example of what I mean.
Form.php pseudo code
//set default values for fields
//print form tag
if (isset($'id',$_GET)) {
//fetch data from database
//print hidden id field
//override default values for fields
}
//print rest of fields using default values (possibly overridden)
DoForm.php pseudo code
//Sanitize user input
if (isset('id',$_POST)) {
//UPDATE database with user input
} else {
//INSERT new rows into table with user input
}
Let's say you have a php file called Form.php which is responsible for displaying the form, and another php script called DoForm.php which is responsible for handling the form.
If a user visits Form.php with no ID specified (http://example.com/Form.php) then it will display the following form:
<form method="post" action="DoForm.php">
<input type="text" name="name" value="" />
<input type="text" name="title" value="" />
... other stuff ...
</form>
The user will add some information, click on the submit button and DoForm will get the following POST variables:
"name" => "NewPageName"
"title" => "My First Webpag" [intetional typo, see later]
... other stuff ...
DoForm will check to see if $_POST['id'] exists. Since it doesn't DoForm issues the INSERT commands to add a new page.
Later on, the user realises the made a typo, and goes to fix it. The user clicks on the "Edit Page" control for "NewPageName" which will be http://example.com/Form.php?id=1
Form.php see's that id is set, so the form it prints out is as follows:
<form method="post" action="DoForm.php">
<input type="hidden" name="id" value="1"
<input type="text" name="name" value="NewPageName" />
<input type="text" name="title" value="My First Webpag" />
... other stuff ...
</form>
The user fixes their type, changing Webpag to Webpage, and hits submit. DoForm gets the following Post variables
"id" => 1
"name" => "NewPageName"
"title" => "My First Webpage"
... other stuff ...
DoForm sees that id is set, and so uses UPDATE instead of INSERT.
Any more clear?
MySQL has an INSERT ... ON DUPLICATE KEY UPDATE feature that will let you try to insert a row, or fall back to an update if it discovers a duplicate key (i.e. the row already exists).
I am new to PHP and working on small local webpage and database that takes user information and database stores the same user information .If i Login with ADMIN it shows all data. My requirement is that the loggined user is an admin, then he has a right to edit all the informtion of the users that i stored in the database.And this is to be done using GET method . How it will be working?
Heres some example code purely to demonstrate how to update a table using a GET method form. The code doesn't have any kind of error checking and assumes you already know how to connect to your database (and that its MySQL).
Assuming you've landed on a page which invites you to edit data, which record you're editing is referenced by an 'id' variable on the URL which matches a numerical primary key in your database table.
<?php
$SQL = "SELECT myField1,myField2 FROM myTable WHERE myKeyField = '".intval($_GET['id'])."'";
$QRY = mysql_query($SQL);
$DATA = mysql_fetch_assoc($QRY);
?>
<form method='get' action='pageThatStoresData.php'>
<input type='hidden' name='key' value='<?php echo $_GET['id']; ?>' />
<input type='text' name='myField1' value="<?php echo $DATA['myField1']; ?>" />
<input type='text' name='myField2' value="<?php echo $DATA['myField2']; ?>" />
<button type='submit'>Submit</button>
</form>
So, this will give you a page that takes the data out of your table, displays it in a form with pre-filled values and on submit, will go to a URL like:
http://mydomain.com/pageThatStoresData.php?key=1&myField1=someData&myField2=someMoreData
In that page, you can access variables 'key', 'myField1', 'myField2' via the $_GET method.
Then you just need to update your table within that page:
$SQL = "UPDATE myTable
SET myField1 = '".mysql_real_escape_string($_GET['myField1'])."',
myField2 = ".mysql_real_escape_string($_GET['myField1'])."
WHERE key = '".intval($_GET['key'])."'
";
$QRY = mysql_query($SQL);
PLEASE NOTE: The code above is unsuitable for a straight copy/paste as it doesn't do any error checking etc, its purely a functional example (and typed straight in here so I apologise if there are any typos!).