issue when inserting data in DB using submit button - php

i define below codes to show my products on website. I fetch my products details from Database.
When i click on the enquiry submit button it is not selecting the same id and inserting another product id in to database. Please see below codes which i use to send details in database using enquiry Submit Button
Please see below the updated codes, these are all codes which i am using to inserting data when clicking on enquiry submit button
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
</tr>
</table>
</td><br>
<?php
endwhile;
if($_REQUEST['enquiry'])
{
mysql_query("insert into orders values('$userid','$productid','$productprice')");
}
?>

Your table in your mysql database probably has the columns in a different order. To make sure, specify the columns in your insert query before specifying the values.

You're getting the wrong value for $productid because it's assigning the last value of it in your while loop, as your insertion code (and therefore your reference to it) is below that loop, you want to send the product id and price to the page accessible by $_REQUEST when the user clicks submit, to do this in your case you can use hidden form fields to store the values of each product, and a separate form for each element in your loop.
Also you want to put your submission code above your loop.
Depending where this data comes from you might want to escape it before inserting it in the database, I haven't in this example.
<?php
session_start();
include'database.php';
$userid=$_SESSION['userid'];
//check for submission and insert if set
if($_REQUEST['enquiry'])
{
//use the userid session for userid, and submitted values for productid and productprice
mysql_query("insert into orders values('$userid,'{$_REQUEST['productid']}','{$_REQUEST['productprice']}')");
}
$c=mysql_query("select 'productid','productprice' from products order by rand()");
while(list($productid,$productprice)=mysql_fetch_array($c)):
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<td align="center">
<table class="newproducttd" align="center">
<tr>
<td class="code" align="center"><?php echo $productid; ?></td>
<td class="price" align="center"><?php echo $productprice; ?></td>
</tr>
<tr>
<td class="button" align="center"><input type="submit" class="enquiry" name="enquiry" value="ENQUIRY" /></td>
//hidden form fields to store data to send to page
<input type="hidden" name="productid" value="<?php echo $productid;?>">
<input type="hidden" name="productprice" value="<?php echo $productprice;?>">
</tr>
</table>
</form>
<?php
endwhile;
?>

Related

PHP calculator results in a new page? PHP first attempt

I'm trying to get the website to send the calculation results to another page. The code below is working but I have no idea how to get the rows with the results to be shown in a new page.
I know that i have to change the action below to /mynewpage
But I just want the results not the whole table.
I have no idea what to do to the code to make it show the results only in a new page. IF everything statys in the same page the calculator works well.
It's my first attempt with PHP, I clearly have no idea of what I'm doing. Many thanks in advance.
<?php
if (isset($_POST['valuea'])) $valuea = $_POST['valuea'];
if (isset($_POST['valueb'])) $valueb = $_POST['valueb'];
if (isset($_POST['valuec'])) $valuec = $_POST['valuec'];
if (isset($_POST['valued'])) $valued = $_POST['valued'];
if (isset($_POST['valuee'])) $valuee = $_POST['valuee'];
$balance = $valuec * $valuee;
$newphone = $valuea;
$total = $balance + $valuea;
$total2 = $balance + $valueb;
echo <<<_END
<form method='post' action='/'>
<table border='0' width='500px' cellpadding='3' cellspacing='1' class="table">
<tr class="calcheading"><td colspan="2"><strong>CALCULATOR</strong></td></tr>
<tr class="calcrow"><td>Phone Value:</td><td align="center"><input type='text' name='valuea' value="$valuea"/></td></tr>
<tr class="calcrow"><td>Phone upfront cost:</td><td align="center"><input type='text' name='valueb' value="$valueb"/></td></tr>
<tr class="calcrow"><td>Monthly contract cost:</td><td align="center"><input type='text' name='valuec' value="$valuec"/></td></tr>
<tr class="calcrow"><td>Contract duration:</td><td align="center"><input type='text' name='valued' value="$valued"/></td></tr>
<tr class="calcrow"><td>No. months left in the contract:</td><td align="center"><input type='text' name='valuee' value="$valuee"/></td></tr>
<tr class="submit"><td colspan="2"><input type='submit' value='Calculate'/></td></tr>
_END;
?>
<tr class="calcheading"><td colspan="2"><strong>OPTION 1 - PAY REMAINING OF THE CONTRACT AND BUY SAME PHONE UNLOCKED</strong></td></tr>
<tr class="calcrow">
<td><i>Payment left to network:</td>
<td align="center"><input type="text" value="<?php echo round($balance)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>New unlocked phone:</td>
<td align="center"><input type="text" value="<?php echo round($newphone)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>TOTAL:</td>
<td align="center"><input type="text" value="<?php echo round($total)?>"></td></i>
</tr>
<br>
<tr class="calcheading"><td colspan="2"><strong>OPTION 2 - PAY BALANCE LEFT AND GET SAME PHONE ON A NEW CONTRACT*</strong></td></tr>
<tr class="calcrow">
<td><i>Payment left to network:</td>
<td align="center"><input type="text" value="<?php echo round($balance)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>New contract phone initial cost:</td>
<td align="center"><input type="text" value="<?php echo round($valueb)?>"></td></i>
</tr>
<tr class="calcrow">
<td><i>TOTAL:</td>
<td align="center"><input type="text" value="<?php echo round($total2)?>"></td></i>
</tr></table>
</form>
You can either send the values in a form and receive them on the other page using
$value1 = $_GET['value1'];
$value2 = $_GET['value2']; // etc
The other method would be saving them in a session variable, at the top of any pages where you wish to use session variables, call session_start(), then save them
$_SESSION['value1'] = $value1;
Then in another page, you can call them by simply
echo $_SESSION['value1'];
I'm not sure what you mean by new page? If you have a script like process.php that has that code then you can add session_start(); as your first line after the php start tag. By using $_Session['result']=$calc_result; on the 'process.php' you will store the value in your session. In the 'new page' script you call session_start(); again and you can get the stored value by saying $_Session['result'].
There are many ways to print your answers on a new page but lets keep it simple: A good way to do it would be for you to separate out the HTML form that posts the values and the php calculation logic on two different pages. So for example, your HTML form is in one file values.php (does not have any php code, you can name it with a .html prefix as well) and the php code is in another file calc.php. Now, to your form, specify an action such as
<form method='post' action='calc.php'>
This will post all the values to calc.php where your calculation code is and you can display the results however you please (not limited to a form again) but in a table or so on. Once you learn ajax, you'll never want to come back to doing this.
Here is a working barebones example: http://runnable.com/VEKvtTTrkXFwjAwL/calculator555-for-php

Store PHP/SQL foreach form items in variables

Sorry I'm a bit of a noob when it comes to PHP but I just wondered if someone had an idea on how I could solve this PHP/SQL problem.
I have a PDO statement that gets all users from a database.
With the array of users from the database I create a foreach loop to display all of the users in a table which I want to use to select a specific user, enter a number in the row of the user I select, then click submit and store the users name and also the number. I will use this information to populate another database later.
My question is, I cant seem to reference the user or the number in the table to extract the user and number I enter. When I try and request the numbered entered in the index.php, it will only ever display a number if I enter a number for a the final user in the table. When I try and view the FullName it never works and I get 'Undefined index: FullName' error.
I also specified to 'POST in the form but it doesnt seem to be doing that.
Does anyone have any ideas?
Thanks
//function.php
function getName($tableName, $conn)
{
try {
$result = $conn->query("SELECT * FROM $tableName");
return ( $result->rowCount() > 0)
? $result
: false;
} catch(Exception $e) {
return false;
}
}
//form.php
<form action "index.php" method "POST" name='form1'>
<table border="1" style="width:600px">
<tr>
<th>Name</th>
<th>Number Entered</th>
<tr/>
<tr>
<?php foreach($users as $user) : ?>
<td width="30%" name="FullName">
<?php echo $user['FullName']; ?>
</td>
<td width="30%">
<input type="int" name="NumberedEntered">
</td>
</tr>
<?php endforeach; ?>
</table>
<input type="submit" value="submit"></td>
</form>
//index.php
$users = getName('users', $conn);
if ( $_REQUEST['NumberedEntered']) {
echo $_REQUEST['NumberedEntered'];
echo $_REQUEST['FullName'];
}
The variable FullName isn't transmitted by your form to index.php. Only values of form elemnts are sent. You can add a hidden form field, that contains FullName like this:
<input type="hidden" name="FullName" value="<?php echo $user['FullName']">
But your second problem is, that your foreach loop will create several input fields with the exact same name. You won't be able to recieve any of the entered numbers, except the last one. have a look at this question for possible solutions.
Update
Putting each row in individual form tags should solve your problem:
<?php foreach($users as $user) : ?>
<form action="index.php" method="POST">
<tr>
<td align="center" width="40%" >
<?php echo $user['FullName']; ?>
<input type="hidden" name="FullName" value="<?php echo $user['FullName']; ?>" />
</td>
<td width="30%">
<input name="NumberedEntered"/>
</td>
<td>
<input type="submit" value="submit"/>
</td>
</tr>
</form>
<?php endforeach; ?>

Displaying Data from mysql table

I have created this form using the while loop so that i dont have to make 28 text field ... but when i submit the data into my mysql database it works well but how to display the data back to my form for edit and update .. when i type a value to a text field (EX - submitted data from mysql in emp_name field) then it repeated 4 times in the text field .... i know it is happening because of loop but is there any way that i can display multiple data in each text field for updating after submitting data by the user as normal ....
my form.php
<form action="userdata.php" name="frmAdd" method="post">
<table width="80%" border="0" cellpadding="3" cellspacing="3" class="forms">
<tr>
<td width="5"> <div align="center">NO</div></td>
<td width="91"> <div align="center">Employer's NAME</div></td>
<td width="160"> <div align="center">COUNTRY</div></td>
<td width="198"> <div align="center">POSITION</div></td>
<td width="70"> <div align="center">FROM</div></td>
<td width="70"> <div align="center">TO</div></td>
<td width="70"> <div align="center">SALARY</div></td>
<td width="70"> <div align="center">REASONS FOR LEAVING</div></td>
</tr>
<?php for($i=1;$i<=4;$i++) { ?>
<tr>
<th width="5"> <div align="center"><? echo $i . "."; ?></div></th>
<td><input type="text" name="emp_name<?=$i;?>" size="25" value="submitted data from mysql"></td>
<td><input type="text" name="emp_country<?=$i;?>" size="10"></td>
<td><input type="text" name="emp_pos<?=$i;?>" size="10"></td>
<td><input type="text" name="emp_frm<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_to<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_sal<?=$i;?>" size="5"></td>
<td><input type="text" name="emp_lev<?=$i;?>" size="25"></td>
</tr>
<?php } ?>
</table>
</br>
<input type="submit" name="doHis" value="Save Employment History">
<input type="hidden" name="hdlfrm" value="<?=$i;?>">
</form>
and my userdata.php
if($_POST['doHis'] == 'Save Employment History')
{
try{
$conn = new PDO("mysql:host=localhost;dbname=dbname", "user", "pass");
}
catch(PDOException $pe)
{
die('Connection error, because: ' .$pe->getMessage());
}
for($i=1;$i<=$_POST["hdlfrm"];$i++){
if($_POST["emp_name$i"] != ""){
$sql = "INSERT INTO emp_table (emp_name, emp_country, emp_pos, emp_frm, emp_to, emp_sal, emp_lev)
VALUES (:emp_name, :emp_country, :emp_pos, :emp_frm, :emp_to, :emp_sal, :emp_lev)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':emp_name', $_POST["emp_name$i"]);
$stmt->bindParam(':emp_country', $_POST["emp_country$i"]);
$stmt->bindParam(':emp_pos', $_POST["emp_pos$i"]);
$stmt->bindParam(':emp_frm', $_POST["emp_frm$i"]);
$stmt->bindParam(':emp_to', $_POST["emp_to$i"]);
$stmt->bindParam(':emp_sal', $_POST["emp_sal$i"]);
$stmt->bindParam(':emp_lev', $_POST["emp_lev$i"]);
$stmt->execute();
echo "Save Done. Click <a href='phpMySQLListRecord.php'>here</a> to view.";
}
}
}
and here is the snapshot
The problem you have is your data model - you are saving employment history, but for who? It needs to have an employee_id somewhere to say who this data belongs to, and join it to a table that saves the employee_table data. Next you need to have a unique ID on the emp_table to identify each row, which you can use instead of your $i index.
TABLE
history_id INT autoincrement | employee_id INT | emp_name VARCHAR | your other fields....
SELECT
SELECT history_id, emp_name, ... FROM emp_history where employee_id = ?
You can then loop over the results and use the history_id to identify the row that the data belongs to to update it. Submitting multiple fields with the same name will be an array you can iterate over, so you don't need to use a unique field name for each.
As a side note, you probably want to use isset($_POST["key"]) instead of $_POST["key"] != "" to check if a field was submitted.

Is POST information from jquery $.post sent in parent page

I have a parent page which has a drop down list in it. using the onchange event, data is posted to a second page using $.post(). This page uses the posted variables to output mysql data with a checkbox for each line. This page output is then inserted into the parent page using jquery $('#DIV name').html(output).show();
The user can then see the mysql table rows with corresponding checkboxes. They then select the checkboxes they want and say delete. Delete is a form submit button.
My question is, when they click delete how do I take the form data from the second page and post it with that of the parent page so that I can then use $_POST[] to get the checkbox info and delete the selected table rows?
example of the parent page code is:
javascript/jquery
<script type="text/javascript">
function get(row){ //row being processed, defined in onchange="get(x)"
('getpeopleinjobs.php',{ //data posted to external page
postvarposition: form["position"+row].value, //variable equal to input box, sent to external page
postvarjob: form["job"+row].value, //variable equal to input box, sent to external page
postvarperson: form["person"+row].value, //variable equal to drop down list, sent to external page
postrow: row}, //variable equal row being processed, sent to external page
function(output){
$('#training'+row).html(output).show(); //display external results in row div
//popupWindow = window.open('t4.php?variable1Name=Vicki&variable2Name=Maulline','popUpWindow','height=400,width=1000,left=10,top=10,resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,directories=no,status=yes')
});
}
</script>
Form data is
<tr>
<td>
<?PHP echo $i; ?>
</td>
<td>
<input type=text NAME="position<?PHP echo $i; ?>" id="position<?PHP echo $i; ?>" style="border: 1px solid #2608c3;color:red; width=200px" value="<? echo mysql_result($resultpositionjob,$r,0);?>">
</td>
<td>
<input type=text NAME="job<?PHP echo $i; ?>" id="job<?PHP echo $i; ?>" style="border: 1px solid #2608c3;color:red; width=200px" value="<? echo mysql_result($resultpositionjob,$r,1);?>">
</td>
<td>
<SELECT NAME="person<?PHP echo $i; ?>" id="person<?PHP echo $i; ?>" style="border: 1px solid #2608c3;color:red; width=200px" onchange="get(<? echo $i; ?>);">
<OPTION VALUE=0 >
<?=$optionpeople?>
</SELECT>
</td>
<td onclick="train(<? echo $i; ?>);" style="color:grey; cursor: pointer;">
<div id="training<?PHP echo $i; ?>"><font color=grey size=2></div>
</td>
<td>
</td>
</tr>
<?PHP
$i++;
$r++;
}
?>
The second page or page called by jquery, the output is:
echo
"
<table border=0 width=400>
<tr>
<td width=20>
</td>
<td width=150>
<b>Position<b>
</td>
<td>
<b>Job<b>
</td>
</tr>
";
while($line = mysql_fetch_array($result))
{
echo "
<tr>
<td>
";
?>
<input type=checkbox name="delete[]" id="delete[]" value="<?php echo $rows['id']; ?>">
<?PHP
echo "
</td>
<td>
";
echo $line['position'];
echo "
</td>
<td>
";
echo $line['job'];
echo "
</td>
</tr>
";
}
?>
<tr>
<td>
<input type=submit name="update" id="update" value="Update">
</td>
</tr>
</table>
<?PHP
}
To repeat I want the table checkbox element from the second page posted with the form data of the parent page.
Is this possible as my testing hasnt given me any luck.
Am I doing something wrong or do I need to modify the jquery code?
Thanks as always for the assistance.
There is no second page. Really - you're loading HTML content from the second page, but it's being inserted into the parent page. All content, from your browsers perspective, is in the same page. The fields should be included as long as they're inside the DOM inside the element. Use the developer tools for your browser or Firebug for Firefox to make sure that the content is placed within the form element in the DOM. The developer tools should also be able to show you exactly which variables are submitted to the server when the form is submitted.
The 'action' parameter of 'form' will indicate where the content gets submitted (and it seems you've left that part out of your HTML, so it's impossible to say if you've left out or just not included it in the paste.

How to handle a dynamic table with dojo.query()

This is going to be a meaty question because I am not sure the best way to handle this.
I have a page that contains a number of dojo inline editors, to allow users to change values, when one entry had been changes a save button will appear to prompt the user to save the information.
The page has a number of rows, contained within DIV tags, which relate to a row in a database table.
<?php if($this->userjobdetails != null) : ?>
<?php foreach($this->userjobdetails as $employment) :?>
<div id="employ_<?php echo $this->escape($employment['historyid']);?>">
<table class="employment-table">
<tr>
<td><Strong>
<span dojoType="dijit.InlineEditBox" editor="dijit.form.TextBox" onchange="markEmploymentForUpdate();" id="cmpy_<?php echo $this->escape($employment['historyid']);?>"><?php echo $this->escape($employment['employername']);?></span>
</Strong>
</td>
<td align="left"><input dojoType="dijit.form.FilteringSelect" store="rolestore" searchAttr="name" name="role" id="roleInput_<?php echo $this->escape($employment['historyid']); ?>" value="<?php echo $this->escape($employment['jobrole']);?>"></td>
<td align="left">
<span dojoType="dijit.InlineEditBox" editor="dijit.form.TextBox" onchange="markEmploymentForUpdate();" id="jtitle_<?php echo $this->escape($employment['historyid']);?>"><?php echo $this->escape($employment['jobtitle']);?></span>
</td>
<td width="15px;">
<input type="hidden" value="<?php echo $this->escape($employment['historyid']);?>" name="employid" id="employid_<?php echo $this->escape($employment['historyid']);?>"/>
<img src="<?php echo $this->baseUrl();?>/images/site/msg/small/msg-remove-small.png" border="0" onmouseover="this.style.cursor='pointer';" onclick="removeEmployer('emply_<?php echo $this->escape($employment['historyid']);?>')"/>
</td>
</tr>
</table>
</div>
<?php endforeach;?>
When the user 'saves' the page I want to then using dojo.xhrPost post the data for the elements on the page, so that the database rows are updated.
How would I go about this, having multiple 'rows'??
Thanks
Take a look at dijit.form.Form — the second example shows how to validate a form and do whatever actions you like when user submits it. AFAIK, dijit.form.Form doesn't care how many fields it has, and collects them dynamically.

Categories