Saving a specific row using PHP and a search option - php

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.

Related

set php get set variable with hyperlink

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!

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.

Running javascript inside php

I have this javascript that i want to run in php,
the code bellow is supposed to be submitted in a form and then then prints it
but when submitted the javascript doesn't execute, the output is simply
var text = document.getElementById(\'course1\').options[document.getElementById(\'course1\').selectedIndex].text; document.write(text);
this is the whole thing,
echo "<form name\"find\" action=\"postEnrolled.php\" method=\"get\" class=\"required\" onsubmit=\"return validate(this);\">";
echo "<table width=\"225\" border=\"0\" align=\"center\" >";
echo "<tr>";
echo "<td width=\"181\"><label>Course#1:</label> <select name=\"dep1\" style=\"width:190px\" class=\"dep1\">";
echo "<option selected=\"selected\" value=\"\">Select Department</option>";
include('db.php');
$sql=mysql_query("select id,data from data where weight='1'");
while($row=mysql_fetch_array($sql))
{
$id = $row['id'];
$data = $row['data'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
echo "</select><br/></td>";
echo "<td width=\"267\">";
echo "<label> </label><select name=\"course1\" class=\"course1\" style=\"width:200px\">";
echo "<option selected=\"selected\" value=\"\">Select Course</option>";
echo "</select>";
echo "<input type=\"hidden\" name=\"course_1\" value=\"
<script language='javascript' >
var text = document.getElementById('course1').options[document.getElementById('course1').selectedIndex].text;
document.write(text);
</script>
Am I missing something?
what I really want is to submit the text in the options and not the value of the options.
getElementById will only find an element whose id is course_1, not the name.
Don't put the script element inside the input element
You must have the DOM ready when calling it (use document.onload=function(){...yourcodehere...};)
At first sight, there is no PHP really involved in this problem. But are you aware that the code, as it is, wouldn't be executed when you change the value of the option ? If that's what you need, use onchange="yourcodehere;". But as it is an hidden field, maybe you should describe what you really want to achieve.
EDIT :
If what you want is change the hidden input when the user selects another option, here's how you can do it :
<input type=hidden name=course_1 id=course_1>
<select onchange="document.getElementById('course_1').value=this.options[this.selectedIndex].text;" ...
Your problem is that you're putting a <script> tag inside of the value attribute of the <input> tag. That isn't valid HTML or JavaScript and will not work.
why you don't post what is the actual error you got? actually this approach (including the javascript code into php tags) is not good at all.if you want to use javascript on any page, you just have to put it on the very top of your page under the script tags.
try it, will help u ..!

Hide text input field on page load?

it's should be something really simple if its possible. anyway of doing so? can't seem to find it online.
i have a set of checkboxes and textboxes beside it. i only want the textboxes to appear if i check it. my ids are dynamic using php so i cant use javascript out of the loop.
the code below is to test if it works to hide. i am able to hide on click but iam hoping to do the other way round.
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td><input name='CBox $TBCounter' type=\"checkbox\" value=\"{$row['type']}\" onclick=\"document.getElementById('TBox $TBCounter').style.visibility='hidden';\"/></td>";
echo "<td>" . $row['type'] . "</td>
<td><input type=\"text\" name=\"mytext\" id=\"TBox $TBCounter\"></td><br />
</tr>";
$TBCounter++;
}
You can use Javascript's window.onload to make something run every time the page loads.
Before your loop...
$elementsToHide = array();
During your loop, put this
$elementsToHide[] = $TBCounter;
Then make your script (after the loop) look like this
<script type="text/javascript">
window.onload = function ()
{
<?php foreach ($elementsToHide AS $TBCounter): ?>
document.getElementById('TBox <?php echo $TBCounter ?>').style.visibility = 'hidden';
<?php endforeach ?>
}
</script>
There are probably better (read: less intrusive) ways, but the simplest is probably to set the visibility of the element to hidden and change your Javascript to make it visible.
So, add style="visibility:hidden;" to the textbox element and change the javascript to set .style.visibility = 'visible'
Editing your code, that would be:
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td><input name='CBox $TBCounter' type=\"checkbox\" value=\"{$row['type']}\" onclick=\"document.getElementById('TBox $TBCounter').style.visibility='visible';\"/></td>";
echo "<td>" . $row['type'] . "</td>
<td><input type=\"text\" name=\"mytext\" id=\"TBox $TBCounter\" style=\"visibility:hidden\"></td><br />
</tr>";
$TBCounter++;
}
As per Joe's comment, this will not work for users with javascript disabled as the field if hidden when the page loads. One way around this is to set the field invisible in javascript by outputting an inline script tag.
while($row = mysql_fetch_array($result)){
echo "<tr>";
echo "<td><input name='CBox $TBCounter' type=\"checkbox\" value=\"{$row['type']}\" onclick=\"document.getElementById('TBox $TBCounter').style.visibility='visible';\"/></td>";
echo "<td>" . $row['type'] . "</td>
<td><input type=\"text\" name=\"mytext\" id=\"TBox $TBCounter\"></td><br />
</tr>
<script>document.getElementById('TBox $TBCounter').style.visibility='hidden';</script>";
$TBCounter++;
}
A third (better) alternative could be to set a class for the textboxes and use javascript to hide all elements with that class on page load.

identify jquery button click in php rows

I have an input button in :
while ($row = $result->fetch()) {
echo '<table class="cart-row" cellspacing="0" cellpadding="0" width="100%">';
echo '<tbody>';
echo '<tr>';
echo '<td width="75"><img border="0" width="59px" height="78px" title="" alt="" src=' . $row["ImagePath"] .'></td>';
echo '<td width="203"><span id="itemName" class="itemElements">'. $row["Name"] .'</span></td>';
echo '<td width="135"><span id="qtyNum">('. $row["Qty"] .')</span> <br />';
echo '<span id="qtyRemoveLink"><input class="linkbtn" type="submit" id="btnRemove" value="Remove"></td>';
echo '<td width="180"><span id="orderStatus" class="itemElements">In Stock Usually dispatched within 24 hours</span></td>';
echo '<td width="175" id="itemPriceRow"><span id="itemPrice">€ '. $row["Price"] .'</span></td>';
echo '</tr>';
echo '</tbody>';
echo '</table>';
echo '<br>';
}
I'm trying to use this method to trigger an event when the button is clicked however the event is only being fired for the first button generated in the first row. I'm using this method:
$(document).ready(function() {
$('#btnRemove').click(function() {
alert("test");
});
});
Any ideas how I can fix this problem? I know in C# there is on row databound method however in jQuery I dont now if it exsists. Thanks
You are selecting an element to bind the click event handler to that has a unique ID. When you select by ID you will be returned only the first matching element because to be a valid ID it must be unique.
Change the ID to a class and change your selector to .btnRemove and the alert will work for all the buttons.
echo '<span id="qtyRemoveLink"><input class="linkbtn" type="submit" id="btnRemove" value="Remove"></td>';
Should change to:
echo '<span id="qtyRemoveLink"><input class="linkbtn btnRemove" type="submit" value="Remove"></td>';
And:
$('#btnRemove').click(function() {
Should change to:
$('.btnRemove').click(function() {
Here is a demo: http://jsfiddle.net/rSyCw/
Here is an excellent answer on the site regarding the creation of valid HTML IDs: What are valid values for the id attribute in HTML?
Use a class for the button, not an ID. IDs are unique identifiers (can only be one with that name on the whole page), however classes may be applied to multiple elements. So...
<input type="submit" id="btnRemove" />
Becomes
<input type="submit" class="btnRemove" />
And, as such, your selector changes to .btnRemove.
And, now that you know that IDs need to be unique, you should go ahead and re-configure the output to use classes, or use IDs with a unique ID appended. e.g.
<?php
while ($row = $result->fetch()){
?>
<!-- Other HTML -->
<input type="submit" id="btnSubmit_<?= $row['Unique_Column_Id']; ?>" ... />
Then you can modify your selector:
$('[id^="btnSubmit_"]').click(...); // All elements with an
// ID that starts with "btnSubmit_"
One red flag here is that you are generating multiple elements with the same ID on each iteration of your loop. Element IDs need to be unique in your document. My guess is that jQuery is only binding to the first element it finds with the ID "btnRemove" because it assumes that your IDs are unique.
As others have stated, using a class name on your button would help your problem, but you should still come up with a way to put unique IDs on your itemName, qtyNum, qtyRemoveLink, orderStatus, itemPriceRow, and itemPrice elements, and anywhere else you might be using this technique.

Categories