I have been working on my own PHP project. I have hit an obstacle. I am trying to retrieve the results of a database and print out a form for each result set.
I then wish to interact with one particular result either be deleting it or passing it into a function etc..
Heres is my current code :
<?php
while($row = mysqli_fetch_array($result)){
echo '<div id="post">'; ?>
<form action="" method="post">
<?php
echo "<font size=4>".$row['post']."<br>";
echo "posted by : ".$row['username']."<br>";
$id = $row['p_id']; ?>
<input type="submit" name="choice" value="Y">
<input type="submit" name="choice" value="N">
</form>
<br>
</div>
}
<?php
if($_POST['choice']=="Y"){
// progress
functionA();
}
else if($_POST['choice']=="N"){
// delete or remove
functionB();
}
?>
So my goal here would be click Y to progress that particular result or N to delete/remove the result.
However currently by clicking either button all results either get deleted or progress. I do know that the id should be used to differentiate between posts but I cant quite seem to get it to work. Once the button is pressed it passes all results to either function.
First of all, I suppose you want to know the record to delete. So, add an input to your form:
<input type="hidden" name="id" value="<?php echo $row['p_id']; ?>">
Then, in your script, call:
if( $_POST['choice'] == "Y" )
{
// progress
functionA( $_POST['id'] );
}
elseif( $_POST['choice']=="N" )
{
// delete or remove
functionB( $_POST['id'] );
}
Additional problem: how you can use your db connection inside the functions? Assuming your mysqli connection is named $conn, call the function(s) in this way:
functionA( $_POST['id'], $conn );
Side note: First process $_POST values, then retrieve db records and print it.
Side note 2: take a look at prepared statement.
Read more about variable scope
Read more about prepared statements
Use two different <input type="radio">s for each item with the id in the value and let the user select which to delete and which to process.
So for an item with id 1 the outputted HTML would look like:
<input type="radio" name="items[1]" value="delete"><input type="radio" name="items[1]" value="process">
The name forces the items to go to _POST as an array with the ids as keys and the selected action as their values.
Example html: https://jsfiddle.net/gu1gkwod/
Related
I have a value coming from another form in the same page called $_POST['serial']. And i want to use this value to run a query in another form but after I submit the second form nothing happened and the query not running.
<?php
if (isset($_POST['serial'])) {
$serial = $_POST['serial'];
?>
<form action="" method="post">
<button type="submit" name="submit">Click to use</button>
</form>
<?php
if (isset($_POST['submit'])) {
$query = mysql_query("UPDATE table_name SET status = 'inactive' WHERE serial = '$serial'");
}
}
?>
To pass the variable along you would create a hidden input on your second form to contain the value:
<?php
// check and clean up the passed variable
$serial = isset($_POST['serial']) ? htmlspecialchars($_POST['serial']) : '';
?>
<form action="" method="post">
<input type="hidden" name="serial" value="<?php echo $serial; ?>" />
<button type="submit" name="submit">Click to use</button>
</form>
For Safety's Sake
Your script is at risk for SQL Injection Attacks.
If you can, you should stop using mysql_* functions. These extensions have been removed in PHP 7. Learn about prepared statements for PDO and MySQLi and consider using PDO, it's really not hard.
Additional Thoughts
If you're planning to do a two-step form you'll likely want to place all of the data processing outside of the form page, in a separate PHP file. With the limited code that you have shown I fear that we will miss something in our answers which will lead you to additional questions because your code still isn't working as you would expect.
A button needs a name and a value to be successful. Your button doesn't have a value so $_POST['submit'] will be undefined.
Add a value attribute to your <button> element.
After you do that, $serial will be undefined because your form doesn't submit that.
You need to include it in your form too:
<input type="hidden" name="serial" value="<?php echo htmlspecialchars($serial); ?>">
I want to create a project that save the fill up forms in previous form and insert into database using one button only. For example answer1.php and answer2.php the save button is in the answer2.php i want to fetch data from answer1.php and save to databse same as in answer2.php
this code below insert data in one form only
$query = mysql_query("INSERT into holiday (holiday_no,holiday_name, status,campaign_name,holiday_type, createdBy, holiday_date, createdDate)
VALUES('$holiday_no', '$id','$status','$campaign_name','$hol', 'System','$date','$createdDate')") or die(mysql_error());
echo "Data has been saved with holiday name";
Not quite sure what you're asking for ...but giving it a try ;-) :
You can put the key-value pairs the first script receives into the next form so they get transmitted once again to the second script. E.g. if in the first step something like category=foo and country=bar gets transmitted write out a form that looks like
<form method="POST" action="answer2.php">
<p>
<input type="hidden" name="category" value="foo" />
<input type="text" readonly="readonly" name="country" value="bar" />
<!-- all the other things you want to add to the form -->
<input type="submit" />
</p>
</form>
But keep in mind that a) you need to encode the values properly for html output, otherwise your scripts are vulnerable for injection attacks, see http://docs.php.net/htmlspecialchars
and b) your second script can't "be sure" that the values haven't been altered or even transmitted to the first script at all; if you need that (e.g. for some transaction mechanism) you need something else like e.g. http://docs.php.net/features.sessions
Use hidden fields, a session, or a temporary table.
<?php
if (empty($_REQUEST)) {
echo '<form action="', $_SERVER['PHP_SELF'], '">
</form>';
} elseif (empty($_REQUEST['some_field_from_your_second_form']) {
// Do the second part of your form
} else {
// Do the final submission
// Sanitize the values
// Insert in the database
}
I'm trying to add multiple values into a database using PHP from an HTML. However, I can't just refer to the name attribute of the HTML form because each field in the form is generated by a PHP script. I've tried Googling around, but since I don't exactly know what I'm looking for, my search has been futile.
Here's the bit of code that I use to generate the HTML form:
<form action="input_points.php" method="post">
<?php
while($row = mysql_fetch_array($result)) {
echo $row['Name'] . ' <input type="text" name="userpoints">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
I don't know what names are currently in the directory so I need this piece of php to determine what names are in the database. Afterwards, I want to have a bunch of boxes for people to input points (hence the form). I'm having trouble figuring out how to link the particular text box with the user.
For example, if I have a text box for Bob, how would I link up the input text field that contains the number of points Bob earns with Bob's entry in the database?
I know you can do this with regular form fields:
$userpoints = $_POST['userpoints'];
UPDATE members SET points = $userpoints where $user = "Bob";
But since I have multiple users, how do I link up the correct database entry with the right user? Also, how would I determine which boxes are empty and which boxes are updated with a value?
If you want to update multiple filed then are using array
Please changes some code
<form action="input_points.php" method="post">
<?php
$userCount=mysql_num_rows($result);
echo '<input type="hidden" name="userCount" value="' .$userCount. '">';
while($row = mysql_fetch_array($result)) {
echo '<input type="hidden" name="userid[]" value="' .$row['id']. '">'; //Give the uniq id
echo $row['Name'] . ' <input type="text" name="userpoints[]">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
PHP Code -
$userCount = $_POST['userCount'];
for($i=1; $i=$userCount; $i++){
$userpoints = $_POST['userpoints'];
$userid = $_POST['userid'];
//UPDATE members SET points = $userpoints where $user = $userid;
//YOUR CODE HERE
}
The update you're trying to do is not safe unless you treat values to prevent SQL injection... but if you really want it, instead of mysql_fetch_array(), try using mysql_fetch_assoc().
Using mysql_fetch_assoc() you can extract the keys (database field names) with array_keys(). The keys will be your the name property of your form fields and the values of will be the fields' values.
Hope it helps.
You can use an array to store all the data that you need and add a hidden field that contains the missing data:
<form action="input_points.php" method="post">
<?php
for($i=0; $row = mysql_fetch_array($result); $i++ ) {
echo ' <input type="hidden" name="user[0]['name'] value ='". $row['name'] ."'">';
echo $row['Name'] . ' <input type="text" name="user[$i]['points'] ">';
}
?>
<button type="submit" name="add_points">Add Points </button>
</form>
Problem when you hit submit userpoints contain only the last value previous all values are overwritten
solution
name="userpoints"
must be different each time why not you define it in database and then fetch it just like you fetch $row['Name']?
I'm trying to get a website working. What I have are basically two images displayed (random, taken out of a mySQL database). What I need to do is (when the user clicks one of the images) the following:
Update the page, passing the info about the selected image (submit form);
Add one piece of data to the database (upvote the image)
I need to use $_POST to pass an array of values to the next page. So I thought:
<form name="input" action="the_page.php" method="POST">
<input type="image"
name="img"
src="image.png"
value ="dat1[\"data1\",\"data2\",\"data3\"]">
<!-- If value must be a single string, I'll use hidden inputs-->
</form>
<form name="input" action="the_page.php" method="POST">
<input type="image"
name="img"
src="image2.png"
value ="dat2[\"data1\",\"data2\",\"data3\"]">
</form>
Then I can upvote the selected image on the mySQL database with a little php upvote() function that updates the record. The upvoting process is done when the new page is loaded. From this, I have a couple questions:
I'm guessing the images will act as buttons, right? (They are supposed to submit the form, hence refreshing the page). If not, how can I achieve this? I'm unable to do it with a link (since I can't add the values to it). Maybe a javascript function? But I don't know how to submit the form that way either...
Once the page is reloaded, does it mean that only the data from one form has been submited, so I can retrieve the data by simply calling the PHP variable $_POST['img'] and get an array back?
EDIT: I now managed to get everything working, slightly similar to what I proposed initially. Thanks for the AJAX suggestion though, since it was what helped me solve it (looked up AJAX tutorials, found solution).
Here's my solution:
<?php
echo "<form name=\"input\" action=\"F2F.php\" method=\"POST\">";
echo "<input type=\"hidden\" name =\"table\" value=\"".$table1."\">";
echo "<input type=\"image\" name=\"nom\" src=\"".$IMG_Route1."\" value =\"".$Nom_base1."\" border=\"0\">";
echo "</form>";
?>
(where the image goes)
and then, on the header:
<?php
if ($_POST['nom']||$_POST['nom_x']){
if (!$_POST['nom']){
echo 'Could not retrieve name. $_POST[\'nom_x\'] = '.$_POST['nom_x']. mysql_error();
exit;
}
if (!$_POST['table']){
echo 'Could not retrieve table. $_POST[\'table\'] = '.$_POST['table']. mysql_error();
exit;
}
upvote($_POST['table'],$_POST['nom']);
}
?>
You can use one form and a set of radio buttons to simplify things a bit. Clicking on the label will toggle the radio button. You can use commas to separate multiple values for each checkbox, which you can then abstract later on (see below)
<form name="input" action="the_page.php" method="POST">
<ul>
<li>
<label>
<img src="whatever.jpg" />
<input type="radio" name="selectedImage" id="img1" value="12,16,19" />
</label>
</li>
<li>
<label>
<img src="whatever2.jpg" />
<input type="radio" name="selectedImage" id="img2" value="12,16,19" />
</label>
</li>
</ul>
</form>
You can detect when the radio button is selected by adding a listener for the change event, then submit the form.
$('input[name="selectedImage"]').change(function() {
$('form[name="input"]').submit();
});
To abstract the multiple values, you can then explode the form result with PHP, which will return an array of the values.
$selectedImageValues = array();
$selectedImageValues = explode(",", $_POST['selectedImage']);
From there you can pull the different values out and save the data to the database.
OK that probably sounded a bit confusing but what I have is a table that spits out courses locations and dates depending on what the user chooses. I than want the user to go through the fields and than on the 3rd submit button I have the course information displayed to them. I'm asking how in php i can take the echo from the first query and use that to upload it to the other table. Would I just be using MySQL Links?
If you have multiple pages, you can use $_SESSION variables to store the data for when you're ready for it.
If you have one page, with multiple forms, you can use <input type='hidden' /> fields to hold the data until you're ready for it (it will be stored in $_POST each time you submit the form).
Then, when you're ready, pull the info out of the $_SESSION or $_POST data and run your query.
For the $_POST solution:
<form action='' method='post' >
<input type='hidden' name='data1'
value="<? if(isset($_POST['data1'])) { echo $_POST['data1']; } ?>"
<input type='hidden' name='data2'
value="<? if(isset($_POST['data2'])) { echo $_POST['data2']; } ?>"
<input type='hidden' name='data3'
value="<? if(isset($_POST['data3'])) { echo $_POST['data3']; } ?>"
</form>
<?
if(isset($_POST['data1'] && isset($_POST['data2'] && isset($_POST['data3']) {
//Run your query, echo results
}
?>