Php: updating database with values from dynamically generated form fields - php

How do I save the following form?
<form name="myform">
<input type="text" name="title" value="title" />
$result = mysql_query("SELECT id, text from details where parent='$parent'
order by id asc") or die('Error');
while(list($id,$ftext) = mysql_fetch_row($result)) {
?>
<textarea name="formfield<?php echo $id;?>" id="<?php echo $id;?>">
<?php echo $ftext;?>
</textarea>
<?php
}
</form>
As you can see above, the MySQL query will load data and dynamically create textareas:
<textarea name="formfield34" id="34">text</textarea>
<textarea name="formfield56" id="56">more text</textarea>
<textarea name="formfield78" id="78">anothet text</textarea>
I need to update database like this:
$result = mysql_query("UPDATE details SET text='$formfield34' WHERE id ='34'") or die('Error');
$result = mysql_query("UPDATE details SET text='$formfield56' WHERE id ='56'") or die('Error');
$result = mysql_query("UPDATE details SET text='$formfield78' WHERE id ='78'") or die('Error');
The problem is that each form will have a different number of textareas loaded dynamically and different $ids. I can not imagine hot to save this form.
Thanks.

What you probably need to do is to look at using array notation in your form field names like this:
<textarea name="formfield[34]" id="34">text</textarea>
<textarea name="formfield[56]" id="56">more text</textarea>
<textarea name="formfield[78]" id="78">anothet text</textarea>
PHP will automatically build an array in $_POST['formfield']. that you can access with all this data. This make it easy to loop through this array and generate SQL for your updates.
foreach($_POST['formfield'] as $key => $value) {
// write SQL here
}
Now, rather than a bunch of individual SQL queries, you might want to consider using REPLACE syntax so that you can insert/update your data with a single query.

in the "while" while creating the textarea save an array with the id of these textarea.
Then retrace the array to use ids when you need it

Related

Using a PHP variable as a form fields default value

I have a created an HTML form where users sign up and input there data into an SQL database. I have then retrieved that data in a webpage where they can view their profile. I have created a page where users can edit there profile by creating a form which updates the value in the SQL database for there user id.
I would like the form to use the current value of the SQL cell as the default for that user to make alterations easier. Example: currently user 7 has their city set as New York, when they visits the edit info page, the city field in the form already hase New York as the default value.
I have no problem getting the SQL info and assigning it to a variable, I just don't understand how to set it as the default value. I am aware of how you set default values for input fields though.
My code:
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
echo mysqli_error();
}
}
?>
<input type="text" name="aboutme" defualt="<?php echo $row['aboutme'] ?>" >
There's no default value for html input.
Input can has value, using attribute value:
<input type="text" name="some_name" value="Some value" />
In your case it's
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> />
Input can also has placeholder - some value that is present in an input, but erased when user starts to edit input's content:
<input type="text" name="aboutme" value="<?php echo $row['aboutme']?> placeholder="some value" />
How about
<?php
$id = $_SESSION["user_id"];
// Create a query for the database
$query = "SELECT full_name FROM users WHERE id = $id LIMIT 1";
// Get a response from the database by sending the connection
// and the query
$response = #mysqli_query($dbc, $query);
// If the query executed properly proceed
if($response){
while($row = mysqli_fetch_array($response)){
echo $row['full_name'];
?>
<input type="text" name="aboutme" value="<?php echo $row['aboutme'] ?>" >
<?php
echo mysqli_error();
}
}
?>
And here is a good example http://www.w3schools.com/php/showphpfile.asp?filename=demo_db_select_pdo
Neither of the answers worked and upon further research and trial and error I created a solution.
I changed the value that was store in the array to just be a normal php variable:
$aboutme = $row['aboutme'];
I then called that variable using the following code:
<input type="text" name="aboutme" value="<?php echo htmlspecialchars($aboutme); ?>" >
Thanks for your help.
I hope you find my answer useful.
Why don't you try using it as a place holder? This will provide editable text.
<input type="text" name="aboutme" placeholder="<?php echo $row['aboutme'];" />

HTML Form button in PHP While loop

I have a while loop in PHP that selects data from a database
I want to have a complete button for each row returned which, when pressed will run an SQL Query to change the value of the status column of that particular row
my while loop is:
$stmt = $pdo_conn->prepare("SELECT * from messages where status = :status and (assigned_to = :assigned_to1 OR assigned_to = :assigned_to2) ");
$stmt->execute(array(':status' => '', ':assigned_to1' => $user_result["sequence"], ':assigned_to2' => ''));
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
$i=0;
if(count($records) > 0) {
echo '<tr>
<td colspan="7">You have '.count($records).' Messages</td>
</tr>';
foreach($records as $Messages) {
$i++;
echo '<tr>
<td>'.AdminNameLookup($Messages["assigned_to"]).'</td>
<td>'.$Messages["caller_company"].'</td>
<td>'.$Messages["caller_telephone"].'</td>
<td>'.$Messages["caller_email"].'</td>
<td>'.$Messages["caller_message"].'</td>
<td><input type="submit" name="CompleteMessages['.$i.']" value="" /></td>
</tr>';
}
}
but I'm not too sure on how to handle the PHP on submit?
Before sending data you need to create html form tag. And also you have pass values using input tag values.
format tag should be like this below code.
<form action="" method="">
<input type="" value="">
<input type="submit" name="CompleteMessages['.$i.']" value="" />
</form>
I would use this instead:
<td><input type="submit" name="CompleteMessages" value="'.$i.'" /></td>
You can then get the id with:
$Id = $_POST['CompleteMessages'];
Personally I'd have $i set to $Messages["message_id"] to you can find what Id you have actually submitted.
You also need to wrap everything in a form tag:
<form action="submit.php" method="POST">
...
</form>
If you only want to change the value of the row where you clicked the submit button,
then you will need a unique key for each record.
Lets assume that the messages table has a MessageID column.
One approach would be to call a javascript function.
Let's say your javascript function was called UpdateColumn(ID,ColName,Index)
Here's what would need to be added to each input button (pseudocode)
onclick="UpdateColumn($Messages['MessageID'],'Status',$i)"
Then your javascript will need to lookup value from input CompleteMessages[Index]
The Javascript could call your request php via ajax ...
update.php?MessageID=MessageID&Column=Status&Value=CompleteMessages[Index].value
And finally your php which handles the submit would take the values
using
$MessageID=$_REQUEST["MessageID"];
$Column=$_REQUEST["Column"];
$Value=$_REQUEST["Value"];
Then you will want to run a sql query which updates your database accordingly.

Populate HTML Form from Database

So I have searched for how to insert items from a MySQL database into a form. From what I understand, for each field, I need to add value="<?php echo htmlentities($Variable); ?>" is there a way to insert the fields all at once? Like in a PHP script? Each field already has a name identifier, that's how the insert.php insert the values into the database, like this:
//SQL Query to insert data
$sql="INSERT INTO case_info (Volunteer,CaseShortTitle,CaseNumber,HearingDate...)
VALUES ('$_POST[Volunteer]','$_POST[CaseShortTitle]','$_POST[CaseNumber]','$_POST[HearingDate]'...)
and the form fields look like this:
<div><input type="text" id="p1f5c" name="CaseShortTitle" class="fieldcontent"><div class="fielderror"></div></div>
Then the Submit button goes to this insert.php file
Is there a way to use GET to populate the fields in this manner?
Thank you!
It's generally bad practice to input data into your database directly from the $_POST variables, you should consider sanitizing them first.
If I understand what you are asking, you can do something like this;
<form action="" id="myForm" title="myForm">
<?php
$query = "SELECT * FROM case_info LIMIT 1";
$result = myqsl_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
?>
<input type="text" id="volunteer" value="<?php echo $row['Volunteer']; ?>"
<input type="text" id="CaseShortTitle" value="<?php echo $row['CaseShortTitle']; ?>"
<?php
} //Close while{} loop
?>
</form>

display data from database after chekcbox selection

I want to have a form that allows the user to choose what data to display from a table through checking the checkboxes. If the user wants only 2 columns to be shown, should only 2 columns be shown. I have my codes, but after I submit, it displays nothing.Here's my code:
<form name="form1" method="post" action="view_emp.php">
<p>Select Option
<input type="checkbox" name="number[]" value="name" />Name
<input type="checkbox" name="number[]" value="hired" />Date Hired
<input type="checkbox" name="number[]" value="basic" />Basic Pay
<input type="checkbox" name="number[]" value="incentives">Incentives
</p>
<input type="submit" name="Submit" value="Submit">
</form>
here's my php:
<?php
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('eis', $db) or die (mysql_error());
$employee = array();
foreach ($_POST['number'] as $employee) {
$number = mysql_real_escape_string($number);
$employee[] = "'{$number}'";
}
$sql = "select * from employees where type in (" .implode(", ", $number). ")";
$result = mysql_query($sql);
while ($row = mysql_fetch_array($result)) {
print $row['name'];
}
?>
i am a beginner in php and i need help from gurus and experts. thank you...
PHP's implode() and explode() functions might come in handy. You can easily turn your POST or GET attribute, 'number', into a comma-separated list by using implode($_POST['number']). This would be easy to store in one MySQL field, maybe a column in your user table.
If you want users to edit the form later, render the checkboxes with a loop and add a "checked" attribute to each checkbox element whose name exists in 'exploded' list (array) retrieved from your database.
This is basically serialization/deserialization. There are other ways to do it including serialize(), unserialize() or json_encode(), json_decode(). But since your data seems to be easily modeled as a basic list, you can keep it even simpler.

MYSQL Update not updating database?

I have a simple Form along side a PHP update query that simply isn't working! I know the PHP is working on the page as there are several validation checks that need to be passed before hand which are working perfectly. The form its self is inside the Colorbox Popup tool.
My HTML Form Code is:
<div id="stylized" class="myform">
<form action="#" method="post">
<input type="hidden" name="user_id" value="<?php echo $user_id; ?>" />
<label>First Name:<span class="small">Enter your forename</span></label>
<input id="first_name" type="text" name="first_name" maxlength="50" placeholder="e.g. Joe" required autofocus/>
<div class="spacer"></div>
<input type="submit" id="update" name="update" value="Continue to Step 2!">
</form>
</div>
With the PHP Code as follows (this is above the HTML code on the page):
<?php
if($_POST['update']){
$user_i = $_POST['user_id'];
$f_name = $_POST['first_name'];
$first_name = ucfirst($f_name);
mysql_query("UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'") or die(mysql_error());
} ?>
The actual submit appears to be working, with the Popup refreshing afterwards, but the database does not update! I have triple checked the syntax and the database fields. 'user' and 'first_name' and 'user_id' is correct.
Update: Because the popup box refreshes, I cannot view the error's from the 'or die(mysql_error()) unfortunately, other wise i might have been one step closer.
Any help would be hugely appreciated.
Many thanks in advance.
When you say pop-up box, I assume you are using ajax to communicate from the form to the server, which as you stated is difficult to view submitted data. If this is the case try:
error_log(serialize($_POST));
This will force an entry in your error log with the $_POST data in serialized format, so you can check the values you are submitting are populated correctly.
You will also want to sanitize the variables you are adding to the SQL:
$sql = "UPDATE user SET first_name = " . mysql_real_escape_string($first_name) . " WHERE user_id = " . mysql_real_escape_string($user_i) . " LIMIT 1";
mysql_query($sql);
I would:
print_r($_POST); to view the POST data.
Generate the SQL from a string so it can be printed for debugging purposes, like so:
$sql = "UPDATE user SET first_name = '$first_name' WHERE user_id = '$user_i'";
echo $sql;
mysql_query($sql) or die(mysql_error());
One of these techniques will likely tell you why the PHP-generated SQL doesn't update your database record.
you set your user_id field by echo $user_id; but your variable name is set to $user_i = $_POST['user_id'];
therefore your user id field is not set and your Mysql command will fail.

Categories