I want to pass some value from my form to be sent with POST. However, when i use dropdown, it wont detect the value and thus giving me undefined index error for every variable
When i use simple text form to post, it works, but i need to use the dropdown form.
dropdown for shop code
<?php $stmt = $shop->readName();
echo "<select class='form-control name='shop_id'>";
echo "<option>select shop name</option>";
while ($row_shop = $stmt->fetch(PDO::FETCH_ASSOC)) {
extract($row_shop);
echo "<option value='{$shop_id}'>{$shop_name} </option>";
}
echo "</select>";
?>
and the post code
if ($_POST) {
// Set values
$transaction - > customer_id = $_POST['customer_id'];
$transaction - > shop_id = $_POST['shop_id'];
$transaction - > staff_id = $_POST['staff_id'];
// create transaction
if ($transaction - > add()) {
echo "<div class='alert alert-success'>Transaction was created.</div>";
}
// if unable to create the staff, tell the user
else {
echo "<div class='alert alert-danger'>Failed.</div>";
}
}
EDIT : Now the error is gone, but the form simply wont do anything :(
Here's the screenshot of the form
form
Undefined index errors means that you haven't defined $transaction as an object, thus when you try to update one of the values (for example $transaction->customer_id), PHP will give you an error.
Try defining $transaction like so:
$transaction = new yourObjectNameHere();
Just after the if($_POST).
Related
I'm currently working on a shopping cart using PHP, and I'm trying to figure out how to add items to the cart itself using the code I have written. The items from my database are being displayed correctly, but only the last array under $item is being added to the cart. The following displays the items.
$result = mysqli_query($cxn,$sql) or die("<p class='error'>Couldn't connect to server.</p>");
while($row = mysqli_fetch_assoc($result))
{
$product[] = $row;
}
foreach($product as $item)
{
echo "<div class='product'><form method='post'><div class='img_spacer'><div class='image'>";
include "images.inc";
echo "</div></div><div class='name'><h2>".$item['product']."</h2></div>";
echo "<div class='description'><p>".$item['description']."</p></div>";
echo "<div class='price'><p>".$item['price']."</p></div>";
echo "<div class='add_cart'><input type='hidden' name='add' value='yes'>
<input type='submit' name='add_cart' value='Add to Cart'>
</div></form></div>";
}
The following code is for the shopping cart itself. I have it currently set to print_r the sent variables so I can see what information is being posted.
<?php
if(isset($_POST['add']) and $_POST['add'] == 'yes')
{
$selected = "select product_ID, product, price from product where product_ID='".$item['product_ID']."'";
$result2 = mysqli_query($cxn,$selected);
while($row2 = mysqli_fetch_assoc($result2))
{
print_r($row2);
}
}
?>
I also tried adding the $item['product_ID'] variable to make the 'add' input unique, using
<input type='hidden' name='".$item['product_ID']."_add' value='yes'>
but I couldn't figure out how to add another variable to the $_POST array. I should also mention that I'm using sessions for this project, and I'm not quite sure how to add their shopping cart to the $_SESSION variable. How can I fix this?
You'll want to add more hidden fields to your form. At least:
<input type='hidden' name='product_ID' value='".$item['product_ID']."'>
This will add another variable to the $_POST array when the user clicks Add to Cart.
At the start of each page, you should have a call to session_start();. Then, simply assign the values for your cart to session variables like so:
if(isset($_POST['add']) and $_POST['add'] == 'yes') {
if (!isset($_SESSION['cart'])) {
$_SESSION['cart']=array();
}
array_push($_SESSION['cart'], $_POST);
}
Then (when the user places the order) you would scrub the input, to prevent SQL injection, and add a new SQL query, perhaps something like;
//submit selected items
foreach ($_SESSION['cart'] as $cart_item) {
$pid=scrub($cart_item['product_ID']);
$amount=scrub($cart_item['amount']);
$inserted = "INSERT INTO orders (user, product_id, amount, when) VALUES (".$uid.", ".$pid.", ".$amount.", NOW())";
$result3 = mysqli_query($cxn,$inserted);
}
Of course, you'll have to create the function scrub to scrub your input, but that's outside the scope of the question.
I created a table in HTML, and I'm inserting all the information from a specific database table, into this HTML table using a foreach loop.
I created a button called delete, to delete a specific row from the database, but I'm having some problems because I don't know how I can delete the table information using a foreach loop, because I always use a while statement.
I'm doing a kind of MVC structure, but with my own rules, so I got the model and the view, I'm calling all the functions at view.
And I'm doing something like this on view:
function fname($array) {
foreach($array as $key) {
echo $key['row1'];
echo "<input type='submit' value='delete'";
}
}
And I made my function on model:
function function() {
connect();
$show = ("SELECT * FROM mytable");
$array = db_array($show, 'v');
fname($array);
}
Can you guys help me with an example? Thanks.
Create a form inside the loop for each row i.e. if it prints out 10 rows it means 10 different forms. While submitting form (clicking delete), send the row id as hidden parameter to the controller (in action) while in turns send it to model. Model has the delete query which gets execute and the row gets deleted.
View -
foreach($array as $key)
{
$row_id = $key['row_id'];
echo "<form action='/deleterow' method='POST'>"
echo $key['row1'];
echo "<input type='submit' value='delete'>";
echo "<input type='hidden' name='id' value=$row_id>";
echo "</form>";
}
Controller -
function deleterow($id)
{
$this->model_name->delete($id);
}
Model -
function delete($id)
{
$sql = "DELETE FROM table_name WHERE id=$id";
$exe = mysql_query($sql) or die(mysql_error());
}
I would try this
function fname($array){
foreach($array as $key=>$val){
echo $val['FIELD'];
echo '<input name="Z" type="hidden" value="'.$key.'" />';
echo '<input type="submit" value="Delete"/>';
}
}
I am assuming you are going to make a page where someone can delete something?
You need to echo out the recode name? (this depends on what you are pulling out of the table and fields involved)
The when the delete button is pressed you can act upon hidden field Z
I'm having an issue in passing a value from a dropdown list that is in a separate PHP file that is being used by jquery.
I ended up getting the values from the dropdown list that isn't posting correctly by using jquery based on the value selected in the first dropdown list. The dropdown list in question is populating correctly, but with the way I have it setup I cannot post the value to the submit PHP page.
I'm pretty sure it has to do with the way I have it setup; however, I'm very new to jquery and was looking for some guidance.
The main PHP Page (the small areas in question)
<select name="department_list" id="department_list" onchange="$('#singleUser').load('get_users.php?nid='+this.value);">
...
<div id="singleUser" class="singleUser">
</div>
The PHP page (get_users) used to fill the values (only the area in question)
echo '<p style="text-align:center">';
echo "
<br />
Select a person to receive the form
<br />";
echo "<select id='userSelect' class='userSelect'>";
if ($id == '50') {
echo "<option value='Done'>Done</option>";
echo "</select>";
}else {
echo "<option value='none'>Select user</option>";
try {
$db = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password);
$stmt = $db->prepare("SELECT dm.empid AS empid, u.name AS name FROM mytable dm
JOIN mytable2 u ON dm.empid = u.id
WHERE dm.deptid = :id
ORDER BY u.name");
$stmt->bindParam(':id', $id);
$stmt->execute();
while ($r = $stmt->fetch()) {
$empid = $r['empid'];
$userName = $r['name'];
echo "<option value='".$empid."'>".$userName."</option>";
}
echo "</select>";
echo "</p>";
$db = null;
}
catch (PDOException $ex) {
echo "An Error occurred!";
}
}//end else
In the submit page:
if(isset($_POST['userSelect'])){
$givenID = $_POST['userSelect'];
//the rest of my code
I do have the div code above within the form tags and have method="post". All of my other inputs post correctly, so I'm thinking it has to do with the way I have only the div tags within the main page. Again, I'm pretty new to all of this so any ideas or changes that I should make so it posts correctly would be greatly appreciated.
You forgot the name of the select when you write it with php:
change this:
echo "<select id='userSelect' class='userSelect'>";
to
echo "<select id='userSelect' name='userSelect' class='userSelect'>";
i think the error is in the PHP file generating the user select it is missing the name attribute name="userSelect"
echo "<select id='userSelect' class='userSelect'>";
it should be
echo '<select id="userSelect" name="userSelect" class="userSelect">';
every form element with the name attribute gets posted with its value. if you do not enter the name attribute, the value can not be retrieved from the $_POST array. Also have in mind that disabled form inputs also do not get posted.
Edited the PHP quotes. Use Single qutes everyt time you do not need to insert PHP variable into the string. It is ~9 times faster than double quotes ;)
Hello i am new to php and i have tried to find a piece of code that i can use to complete the task i need, i currently have a page with a form set out to view the criteria of a course. also i have a dropdown menu which currently holds all the course codes for the modules i have stored in a database. my problem is when i select a course code i wish to populate the fields in my form to show all the information about the course selected. The code i am trying to get to work is as follows:
<?php
session_start();
?>
<? include ("dbcon.php") ?>
<?php
if(!isset($_GET['coursecode'])){
$Var ='%';
}
else
{
if($_GET['coursecode'] == "ALL"){
$Var = '%';
} else {
$Var = $_GET['coursecode'];
}
}
echo "<form action=\"newq4.php\" method=\"GET\">
<table border=0 cellpadding=5 align=left><tr><td><b>Coursecode</b><br>";
$res=mysql_query("SELECT * FROM module GROUP BY mId");
if(mysql_num_rows($res)==0){
echo "there is no data in table..";
} else
{
echo "<select name=\"coursecode\" id=\"coursecode\"><option value=\"ALL\"> ALL </option>";
for($i=0;$i<mysql_num_rows($res);$i++)
{
$row=mysql_fetch_assoc($res);
echo"<option value=$row[coursecode]";
if($Var==$row[coursecode])
echo " selected";
echo ">$row[coursecode]</option>";
}
echo "</select>";
}
echo "</td><td align=\"left\"><input type=\"submit\" value=\"SELECT\" />
</td></tr></table></form><br>";
$query = "SELECT * FROM module WHERE coursecode LIKE '$Var' ";
$result = mysql_query($query) or die("Error: " . mysql_error());
if(mysql_num_rows($result) == 0){
echo("No modules match your currently selected coursecode. Please try another coursecode!");
} ELSE {
Coursecode: echo $row['coursecode'];
Module: echo $row['mName'];
echo $row['mCredits'];
echo $row['TotalContactHours'];
echo $row['mdescription'];
echo $row['Syllabus'];
}
?>
however i can only seem to get the last entry from my database any help to fix this problem or a better way of coding this so it works would be grateful
Thanks
The main error is in your final query, you're not actually fetching anything from the query, so you're just displaying the LAST row you fetched in the first query.
Some tips:
1) Don't use a for() loop to fetch results from a query result. While loops are far more concise:
$result = mysql_query(...) or die(mysql_error());
while($row = mysql_fetch_assoc($result)) {
...
}
2) Add another one of these while loops to your final query, since it's just being executed, but not fetched.
For me i would use some javascript(NOTE: i prefer jQuery)
An easy technique would be to do this(going on the assumption that when creating the drop downs, your record also contains the description):
Apart from creating your dropdown options like this <option value="...">data</option>, you could add some additional attributes like so:
echo '<option value="'.$row['coursecode'].'" data-desc="'.$row['description'].'">.....</option>
Now you have all your drop down options, next is the javascript part
Let's assume you have included jQuery onto your page; and let's also assume that the description of any selected course is to be displayed in a <div> called description like so:
<div id="course-description"> </div>
<!--style it how you wish -->
With your javascript you could then do this:
$(function(){
$("#id-of-course-drop-down").change(function(){
var desc = $(this).children("option").filter("selected").attr("data-des");
//now you have your description text
$("#course-description").html(desc);
//display the description of the course
}
});
Hope this helps you, even a little
Have fun!
NOTE: At least this is more optimal than having to use AJAX to fecch the description on selection of the option :)
I'm currently using php to populate a form with selections from a database. The user chooses options in a select style form and submits this, which updates a summary of the selections below the form before a second submit button is used to complete the interaction.
My issue is that every time a user uses the first submit, the selections that were there previously do not stick. They have to go through the whole form again.
Is there anyway to keep these selections present without resorting to php if statements? There are a ton of options so it would be a pain to use php for each one. Also, form is being submitted via POST.
Sample from form:
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'COLOR' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
I tried using this js snippet to repopulate the selections, but it does not seem to work properly...
<script type="text/javascript">document.getElementById('color').value = "<?php echo $_GET['proudct_cpu'];?>";</script>
This does not seem to work. Any suggestions other than php if statements?
Thanks!
edit: This is basically the form set up I'm using, though I've shortened it significantly because the actual implementation is quite long.
// Make a MySQL Connection
<?php mysql_connect("localhost", "kp_dbl", "mastermaster") or die(mysql_error());
mysql_select_db("kp_db") or die(mysql_error());
?>
<br />
<form action="build22.php" method="post">
<input type="hidden" name="data" value="1" />
<br />
<br />
<?php
// GRAB DATA
$result = mysql_query("SELECT * FROM special2 WHERE cat = 'color' ORDER BY cat")
or die(mysql_error());
echo "<div id='color'><select id='color' name='product_color'>";
while($row = mysql_fetch_array( $result )) {
$name= $row["name"];
$cat= $row["cat"];
$price= $row["price"];
echo "<option value='";echo $name;echo"'>";echo $name;echo" ($$price)</option>";}
echo "</select>";
echo "<input type='hidden' name='amount_color' value='";echo $price;echo"'></div>";
?>
<input type="submit" value="Update Configuration">
</form>
The selections from the form above get echoed after submission to provide the user with an update as such:
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>    ";echo $_POST['product_color']; ?>
</div>
I assume you're storing the user's selections in a separate table. If that's the case, you'll need to add some logic to determine if you should display the form values or what's already been stored.
<?php
// form was not submitted and a config id was passed to the page
if (true === empty($_POST) && true === isset($_GET['config_id']))
{
// make sure to properly sanitize the user-input!
$rs = mysql_query("select * from saved_configuration where config_id={$_GET['config_id']}"); // make sure to properly sanitize the user-input!
$_POST = mysql_fetch_array($rs,MYSQL_ASSOC); // assuming a single row for simplicity. Storing in _POST for easy display later
}
?>
<div id="config" style="background-color:#FFF; font-size:12px; line-height:22px;">
<h1>Current Configuration:</h1>
<?php echo "<strong>Color:</strong>    ";echo $_POST['product_color']; ?>
</div>
So after storing the user's selections in the database, you can redirect them to the page with the new config_id in the URL to load the saved values. If you're not storing the selected values in a table, you can do something similar with cookies/sessions.
echo the variables into the value tag of the form elements. If you post all your code I'm sure I can help you.
UPDATE
ah, so they are dropdown lists that you need to remember what was selected? Apologies, I read your post in a rush yesterday and thought it was a form with text inputs.
I just did a similar thing myself but without trying your code let me see if I can help.
Basically what you need to do is set one value in the dropdown to selected="selected"
When I had to do this I had my dropdown values in an array like so:
$options = array( "stack", "overflow", "some", "random", "words");
// then you will take your GET variable:
$key = array_search($_GET['variablename'], $options);
// so this is saying find the index in the array of the value I just told you
// then you can set the value of the dropdown to this index of the array:
$selectedoption = $options[$key];
This is where it might be confusing as my code is different so if you want to use it you will probably need to restructure a bit
I have a doSelect function to which I pass the following parameters:
// what we are passing is: name of select, size, the array of values to use and the
// value we want to use as the default selected value
doSelect("select_name", 1, $options, $selectedoption, "");
// these are the two functions I have:
// this one just processes each value in the array as a select option which is either
// the selected value or just a 'normal' select value
FUNCTION doOptions($options, $selected)
{
foreach ($options as $option)
{
if ($option == $selected)
echo ("<option title=\"$title\" id=\"$value\" selected>$option</option>\n");
else
echo ("<option title=\"$title\" id=\"$value\">$option</option>\n");
}
}
// this is the function that controls everything - it takes your parameters and calls
// the above function
FUNCTION doSelect($name, $size, $options, $selected, $extra)
{
echo("<select class=\"\" id=\"$name\" name=\"$name\" size=\"$size\" $extra>\n");
doOptions($options, $selected);
echo("</select>\n");
}
I know that's a lot of new code that's been threw at you but if you can get your select values from the db into the array then everything else should fall nicely into place.
The only thing I would add, is at the start where we call doSelect, I would put that in an if statement because you don't want to set something as selected which hasn't been set:
if (isset($_GET['variable']))
{
$key = array_search($_GET['variablename'], $options);
$selectedoption = $options[$key];
doSelect("select_name", 1, $options, $selectedoption, "");
}
else
{
doSelect("select_name", 1, $options, "", "");
}
I hope that helps!