How to pass variable from POST - php

I want to pass two variable from POST, one is the text I write and the other one is the result of a query with I already have.But for some reason I am not getting the variable values. Can you help me?
This is my first page:
<form method="post" action="EliminarGrupos.php">
<label for="nomegrupo"><b>Editar nome do grupo 1 :</label</b><br>
<?php
while ($row = mysqli_fetch_array($result66)){
$result = $row['titulogrupo'];
$_POST['nomegrupo'] = $result; //saving first variable
?>
<input type="text" placeholder="<?php echo $result?>" name="grupo1" id="velhas"></td> //saving second variable
<?php } ?>
<input type="submit" name="submit_x" data-inline="true" value="Submeter">
</form>
This is my second page where I want the variables to appear
$variable = $_POST['nomegrupo'];
$variable2 = $_POST['grupo1'];

The placeholder attribute is for display purposes only. You need to set the value attribute to have it sent to the server.
To send a second value, just use a second <input> element. If you don't want it visible, set type attribute to hidden.
In addition, you are expecting an associative array from mysqli_fetch_array() which is not going to happen. Your HTML had a number of errors in it, which I think I've fixed below. You always need to escape output with htmlspecialchars(). You should separate your HTML and your PHP as much as possible.
<?php
$row = mysqli_fetch_assoc($result66);
$titulogrupo = htmlspecialchars($row["titulogrupo"]);
?>
<form method="post" action="EliminarGrupos.php">
<label for="velhas"><b>Editar nome do grupo 1 :</b></label><br/>
<input type="text" placeholder="" name="grupo1" id="velhas"/>
<input type="hidden" name="nomegrupo" value="<?=$titulogrupo?>"/>
<button type="submit" name="submit_x" data-inline="true">Submeter</button>
</form>

You get the $_POST data from the form submission, specfically from the name attributes. This is what gives the $_POST its information, which it retrieves from value, not placeholder, as you have it now.
<input name="grupo1" value="one"> will make $_POST['grupo1'] equal to one.
You also shouldn't set the $_POST variable on page 1 as you are currently doing, and should make the unchanged variable from the database call a hidden field:
Page 1:
<form method="post" action="EliminarGrupos.php">
<label for="nomegrupo"><b>Editar nome do grupo 1 :</label>
<?php
while ($row = mysqli_fetch_array($result66)){
$result = $row['titulogrupo'];
?>
<input type="text" value="<?php echo $result; ?>" name="grupo1" id="grupo1">
<input type="hidden" value="<?php echo $result; ?>" name="titlogrupo" id="titlogrupo">
<?php } ?>
<input type="submit" name="submit_x" data-inline="true" value="Submeter">
</form>
Page 2:
$variable1 = $_POST['titulogrupo']; // $row['titulogrupo']
$variable2 = $_POST['grupo1']; // Form input
Hope this helps! :)

Related

i want to be able to echo all the element in an array?

I pretty newbie to php and javascript but more i am curious about PHP. I want to add elements into a empty array every time i add a new element trough a input form, and after that i want those elements to be displayed in to the browser .The code i use is this
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
if (isset($_POST['submit'])) {
$_SESSION['names']=array();
$names=$_SESSION['names'];
$name=$_POST['name'];
array_push($names,$name);
for($i=0;$i<count($names);$i++){
echo $names[$i];
}
};
How could i achieve to display every element inside the array that i add trough the input field in php?
You overwrite the value every time because you wipe out the array on every page load: $_SESSION['names']=array();. Instead check to see if that session variable exists (and is an array) first and, if it doesn't, then create it. Otherwise just append to that array.
<form action="index.php" method="POST">
<input type="text" name="name" placeholder="name"><br><br>
<input type="submit" name="submit" value="enter"><br><br>
</form>
<?php
session_start();
if (isset($_POST['submit'])) {
if (!isset($_SESSION['names']) || !is_array($_SESSION['names'])) {
$_SESSION['names'] = array();
}
$name = $_POST['name'];
$_SESSION['names'][] = $name;
$num_names = count($_SESSION['names']);
for($i=0;$i<$num_names;$i++){
echo $_SESSION['names'][$i];
}
};

How can i get multiple value from POST variable using same name

When user inputs text in 'ctext' field and press accept, I want to fill the value=" " field with user input, i achieved this but it fills all the value fields of same name in the page, how can i achieve it for different value of different ctext input? Anyone please give me solution with example, Many thanks
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
$i=0;
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here" value="<?php $ctext = false; if(isset($_POST['ctext'])){ $ctext = $_POST['ctext']; } echo $ctext[$i]; ?>"></input>
<input type="hidden" name="id" value="<?php $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
$i++;
endwhile;
endif;
endif;
?>
I hope I understand what you want. You want to access the ctext for each individual $pen when printing the corresponding form.
You just need to name your <input> with a unique name and then access that value when printing. A possible solution is this:
<input type="text" name="ctext[<?php echo $pen['id']; ?>]" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } echo $ctext; ?>"></input>
What does it do?
name="ctext[<?php echo $pen['id']; ?>]" ensures a unique name for each $pen. For a $pen with id 1 this will result in name="ctext[1]".
if(isset($_POST['ctext'][$pen['id']])){ $ctext = $_POST['ctext'][$pen['id']]; } uses $pen['id'] to look up the corresponding value in $_POST['ctext'].
By the way, when outputting user input you should always escape it, e.g. with htmlspecialchars. This will look like this: echo htmlspecialchars($ctext); That way malicious input like "><script>alert('Hello!')</script> won't execute the javascript.
Update: as requested a solution using session to store data:
<?php
$connect = mysqli_connect('localhost', 'root', 'root123', 'font');
$query = 'SELECT * FROM pens ORDER by id ASC';
$result = mysqli_query($connect, $query);
if($result):
if(mysqli_num_rows($result)>0):
session_start();
if (isset($_POST['ctext'])) {
$_SESSION['ctext'][$_POST['id']] = $_POST['ctext'];
}
while( $pen = mysqli_fetch_assoc($result) ):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>?action=add&id=<?php echo $pen['id']; ?>">
<div class="name pen-<?php echo $pen['id']; ?>">
<input type="text" name="ctext" class="form-control" placeholder="Type your text here" value="<?php $ctext = ''; if(isset($_SESSION['ctext'][$pen['id']])){ $ctext = $_SESSION['ctext'][$pen['id']]; } echo htmlspecialchars($ctext); ?>"></input>
<input type="hidden" name="id" value="<?php echo $pen['id']?>"></input>
</div>
<div class="btn-custom">
<input type="submit" name="add_to_cart" class="btn btn-block" value="Accept"></input>
</div>
</form>
<?php
endwhile;
endif;
endif;
Note: I removed the now unnecessary counter $i. The session handling is mainly done before the while loop (start a session and store POST data). During output the values from the session are used. The name of the input is not an array anymore.
Change name of an input to an array.like this . When you submit the form you will get these values as an array. Give it a try
<input type="text" name="ctext[]" class="form-control" placeholder="Type your text here"></input>
I guess your code is misleading you, your form is in while loop so once any of the ctext input is filled your variable $_POST['ctext'] is set on server side and according to your code it sets all the value of ctext once accept is pressed.
You can have different names as a solution or an array indexing in input field name=“ctext[]” to avoid this.

how to set array data for the textbox in php

**I have home.php file and superLec.php file. user can enter studentUniversityId and click on the submit button. particular data i want to show studentName textbox and lecturerName textbox. I want to pass data as a array. How to set array data for textbox value.Please any one help me. **.
home.php
<?php
session_start();
include_once 'include/class.supervisor.php';
$supervisor = new Supervisor();
if (isset($_POST['submit'])) {
extract($_POST);
$autofill = $supervisor->check_auto_fill($studentUniversityId);
/* if ($autofill) {
// Registration Success
header("location:homeLecturer.php");
} else {
// Registration Failed
echo 'Wrong username or password';
}*/
}
?>
<form action="" method="post">
<label for="studentID">Student ID</label>
<input type="text" name="studentUniversityId" id="studentID" placeholder="studentID">
<!--input type="submit" id="autoFill" name="autoFill" value="Auto Fill"><br><br>
<input class="btn" type="submit" name="submit" value="Auto Fill"-->
<label for="studentName">Student Name</label>
<input type="text" id="studentName" name="studentName" value = "<?php echo print_r($autofill);?>" placeholder="Student Name"><br><br>
<label for="lecturerName">Supervisor Name</label>
<input type="text" id="lecturerName" name="lecturerName" value = "<?php echo ($lecturerName) ;?>" placeholder="Supervisor Name"><br><br>
<input type="submit" id="submit" name="submit" value="submit">
</form>
**This is my php file. I want pass array values for the home.php file. can any one help me pls. **
superLe.php
public function check_auto_fill($studentUniversityId){
$query = "SELECT supervisor.lecturerName, supervisee.studentName, supervisee.studentUniversityId FROM supervisee, supervisor WHERE supervisee.lecturerId = supervisor.lecturerId AND supervisee.studentUniversityId = '$studentUniversityId' ";
$result = $this->db->query($query) or die($this->db->error);
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
$arr = array("lecturerName", "studentName", "studentName");
return $arr;
}
You have to use JQuery function to set value of form elements.
Post studentUniversityId via ajax get data in response and populate the data to form element.
To create a response with array, you need to extract the fetched data from query and put them into the output array.
I suggest you to use a key/value array.
public function check_auto_fill($studentUniversityId){
$query = "SELECT supervisor.lecturerName, supervisee.studentName, supervisee.studentUniversityId FROM supervisee, supervisor WHERE supervisee.lecturerId = supervisor.lecturerId AND supervisee.studentUniversityId = '$studentUniversityId' ";
$result = $this->db->query($query) or die($this->db->error);
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
$arr = array(
'lecturerName' => $supervisor_data[0]['lecturerName'], //the "0" index depends of the query structure, but as I can see, this is a right way
'studentName' => $supervisor_data[0]['studentName'],
)
//$arr = array("lecturerName", "studentName", "studentName");
return $arr;
}
After that in your home.php you can simple extract the data from array and put the elements in the right fields as exampled:
<label for="studentName">Student Name</label>
<input type="text" id="studentName" name="studentName" value = "<?php echo $autofill['studentName']; ?>" placeholder="Student Name"><br><br>
<label for="lecturerName">Supervisor Name</label>
<input type="text" id="lecturerName" name="lecturerName" value = "<?php echo $autofill['lecturerName']; ?>" placeholder="Supervisor Name"><br><br>
Hope it help you.
Marco
From what I see and understand (please excuse if I don't), you want to populate the text fields studentName and lecturerName with their respective values. To me, you code looks correct except one thing. You need to drop the line
$arr = array("lecturerName", "studentName", "studentName");
from superLe.php. The line
$supervisor_data = $result->fetch_array(MYSQLI_ASSOC);
already returns an associative array, which you can use in the variable $autofill in file home.php as $autofill['studentName'] or $autofill['lecturerName'].

Returning only the last value of query

This is my second code but the problem is I have 3 queries. So it only returns the last product_id when i Click update it always return product_id=3, but i want update the product_id=2
<form action="update_qty.php" method="POST">
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
<?php } ?>
</form>
Your problem is that the PHP is server side and you need something client side to read the value of the text box. You would need a page refresh to pass the text field value to the server so it could write it to the url in the anchor tag. Which is what the form submit would do, but as it would have submitted the value already the anchor tag would be pointless
To do it without a page refresh use Javascript. It would be easy to do with jQuery. You could add an event that writes whatever is entered in the text box the the anchor tags href as it is typed.
I'll do something more like this.
One form per product.In your case when you submit the form the qty value will always be the las found.
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<form action="update_qty.php" method="POST">
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price">
<input type="hidden" value="<?=$getorder['product_id']?>" name="product">
<input type="text" value="<?=$getorder['qty']?>" name="qty" size="1" style="text-align:center">
<input type="submit" value="update" name="update">
</form>
<?php } ?>
You can add more information like this
update
You can not get all values as like that because input name overwrite in every loop iteration.
For multiple values you can try in two ways like:
<?php
while($getorder = mysqli_fetch_array($order)){
$newArr[] = $getorder['price']."~".$getorder['product_id']."~". $ getorder['qty'];
} //while end
?>
<input type="hidden" name="allinputs" value="<?=$newArr?>">
Input field outside the loop.
In php explode array value with ~ and get the all values.
Other solution is that
Your input field name must be change like:
<?php while($getorder = mysqli_fetch_array($order)){ ?>
<input type="hidden" value="<?=$getorder['price']?>" name="actual_price_<?=$getorder['product_id']?>">
<?php } ?>
Change field name in every iteration.
In current scenario either you need three different buttons or the best solution to use AJAX request .
update
On update_qty.php u can use like this
<?php echo $_GET['product_id'];?>

How to get ID from another file in php?

I'm going to make edit menu in my web. so I direct the page from product into edit page. What I'm confused is how to get the productID from product's page to use in edit page?
Here is my code in product
<?php $query= "SELECT * FROM game";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<div class="gameBox">
<div style="margin:5px;">
<?php echo "<image src=\"images/".$data['gameId'].".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <?php echo $data['gameName'];?></div>
<div class="myLabel">Developer</div><div>: <?php echo $data['gameDeveloper']; ?></div>
<div class="myLabel">Price</div><div>: $ <?php echo $data['gamePrice']; ?></div>
<br />
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
<input type="button" value="Delete"/>
</div>
</div>
<?php } ?>
and it's my code in edit page
<?php include("connect.php");
$id[0] = $_REQUEST['id'];
$query = "SELECT * FROM game WHERE gameId=".$id."";
$rs = mysql_query($query);
while($data = mysql_fetch_array($rs)) { ?>
<form action="doUpdate.php" method="post">
<?php echo "<image src=\"images/".$id.".png\" alt=\"gameImage\" </image>"?>
<div class="cleaner"></div>
<div class="myLabel">Name</div><div>: <input type="text" value="<?php echo $data['gameName'];?>" id="gameName" name="gameName"/></div>
<div class="myLabel">Developer</div><div>: <input type="text" value="<?php echo $data['gameDeveloper'];?>" id="gameDeveloper" name="gameDeveloper"/></div>
<div class="myLabel">Price</div><div>: <input type="text" value="<?php echo $data['gamePrice'];?>" id="gamePrice" name="gamePrice"/></div>
<br/>
<div id="txtError">
<!--error message here-->
</div>
<input type="submit" value="Submit"/>
<input type="button" value="Cancel"/></span>
<?php } ?>
When I try to access edit page, there's an error it said
"Undefined index:$id[0] = $_REQUEST['id'];"
in edit page.
Could anyone help me?
It looks like you're confusing two methods of passing data between pages, forms and query strings in <a href...>s.
Forms:
Data is in <input>-type elements (or friends) and inside a <form...> tag.
For example
<form action="handler.php">
<input type="text" name="var1" />
<input type="text" name="var2" />
<input type="submit">
</form>
Usually passed via POST and accessed in PHP via $_POST.
For example, the values in the text boxes referenced above would be accessed with something like:
<?php
echo $_POST['var1']; // First text box
echo $_POST['var2']; // Second text box
Links:
Passed as query strings in <a href...>, for example:
Click Me
Usually passed via GET and accessed in PHP via $_GET.
For example, the values in the query string provided above would be accessed with something like
<?php
echo $_GET['var1']; // "foo"
echo $_GET['var2']; // "bar"
So in this case it looks like you're hyperlinking an input button -- which is not the usual way to do things, but you would fix it by changing this:
<a href="edit.php" <?php $id=$data['gameId'];?>><input type="button" value="Edit"/></a>
To, this
<input type="button" value="Edit"/>
And then reference the variable in edit.php as $_GET['id'].
But since you know it's going to be an integer and nothing else, something like:
$id = (int)$_GET['id'];
Is good enough sanitation (at least for that variable).
Lastly, I notice you assign a variable to $id[0] but then reference $id. Assigning a variable to $id[0] is not the same as assigning it to $id, as $id is an array in the former and an integer in the latter. It seems to me that you can just drop the [0] w.r.t. $id in your edit.php
You can pass through the query string
<a href="edit.php?<?php $id=$data['gameId'];?>>
In this case your PHP code will get change to
$id[0] = $_SERVER['QUERY_STRING'];
Add the id as a parameter to your edit url:
<input type="button" value="Edit"/>
also at the top of your edit.php:
$id = $_REQUEST['id'];

Categories