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

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.

Related

PHP: MSSQL Query for multiple fields on one page

I am new to PHP, and have a web form, that I am using PHP to get data from the database. What I have currently done, as I havent been able to find out another solution to do so (despite my searching - probably dont know the correct terms to look for), is individually executing a SQL Query for each input field on my form.
As below:
<div class="search-line">
<div class="search-option">
<label>Asset Tag:<i title=""></i></label>
<?php
$asset_tag_sql = "SELECT HardwareAsset.HardwareAssetAssetTag FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";
$asset_tag = sqlsrv_query($database_connection, $asset_tag_sql);
?>
<input type="text" id="AssetTag" disabled value="<?php while ($asset_tag_option = sqlsrv_fetch_object($asset_tag)){echo $asset_tag_option->HardwareAssetAssetTag;} ?>" />
</div>
<div class="search-option">
<label>Serial Number:<i title=""></i></label>
<?php
$serial_number_sql = "SELECT HardwareAsset.HardwareAssetSerialNumber FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";
$serial_number = sqlsrv_query($database_connection, $serial_number_sql);
?>
<input type="text" id="SerialNumber" disabled value="<?php while ($serial_number_option = sqlsrv_fetch_object($serial_number)){echo $serial_number_option->HardwareAssetSerialNumber;} ?>" />
</div>
</div>
Is there anyway to have one PHP piece of code to do one SQL query and then use that to fetch and echo the value for both input fields, as opposed to the two above?
Try it like this?
<?php
$asset_sql = "SELECT HardwareAsset.HardwareAssetAssetTag,HardwareAsset.HardwareAssetSerialNumber FROM HardwareAsset WHERE HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'"
$asset_result = sqlsrv_query($database_connection, $asset_sql);
$asset_data = sqlsrv_fetch_object($asset_result);
?>
<div class="search-line">
<div class="search-option">
<label>Asset Tag:<i title=""></i></label>
<input type="text" id="AssetTag" disabled value="<?php echo $asset_data->HardwareAssetAssetTag; ?>" />
</div>
<div class="search-option">
<label>Serial Number:<i title=""></i></label>
<input type="text" id="SerialNumber" disabled value="<?php echo $asset_data->HardwareAssetSerialNumber; ?>" />
</div>
</div>
Why not just select two fields from the initial query like this:
$serial_number_sql = "SELECT HardwareAsset.HardwareAssetSerialNumber,
HardwareAsset.HardwareAssetAssetTag FROM HardwareAsset WHERE
HardwareAssetID = '".$_SESSION["HardwareAssetID"]."'";

How to pass variable from POST

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! :)

PHP MySQL - Undefined Index in Edit Data

I make file details.php that show list of data from MySQL, and I make edit.php for it.
When I click edit.php it's automatically go to edit.php?id=detailsid (it works) but when I click submit on edit data, it's nothing changed and error.
This is my Edit.php
<form method="post" action="editdata.php">
<?php
include 'config.php';
$id=$_GET['id'];
$sqlTampil="select * from data_korban Where kasus_id=$id";
$qryTampil=mysql_query($sqlTampil);
$dataTampil=mysql_fetch_array($qryTampil);
$data=mysql_fetch_array($qryTampil);
?>
This is some of my HTML form
<input type="DATE" name="tanggal" size="20" value="<?php echo $dataTampil['tanggal']; ?>">
<input type="text" name="namakorban" size="40" value="<?php echo $dataTampil['namakorban']; ?>">
<input type="text" name="umurkorban" size="5" value="<?php echo $dataTampil['umurkorban']; ?>">
<input type="submit" name="submit" value="SUBMIT">
When I click Submit it's automatically call editdata.php but there is no change on my MySQL row ..
This is my editdata.php
<?php
include "config.php";
$id=$_GET['id'];
$tanggal = $_POST['tanggal'];
$namakorban = $_POST['namakorban'];
$umurkorban = $_POST['umurkorban'];
$update = "UPDATE data_korban SET tanggal='$tanggal', namakorban='$namakorban', umurkorban='$umurkorban' WHERE kasus_id = '$id'";
$hasil = mysql_query($update);
if ($hasil)
echo "<center>Update Success<center>";
else
echo "<center><h3><a href=pencarian.php>Back Tampil Data</a></h3></center>";
?>
There is something in my Error_Log
PHP Notice: Undefined index: id in /home/lombokdi/public_html/dbanak/editdata.php on line 4 ------ it's $id=$_GET['id'];
I have change to $_POST['id']; it's still error.
Your form does not seem to include the id named field.
And you are trying to read the non existing field from the request.
Request is formed to send data over post method but you tried to read id parameter using get method. As the value for id is not found, a null is used in where clause and that affected no rows updated.
$id=$_GET['id'];
$tanggal = $_POST['tanggal'];
$namakorban = $_POST['namakorban'];
$umurkorban = $_POST['umurkorban'];
the value for ID is $id=$_GET['id']; ... id come from detail.php?id=24 (example) go to edit.php?id=24 .. If I'm wrong, how to set the ID ??
In edit.php add id named element to the form with value read from the request. And on submitting the form, id goes to editdata.php page.
<input type="DATE" name="tanggal" size="20" value="<?php echo $dataTampil['tanggal']; ?>">
<input type="hidden" name="id" value="<?php echo $id['id']; ?>">
<input type="text" name="namakorban" size="40" value="<?php echo $dataTampil['namakorban']; ?>">
<input type="text" name="umurkorban" size="5" value="<?php echo $dataTampil['umurkorban']; ?>">
And in editdata.php:
Change:
$id=$_GET['id'];
To:
$id=$_POST['id'];
It's because you don't have the filed "id" if you switch to editdata.php
add: <input type="hidden" name="id" value="<?php $_GET['id']; ?>">
to your form in Edit.php
and replace
$id=$_GET['id']; with $id= $_POST['id']; in editdata.php.
Try like this
$id=$_GET['id'];
$sql=mysqli_query($con,"Update client set nama='$nama',instansi='$instansi',telepon='$telepon',email='$email' where id = '".$_GET['id']."'");
if($sql)
{
$msg="Your Client updated Successfully";
header('location:manage-client.php');
}
for after body add this query
$sql=mysqli_query($con,"select * from client where id = '".$_GET['id']."'");
while($data=mysqli_fetch_array($sql))
You are using $_GET to get the id. It is best do var_dump($_REQUEST);

populating text fields from the sql using dropdown list Jquery

Hello there first time doing this, Basically I am rather confused on how to Re-populate text boxes from the database.
My current issue is that basically I have two tables in my database 'USER' and 'STATISTICS'.
Currently what is working is that my code is looking up the values of 'User_ID' in the 'USER' table and populating the values in the drop down list.
What I want from there is for the text fields to populate corresponding to those values from the database looking up the 'User_ID' E.G 'goal_scored' , 'assist', 'clean_sheets' and etc.
I am pretty baffled I have looked up on various different questions but cannot find what im looking for.
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("f_club",$link);
$sql = "SELECT * FROM user ";
$aResult = mysql_query($sql);
?>
<html>
<body>
<title>forms</title>
<link rel="stylesheet" type="text/css" href="css/global.css" />
</head>
<body>
<div id="container">
<form action="update.php" method="post">
<h1>Enter User Details</h1>
<h2>
<p> <label for="User_ID"> User ID: </label> <select id="User_ID" id="User_ID" name="User_ID" >
<br> <option value="">Select</option></br>
<?php
$sid1 = $_REQUEST['User_ID'];
while($rows=mysql_fetch_array($aResult,MYSQL_ASSOC))
{
$User_ID = $rows['User_ID'];
if($sid1 == $id)
{
$chkselect = 'selected';
}
else
{
$chkselect ='';
}
?>
<option value="<?php echo $id;?>"<?php echo $chkselect;?>>
<?php echo $User_ID;?></option>
<?php }
?>
I had to put this in because everytime I have text field under the User_ID it goes next to it and cuts it off :S
<p><label for="null"> null: </label><input type="text" name="null" /></p>
<p><label for="goal_scored">Goal Scored: </label><input type="text" name="Goal_Scored" /></p>
<p><label for="assist">assist: </label><input type="text" name="assist" /></p>
<p><label for="clean_sheets">clean sheets: </label><input type="text" name="clean_sheets" /></p>
<p><label for="yellow_card">yellow card: </label><input type="text" name="yellow_card" /></p>
<p><label for="red_card">red card: </label><input type="text" name="red_card" /></p>
<p><input type="submit" name="submit" value="Update" /></p></h2>
</form>
</div>
</body>
</html>
If anyone can help with understanding how to get to the next stage would be much appreciated thanks x
Rather than spending time on something complicated like AJAX, I'd recommend going the simple route of pages with queries, such as user.php?id=1.
Craft a user.php file (like yours) and if id is set (if isset($_GET['id'])) select that user from the database (after having sanitised your input, of course) with select * from users where id = $id (I of course assume you have an id for each user).
You can still have the <select>, but remember to close it with </select>. You might end up with something like this:
<form method="get">
<label for="user">Select user:</label>
<select name="id" id="user">
<option value="1">User 1</option>
...
</select>
<submit name="submit" value="Select user" />
</form>
This will send ?id=<id> to the current page and you can then fill in your form. If you further want to edit that data, create a new form with the data filled in with code like <input type="text" name="goal_scored" value="<?php echo $result['goal_scored']; ?>" /> then make sure the method="post" and listen on isset($_POST['submit']) and update your database.
An example:
<?php
// init
// Use mysqli_ instead, mysql_ is deprecated
$result = mysqli_query($link, "SELECT id, name FROM users");
// Create our select
while ( $row = mysqli_fetch_array($link, $result, MYSQL_ASSOC) ) {?>
<option value="<?php echo $result['id']; ?>"><?php echo $result['name'] ?></option>
<?php}
// More code ommitted
if (isset($_GET['id'])) {
$id = sanitise($_GET['id']); // I recommend creating a function for this,
// but if only you are going to use it, maybe
// don't bother.
$result = mysqli_query($link, "SELECT * FROM users WHERE id = $id");
// now create our form.
if (isset($_POST['submit'])) {
// data to be updated
$data = sanitise($_POST['data']);
// ...
mysqli_query($link, "UPDATE users SET data = $data, ... WHERE id = $id");
// To avoid the 'refresh to send data thing', you might want to do a
// location header trick
header('Location: user.php?id='.$id);
}
}
Remember, this is just an example of the idea I'm talking about, lots of code have been omitted. I don't usually like writing actually HTML outside <?php ?> tags, but it can work, I guess. Especially for smaller things.

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