set php get set variable with hyperlink - php

I have two .php pages, one that returns the contents of a table including an id for each entry along with an html text input and another that retrieves the details and allows me to update the record.
I'd like to store the id of the entry by clicking on the list item using a href rather than having to text input the id and submit.
choose.php
echo "<ul>";
while ($row=mysql_fetch_array($result)) {
$reference=$row[reference];
$name=$row[name];
echo "<li>$reference, $name</li>";
}
echo "</ul>";
session_start();
$_SESSION['regName'] = $reference;
mysql_close($link);
?>
<form method="get" action="update.php">
<input type="text" name="regName" value="">
<input type="submit">
</form>
update.php
session_start();
$reference = $_GET['regName'];
echo "Your selection id is: ".$reference.".";
$query="SELECT * FROM firsttable WHERE reference='$reference'";
$result=mysql_query($query) or die("Query to get data from firsttable failed with this error: ".mysql_error());
$row=mysql_fetch_array($result);
$name=$row[name];
echo "<form method=\"POST\" action=\"updated.php\">";
echo "<p>";
echo "<label for=\"name\">Name: </label><input type=\"text\" id=\"name\" name=\"name\" size=\"30\" value=\"$name\"/>";
echo "<p><input type=\"submit\"></p>";
echo "</form>";
I apologise if this seems very obvious, I've only started to learn php as of today and it's much more complicated than anything I've done up until now.
Thanks
James

Answering your question, you just need to use HREF parameter of A tag. This will make an active link, which will contain a reference you need:
echo '<ul>';
while ($row = mysql_fetch_array($result)) {
$reference = $row[reference];
$name = $row[name];
echo '<li><a href=/update.php?regName='.$reference.'>'.$name.'</a></li>';
}
echo '</ul>';
?>
Read here for more details about passing data via GET\POST: https://www.w3schools.com/tags/ref_httpmethods.asp
And as you were told above, please consider rewiring the code as it is totally unsafe and must not be used anyhow besides some very basic concept proof. And only inside intranet or local machine.
Good luck!

Related

Retrieve DIV-content inside a Form

I have been searching for help from various forums and similar posts, but without any progress.
I have three pages, one that lets me insert information about projects into my database, a second that show the images and names of every project in the database, and a third page which I want to have a function that shows the image and name of the selected project in the second page.
Code on the second page(dashboardadmin.php):
<?php
ini_set('display_errors',1);
error_reporting(E_ALL);
$conn = mysqli_connect("localhost","root","","wildfire");
if(mysqli_connect_errno())
{
echo mysqli_connect_error();
}
$sql= "SELECT pid, project_name, image, image_type FROM project";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo "<form action='omprojekt.php' method='post'>
<div id='comp' name='comp'>
<img src=pic.php?pid=".$row['pid']." width=100xp height=100xp/>"." ".$row['project_name']."
</div>
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
else {
echo "0 results";
}
mysqli_close($conn);
?>
Code on the third page (omprojekt.php):
<?php
/* Tried both of the $val variables but of course only one at a time. This is only to show you what I have tried. */
$val = isset($_POST['comp']) ? $_POST['comp'] : '';
$val = $_POST['comp'];
if(isset($_POST['submit'])){
echo "$val";
}
?>
In the last code you can see that I have two $val variables, but I have only used one of them at a time in my codes. The purpose of showing both of them here is to show you that I have tried both of them.
What I want to do is to make the third page show the image and name of the selected project in the second page. As you see, I have tried to retrieve the content from the DIV using the same "name". The problem is that the third page(omprojekt.php) doesn't show any content at all, and not even any errors.
You're expecting the div to submit like an input, but it won't, because it's not an input. So put it in an input.
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
// Don't use and id attribute because you're in a loop and you might have multiple id's with the same value.
echo "<form action='omprojekt.php' method='post'>
<div>
<img src=pic.php?pid=".$row['pid']." width=100xp height=100xp/>"." ".$row['project_name']."
</div>
<input type='hidden' name='pid' value='".$row['pid']."'>
<input type='hidden' name='project_name' value='".$row['project_name']."'>
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
Then on the next page,
$val = (isset($_POST['pid']) && isset($_POST['project_name'])) ?
"<img src=pic.php?pid={$_POST['pid']} width=100xp height=100xp/> {$_POST['project_name']}" : '';
For the sake of completeness, there are a few other things wrong with your code.
1) The width and height attributes on the iamge should have quotes, and do not accept "px", they are just numbers. If you want to use "px" you should use style instead. <img src='' style='width:20px; height:20px;' />
2) You should be escaping user input before running it through your query.
Data will only be sent from a <form> to the action script if it exists in an <input...> HTML tag. You cannot pick data out of randon <DIV> tags etc.
So you could do this by using a hidden input field like this ( this is only one way )
if ($result->num_rows > 0) {
while($row = $result->fetch_array()) {
echo "<form action='omprojekt.php' method='post'>
<div>
<img src=pic.php?pid=".$row['pid'] .
" style="width:100px;height:100px" /> " .
$row['project_name']."
</div>
<input type='hidden' name='comp' value='" . $row['pid'] . "' />
<input type='submit' name='submit' value='Choose' />
</form>";
}
}
Now when you get to omprojekt.php the $_POST['comp'] variable will exist.
You can have as many hidden input fields as you like so if you want to pass the project_name as well just add another hidden field.

Saving a specific row using PHP and a search option

I have the following program, it searchs for the text placed in a previous php file, and it displays the results, by adding a radiobox to check the item that will be purchased. I am not able to make the page save the item that was checked from the items found into a new table, I don't know how to do that, because the items found are placed as fetched items, therefore I don't know how to select one to save the entire row selected. Please help!.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Search option</title>
</head>
<body>
<?php
echo "<form action='slips.php' method='post'>";
if(isset($_POST['name_prod2'])){
$word=$_POST['name_prod2'];
$conn = oci_pconnect('dbname', 'password', 'localhost/XE');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['Error'], ENT_QUOTES), E_USER_ERROR);
}
$stid = oci_parse($conn, "SELECT * FROM product WHERE LOWER(name) LIKE '%" . $word . "%'");
oci_execute($stid);
echo "<table width='950' table border='1' align='center'>\n";
echo "<tr>\n";
echo "<th width='50'> <div align='center'>buy</div></th>";
echo "<th width='110'> <div align='center'>Product ID</div></th>";
echo "<th width='190'> <div align='center'>Product name</div></th>";
echo "<th width='250'> <div align='center'>Description</div></th>";
echo "<th width='100'> <div align='center'>in Store</div></th>";
echo "<th width='100'> <div align='center'>price</div></th>";
echo "<th width='190'> <div align='center'>Quantity to purchase</div></th>";
echo "</tr>\n";
while ($product = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
//echo "<td><div style='text-align:center'><label><input type='radio' name='radio1' value='valor'></label></td></div>";
echo sprintf('<td><div style="text-align:center"><label><input type="radio" name="product" value="%s"></label></td></div>', $product['product_id']);
foreach ($product as $aspect) {
echo '<td><div style="text-align:center">'.($aspect !== null ? htmlentities($aspect, ENT_QUOTES) : '')."</td></div>\n";
}
echo '<td width="50"><div align="center"><input name="quantity" type="text" size="27" maxlength="50" placeholder="Enter quantity"></div></td>';
}
echo "</table>\n";
}
echo "<div style='text-align:center'><input type='submit' value='Comprar'></div>";
echo"</form>";
?>
</body>
</html>
These are two of the Javascripts that I have tried so far to complete this, but they fail to tell me when one has been selected, I don't know if I can try adding this code to a button, and when I click it, it will tell me which row from the radio box was checked, and then save it:
<script type="text/javascript" src="js/jquery.js"> </script>
<script type="text/javascript">
var user_cat = $("input[radio1='user_cat']:checked").val();
if (!$("input[radio1='radio1']").is(':checked')) {
alert('Nothing is checked!');
}
else {
alert('One of the radio buttons is checked!');
}
$(document).ready(function() {
$('#btnStatus').click(function(){
var isChecked = $('#rdSelect').prop('checked');
alert(isChecked);
});
});
</script>
When is use this line echo "<td><div style='text-align:center'><label><input type='radio' name='radio1' value='valor'></label></td></div>"; it works and displays this results
But when I use this line echo sprintf('<td><div style="text-align:center"><label><input type="radio" name="product" value="%d"></label></td></div>', $product['product_id']);it doesn't work and displays this results
OK, picking up the information from the comments to the question and doing a little guess work I will try to point you into the right direction. It is not possible to give a read-to-use answer, since still there are things not clear, but let's have a try to get started...
I see you have an html form which includes a table. That table has a header row and dynamic generated rows holding some product information each. You want to have a radio button in front of each row to allow to select a row. And you want a text input field at the end of each row which allows to enter a quantity. Then you want to post that information to the server to be able to process it.
I will stick with the "conservative" html approach and not introduce scripting here. Reason is that for the purpose described before that is not required. So let's keep things simple. Obviously nothing speaks against making things more complicated later on :-)
Your radio buttons have to be changed, they currently make no sense. You have to give the an individual value, so that you can identify which row has been selected later on. Currently you give them all the same static value 'value'. So change the loop that iterates over the products to something like:
while ($product = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
echo "<tr>\n";
echo sprintf('<td><div style="text-align:center"><label><input type="radio" name="product" value="%s"></label></td></div>'."\n", $product['product_id']);
foreach ($row as $aspect) {
echo '<td><div style="text-align:center">'
.($aspect !== null ? htmlentities($aspect, ENT_QUOTES) : '')
."</td></div>\n";
}
echo '<td width="50"><div align="center"><input name="quantity" type="text" size="27" maxlength="50" placeholder="Enter quantity"></div></td>'."\n";
}
Note: I took the liberty to change the chosen names to be more logical to product, aspect and quantity...
That is all... Now when you press the submit button the form should get posted to the target you specified: slips.php which is probably a script of yours... Inside that script you now can access the data like that:
$product = $_POST['product'];
$quantity = $_POST['quantity'];
There are more issue worth discussing and modifying, but as said: let's keep things simple and take one step after the other!
ChangeLog:
changed the literal key of the array element used as a value inside the radio button definition from id to procduct_id according to one of the comments below
Your radiobox need to stay inside the form.

onclick action not working as intended with radio buttons

For the last 4 hours I've been struggling to get something to work. I checked SO and other sources but couldn't find anything related to the subject. Here is the code:
<?php
$email=$_SESSION['email'];
$query1="SELECT * FROM oferte WHERE email='$email'";
$rez2=mysql_query($query1) or die (mysql_error());
if (mysql_num_rows($rez2)>0)
{
while ($oferta = mysql_fetch_assoc($rez2))
{
$id=$oferta['id_oferta'];
echo "<input type='radio' name='selectie' value='$id' id='$id'> <a href='oferta.php?id={$oferta['id_oferta']}'>{$oferta['denumire_locatie']}</a>";
echo "</br>";
}
echo "</br>";
//echo "<input type=\"button\" id=\"cauta\" value=\"Vizualizeaza\" onclick=\"window.location.href='oferta.php?id={$oferta['id_oferta']}'\" />";
//echo " <input type=\"button\" id=\"cauta\"value=\"Modifica\" onclick=\"window.location.href='modifica.php?id={$oferta['id_oferta']}'\" />";
echo " <input type=\"button\" id=\"sterge\" value=\"Sterge\" onclick=\"window.location.href='delete.php?id=$id'\" />";
echo "</form>";
echo "</div>";
}
else
{
}
?>
The while drags all of the user's entries from the database and creates a radio button for each one of them with the value and id (because I don't really know which one is needed) equal to the entry's id from the db. I echoed that out and the id is displayed as it should so no problems there.
The delete script works ok as well so I won't attach it unless you tell me to. All good, no errors, until I try to delete an entry. Whatever I choose from the list of entries, it will always delete the last one. Note that I have two other inputs echoed out, those will be the "view" and "modify" buttons for the entry.
I really hope this is not JavaScript related because I have no clue of JS. I think this will be of major help to others having this problem. Please let me know if I need to edit my question before downrating. Thanks!
After edit:
This is the delete script, which as I said earlier works fine.
<?php
if (isset($_GET['id']))
{
$id = $_GET['id'];
echo $id;
require_once('mysql_connect.php');
$query = "DELETE FROM oferte Where id_oferta = '$id'";
mysql_query($query) or die(mysql_error());
//header('Location: oferte.php');
}
else
{
//header('Location: oferte.php');
}
?>
The session is started as well, like this:
<?php
session_start();
?>
The reason the last $id is deleted is because this line is outside/after the while loop:
echo " <input type=\"button\" id=\"sterge\" value=\"Sterge\" onclick=\"window.location.href='delete.php?id=$id'\" />";
You want to move this line inside the loop so that you have a button that executes delete for each radio button.
Update:
To have links to delete and
echo "<input type='radio' name='selectie' value='$id' id='$id'> ";
echo "<a href='oferta.php?id={$oferta['id_oferta']}'>{$oferta['denumire_locatie']}</a> ";
echo "<a href='delete.php?id=$id'>delete</a>";
Also I do not think the radio button is needed here at all since you are not really doing anything with it. You could simply echo out the value of your choice and have these links as follows:
echo $oferta['denumire_locatie'] . ' '; // replace $oferta['denumire_locatie'] with something of your choice
echo "<a href='oferta.php?id={$oferta['id_oferta']}'>{$oferta['denumire_locatie']}</a> ";
echo "<a href='delete.php?id=$id'>delete</a>";
echo "<br />";
The problem, in this case, is JavaScript related, yes. What I recommend you to do is to simply add a Remove link for each item.
echo "<a href='oferta.php?id={$oferta['id_oferta']}'>{$oferta['denumire_locatie']}</a>";
echo " - <a href='delete.php?id={$oferta['id_oferta']}'>Remove</a>";
echo "</br>";
Your $id is outside your while() loop.
The last one is getting deleted because the $id has the last one's value when the loops is exited.
Include all your code :
echo "</br>";
//echo "<input type=\"button\" id=\"cauta\" value=\"Vizualizeaza\" onclick=\"window.location.href='oferta.php?id={$oferta['id_oferta']}'\" />";
//echo " <input type=\"button\" id=\"cauta\"value=\"Modifica\" onclick=\"window.location.href='modifica.php?id={$oferta['id_oferta']}'\" />";
echo " <input type=\"button\" id=\"sterge\" value=\"Sterge\" onclick=\"window.location.href='delete.php?id=$id'\" />";
Inside your while loop.
When the rendered html reaches the browser, it will be something like this:
<input type='radio' name='selectie' value='1' id='1'> <a href='oferta.php?id=1'>TEXT</a>
<input type='radio' name='selectie' value='2' id='2'> <a href='oferta.php?id=2'>TEXT</a>
<input type='radio' name='selectie' value='3' id='3'> <a href='oferta.php?id=3'>TEXT</a>
<input type='radio' name='selectie' value='4' id='4'> <a href='oferta.php?id=4'>TEXT</a>
<br/>
<input type="button" id="sterge" value="Sterge" onclick="window.location.href='delete.php?id=5'" />
With this markup you won't be able to accomplish what you want without using javascript to update the onclick attribute whenever you select a radio button.
On the other hand, instead of using the client-side onclick event you can use the button's default behaviour, which is to submit the form.
You'll just have to set the action attribute:
<form method="post" action="http://myurl.php">
and write the myurl.php page which will just read the posted variable $_POST['selectie'] and call the delete method with the posted id.

Passing data between PHP webpages from a dynamically generated list

I have a PHP code which generates a dynamic list inside a form like the following, note that the list is built dynamically from database:
echo '<form name="List" action="checkList.php" method="post">';
while($rows=mysqli_fetch_array($sql))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='hidden' name='SessionID' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
What I need is to POST the data corresponding to the user choice when he clicks on the button for that row to another page.
If we use hyperlinks with query strings there will be no problem as I'll receive the data from the other page using a GET request and the hyperlinks would be static when showed to the user.
Also I need to obtain the user input from a textbox which is only possible with POST request.
Simply from the other page (checkList.php) I need these data for further processing:
$SessionID=$_POST['SessionID'];
$Code=$_POST['code'];
As I have a while loop that generates the fields, I always receive the last entry form the database and not the one corresponding to the line (row) that the user chosed from the LIST.
I'm going to recommend that you clean up the names of variables so that your code can
at least tell us what it's supposed to do. It should be rare that someone looks at your code
and has a lot of trouble trying to see what you're trying to accomplish :P, ESPECIALLY when you need help with something ;]. I'm going to try some things and hope that it makes doing what you want easier to comprehend and perhaps get you your answer.
It's good to try your best to not echo large amounts of HTML unnecessarily within a script , so firstly I'm going to remove the
echos from where they are not necessary.
Secondly, I'm going to use a mysql function that returns an easier to process result.
$user = mysqli_fetch_assoc($sql)
Third, I don't know if form having a name actually does anything for the backend or frontend of php, so I'm
just going to remove some of the extra crust that you have floating around that is either invalid HTML
or just doesn't add any value to what you're trying to do as you've presented it to us.
And yes, we "note" that you're building something from the database because the code looks like it does =P.
I'm also sooo sad seeing no recommendations from the other answers in regard to coding style or anything in regard to echoing html like this :(.
<?php while($user = mysqli_fetch_assoc($sql)): ?>
<form action="checkList.php" method="post">
<input type='password' name='code' value='<?php echo $user['code'] ?>' />
<input type='hidden' name='SessionID' value='<?php echo $user['id'] //Whatever you named the field that goes here ?>' />
<input type='submit' value='Take Survey' />
</form>
<?php endwhile; ?>
i not sure this is correct
echo '<form name="List" method="post">';
while($rows=mysqli_fetch_array($result))
{
echo "<input type='password' name='code' id='code'>";
echo "<input type='button' value='Take Survey' onclick=show($rows[0])>";
echo "<br>";
}
and javascript
<script>
function show(id)
{
alert(id);
window.location="checkList.php?id="+id;
}
</script>
On checkList.php
$id=$_GET['id'];
echo $id;
You can just check in checkList.php whether $_POST['code'] exists and if exists retrieve $_POST['SessionID'] which will be generated from database. But one thing, if You have all hidden fields in one form, they all will be sent, so You need to think how to correct that - maybe seperate forms for each hidden field, submit button and maybe other POST fields.
And afterwards, You will be able to get data in the way You need - $SessionID=$_POST['SessionID'];
I suppose it is the easiest way to solve that.
You can try something like this:
while($rows=mysqli_fetch_array($sql))
{
$index = 1;
echo "<input type='password' name='code' id='code'>";
//Attach $index with SessionID
echo "<input type='hidden' name='SessionID_$index' id='SessionID' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
}
On checkList.php
<?php
$num = explode('_', $_POST['SessionID']);
$num = $num[1];
//in $num you will get the number of row where you can perform action
?>
$form = 1;
while($rows=mysqli_fetch_array($sql))
{
echo '<form name="List_$form" action="checkList.php" method="post">';
echo "<input type='password' name='code' id='code_$form'>";
echo "<input type='hidden' name='SessionID' id='SessionID_$form' value='$rows[0]' />";
echo "<input type='submit' value='Take Survey'>";
echo '</form>';
$form++;
}

Putting SQL information into a HTML/PHP form

I've been having a rather irritating issue regarding capturing SQL information and then placing it into a PHP form (in theory, it should be kinda easy).
Here's the code for the SQL database information:
<?
$select = "SELECT * FROM beer WHERE country_id = 3";
$data = mysql_query($select) or die("Unable to connect to database.");
while($info = mysql_fetch_array($data)) {
echo '<center>';
echo '<h2>'.$info['name'].'</h2>';
echo '<table style="padding:0px;"><tr>';
echo '<tr><td><b>ABV%:</b></td><td width="570">'.$info['abv'].'</td></tr>';
echo '<tr><td><b>Bottle Size:</b></td><td width="570">'.$info['bottleSize'].'</td></tr>';
echo '<tr><td><b>Case Size:</b></td><td width="570">'.$info['caseSize'].'</td></tr>';
echo '<tr><td><b>Price:</b></td><td width="570">$'.$info['price'].'</td>';
echo '</tr></table>';
echo '</center>';
echo '<br/>';
echo '<img src="" border="0"><br><br>';
echo '<form name="cart" method="post" action="cart.php"> <table border="0"> <tr>';
echo '<td><input type="hidden" name="bname" value="'.$info['name'].'"><input type="hidden" name="price" value="'.$info['price'].'"></td>';
echo '<td><b>Quantity:</b></td>';
echo '<td><input type="text" name="qty" size="3"></td>';
echo '<td><input type="submit" value="Add to Cart" a href="cart.php?name=foo&price=bar" /a></td>';
echo '</tr></table></form>';
}
?>
I want when the submit value is pressed to somehow transmit the price, quantity and name to a basic HTML form (so that all the user has to do is add name, address, etcetc). I am completely stumped on how to do this.
If anyone could help, it would be much appreciated.
As you mentioned Amazon checkout, here is one thing you probably don't understand.
Amazoin doesn't use the form to move items data between server and browser to and fro.
It is stored in a session on a server time. All you need is some identifier put into hidden field.
To use a session in PHP you need only 2 things:
call session_start() function before any output to the browser on the each paghe where session needed.
Use `$_SESSION variable.
That's all.
Say, page1.php
<?
session_start();
$_SESSION['var'] = value;
and page2.php
<?
session_start();
echo $_SESSION['var'];
You wrote that code? because it's simply the same code as here.
You'll need to write an HTML form in your cart.php file
and use the $_POST variable to show the values of the price , quanitity and name.
For example:
<form method='post'>
<input type='text' name='price' value='<?=$_POST['price']?>'>
<input type='text' name='quanitity' value='<?=$_POST['qty']?>'>

Categories