I am having some trouble sending data from a form to a function
Here is my form:
echo "<form id='AddCompany' action='' method=post>";
echo "<table>";
echo "<tr>";
echo "<th colspan='2'>Opret nyt firma</th>";
echo "</tr>";
echo "<td>Firma Navn:<td><input type='text' name='Name' /></td>";
echo "</td></tr>";
echo "<td>Adresse:<td><input type='text' name='Address' /></td>";
echo "</td></tr>";
echo "<td>Postnr.:<td><input type='text' name='Zipcode' /></td>";
echo "</td></tr>";
echo "<td>By:<td><input type='text' name='City' /></td>";
echo "</td></tr>";
echo "<td>Land:<td><input type='text' name='Country' /></td>";
echo "</td></tr>";
echo "<td>Tlf:<td><input type='text' name='Phone' /></td>";
echo "</td></tr>";
echo "<td>Slogan:<td><input type='text' name='Slogan' /></td>";
echo "</td></tr>";
echo "<td>Catch All Email:<td><input type='text' name='Email' /></td>";
echo "</td></tr>";
echo "<td>Logo 1:<td><input type='FILE' name='Logo1' /></td>";
echo "</td></tr>";
echo "<td>Lille Logo:<td><input type='FILE' name='SmallLogo' /></td>";
echo "</td></tr>";
echo "<td>Logo 2:<td><input type='FILE' name='Logo2' /></td>";
echo "</td></tr>";
echo "<td colspan='2'><input type='submit' value='Opret Firma' />";
echo "</form>";
echo "</td></tr>";
echo "</tr>";
echo "</table>";
I want to send the data to this function
function insertRecord ($fieldarray)
{
$this->errors = array();
global $dbconnect, $query;
$dbconnect = db_connect($this->dbname) or trigger_error("SQL", E_USER_ERROR);
$fieldlist = $this->fieldlist;
foreach ($fieldarray as $field => $fieldvalue) {
if (!in_array($field, $fieldlist)) {
unset ($fieldarray[$field]);
} // if
} // foreach
$query = "INSERT INTO $this->tablename SET ";
foreach ($fieldarray as $item => $value) {
$query .= "$item='$value', ";
} // foreach
$query = rtrim($query, ', ');
return;
} // insertRecord
I just realised you might need this bit of code also:
class Company extends Default_Table
{
// additional class variables go here
function __construct ()
{
$this->tablename = 'Company';
$this->dbname = 'oop';
$this->rows_per_page = 15;
$this->fieldlist = array('ID', 'Name', 'Address','Zipcode','City','Country','Phone','Slogan','CatchAllEmail','Logo1','LogoSmall','Logo2');
$this->fieldlist['ID'] = array('pkey' => 'y');
} // __construct
} // Company
Where do I call the function and which variables should I send with it?
I have tried onclick=insertRecord() which doesn't seem to work, and I am thinking it is because I need to insert a variable, which I think needs to be an array of the form data as the function is declared with an array.
As you can see I am pretty much a tenderfoot at this.
I have found out the following:
If I echo my $query after the foreach loop in the insertRecord function I see the query like so:
INSERT INTO Company SET Name='1', Address='2', Zipcode='3', City='4', Country='5', Phone='6', Slogan='7', CatchAllEmail='8', Logo1='', LogoSmall='', Logo2=''
However still nothing is being inserted, I have tried this on 2 servers and with users I know have insert rights however nothing is getting inserted.
No need to use function but you can do like,
remove action ="" from <form>.
then check like,
if($_POST){
//your function logic
// get variable data like
echo $_POST["Name"];
}
Enjoy!
Please take this in the most friendly way, I recommend that you pick up a book or read a tutorial about PHP/MySQL/HTML/JavaScript.
I'll do my best to explain this without going outside the scope of this Q&A site.
What you have in the first part of the code is an HTML form echoed by a PHP script, so the HTML form is now in the client's browser.
What you're trying to do with onclick=insertRecord() is binding an event handler written in PHP (server side) to an event fired in browser (client side).
How to solve your problem?
You need to POST this form to the PHP script containing the insertRecord() function. First you need to modify the action attribute in your <form> and point it to the .php script that has this function, then you simply do something like this:
$cmpny = new Company();
$cmpny->insertRecord($_POST);
You need to have some way of getting your POST data into the $fieldarray. Could be something as simple as:
function insertRecord ($fieldarray) {
//the function you have above
}
insertRecord($_POST);
Of course this is depending on how the insertRecord function is set up to work and if it will recognize all the POST data in the way you have things set up.
Related
I am generating a list of buttons with the id being a value extracted from a database. Then I want to take this id and display. But, when I try to do that, I get an error. Can some one tell me what I'm doing wrong here.
Button generation
//This function will display items
function showItems($sqlString)
{
$result = mysqli_query($this->connectToDb(), $sqlString);
//var_dump($result);
if(mysqli_num_rows($result) > 0)
{
foreach ($result as $row)
{
echo "<div class='div_item'>";
echo "<img src='../images/uploads/".$row['It_image']."' style='width:200px;height:150px;'>"."<br>";
echo "IT CODE: ".$row['It_code']."<br>";
echo "ITEM: ".$row['It_name']."<br>";
echo "DESC: ".$row['It_desc']."<br>";
echo "QTY AVAIL: ".$row['qty']."<br>";
echo "PRICE: ".$row['price']."<br>";
echo "<form enctype='multipart/form-data' action='' method='POST'>";
echo "<button type='submit' name='id' id='".$row['It_code']."'>Buy</button>";
echo "</form>";
echo "</div>";
}
}
}
Displaying the ID when the respective button is clicked
//get id of the button
if (isset($_POST['id']))
{
echo $_GET['id'];
}
Error
Pass it inside value value='".$row['It_code']."'
echo "<button type='submit' value='".$row['It_code']."' name='id' id='".$row['It_code']."'>Buy</button>";
Try to var_dump($result), the error message tells us it can't find the key "id". So var_dump could give us more information about what is missing.
It could be because the form method is post, that data will be stored in the $_POST['id'] and not $_GET['id']
First of all I am kind of new to PHP.
I've been asked to change up a bit of code and add the option to see the status of a field and mark the rows which are completed. So I've added a status field to my MySQL database which has a standard value of 0. Then on button click I'd like this to change to the value 1. Based on this I can either project a cross glyph icon with a button to update this, or project a checkmark so that the status is "done".
Now I'm having issues with the update part. I just cannot seem to get it to work with clicking the button and updating only that row. Field "prdh_num" is my unique value if that is usefull.
Here's the code I work with:
function uren_error(){
global $mysql;
$sql = "
SELECT *
FROM uren_error, medw
WHERE uren_error.uren_datum between adddate(now(),-14) and now() AND medw.medw_num = uren_error.medw_num
ORDER BY uren_error.prdh_num";
$query = $mysql->query($sql);
echo "<h1>Niet in MKG verwerkte uren van de afgelopen 14 dagen</h1>";
echo "<div class='row' id='urenTabel'>";
echo "<div class='col-xs-0 col-md-0'></div>";
echo "<div class='col-xs-12 col-md-12'>";
echo "<table class='table'>";
echo "<thead>";
echo "<th>Verwerkingsdatum</th>";
echo "<th>Medewerker</th>";
echo "<th>Productieorder</th>";
echo "<th>Productieorder regel</th>";
echo "<th>Bewerking</th>";
echo "<th>Duur</th>";
echo "<th>Status</th>";
echo "<th>Actie</th>";
echo "</thead>";
while($row = mysqli_fetch_array($query)){
$hours = floor($row['uren_tijd_man_std'] / 3600);
$mins = floor($row['uren_tijd_man_std'] / 60 % 60);
echo "<tr>";
echo "<td>" .$row['uren_datum']. "</td>";
echo "<td>" .$row['medw_roepnaam'] . " " . $row['medw_tussenvoegsel'] . " " . $row['medw_naam'] . "</td>";
echo "<td>" .$row['prdh_num']. "</td>";
echo "<td>" .$row['prdr_num']. "</td>";
echo "<td>" .$row['bewerk_num']. "</td>";
echo "<td>" .$hours.":".$mins. "</td>";
if($row['uren_status'] == "0"){
echo "<td><div class='glyphicon glyphicon-remove' style='color:red'></div></td>";
echo "<td><form action'' method='POST'><input type='submit' name=".$row['prdh_num']."></input></form></td>";
} else if($row['uren_status'] == "1"){
echo "<td><div class='glyphicon glyphicon-ok' style='color:green'></div></td>";
}
echo "</tr>";
}
echo "</table>";
}
my update code so far:
$productieorder = $row['prdh_num'];
$updateStatus = "UPDATE uren_error SET uren_status = 1 WHERE prdh_num=".$productieorder."";
$query2 = $mysql->query($updateStatus);
In more simple way you can use <a> tag to update your record ,instead of <form> , just attached your parameter which you need to passed . i.e :
echo "<td><a href='currentphppagename.php?prdh_num=".$row['prdh_num']."'></a></td>";
And to get prdh_num use $_GET on same page i.e :
//check if have some value or not
if (isset($_GET['prdh_num'])) {
//getting value passed in url
$productieorder = $_GET['prdh_num'];
$updateStatus = "UPDATE uren_error SET uren_status = 1 WHERE prdh_num=".$productieorder."";
$query2 = $mysql->query($updateStatus);
}
And other way using form you can have one hidden field and assign row value to that :
echo "<td><form action='' method='POST'><input type='hidden' value=".$row['prdh_num']." name='prdh_num'/><input type='submit' name='submit'></input></form></td>";
Now on click of submit check below on same page :
//check if have some value or not
if (isset($_POST['submit'])) {
//getting value passed in url
$productieorder = $_POST['prdh_num'];
$updateStatus = "UPDATE uren_error SET uren_status = 1 WHERE prdh_num=".$productieorder."";
$query2 = $mysql->query($updateStatus);
}
You can do this with javascript. You should put "ondblclick" event on tr tag.
<tr ondblclick="Update(rowno)" />
And in javascript tag, there must be a function like
<script type="text/javascript">
function Uptdate(row) {
window.location.href ="update.php?row="+row;
}
</script>
First of all i start writing php this week and there may be unnecessary lines:)
I'm just trying figuring out the logic. For now everything went fine(thx to stackoverflow). Until,
In my foreach loop statement i put submit button, I added the db id after button name. So i put the id after $_POST too. But the problem is only the first submit button works. When i click the others nothing happens.
Thanks for your help. (btw i tried all other answers for foreach button issues. didn't help)
if (isset($_POST['arama'])) {
$ara = trim(strip_tags($_POST["ara"]));
$duzelt = trim(strip_tags($_POST["duzelt"]));
$id = $_SESSION["id"];
if (!empty($ara)) {
echo '<div class="form-style-10">';
echo '<table><tr>';
echo "<th>İsim</th><th>Cep Telefonu</th><th>Sabit Telefonu</th> </tr>";
$ara1 = '%'.$ara.'%';
$sql = $db -> query("SELECT * FROM rehber WHERE k_id='".$id."' AND isim LIKE '%$ara%'");
$yok = $sql->rowCount();;
if ($yok != 0) {
echo "<form action='' method='POST'>";
foreach ($sql as $dizi) {
$iden=$dizi[id];
echo "<tr><td><input type='text' name='isim1' value='$dizi[isim]'></td>";
echo "<td><input type='text' name='cep1' value='$dizi[cepno]'></td>";
echo "<td><input type='text' name='ev1' value='$dizi[evno]'></td>";
echo "<input type='hidden' name='id2' value='$iden'>";
echo "<td><input type='submit' name='duzelt".$iden."' value='duzelt'></td></form></tr>";
}
echo "</table>";
echo "</div>";
}else{
echo '<div class="form-style-10" style="background-color:#f04"><div class="section" style="color:#FFFC00">'.$ara.' adında bir kullanıcı kayıtlı değildir.</div></div>';
header("refresh:3;rehber.php?mr=arama");
}
}
else{
echo '<div class="form-style-10" style="background-color:#f04"><div class="section" style="color:#FFFC00">Arama kutusu boş. Lütfen aramak istediğiniz kişinin adını yazınız.</div></div>';
header("refresh:3;rehber.php?mr=arama");
}
}
$buton = "duzelt".$_POST["id2"];
if (isset($_POST[$buton]) && $_POST[$buton]) {
$duz = $_POST[$buton];
if (!empty($duz)) {
echo $_POST["isim1"];
echo $_POST["cep1"];
echo $_POST["ev1"];
echo $_POST["id2"];
echo $buton;
$sql1 = $db -> prepare("UPDATE rehber SET isim = ?, cepno = ?, evno = ? WHERE id = ?");
$sql1 -> execute(array($_POST["isim1"], $_POST["cep1"], $_POST["ev1"], $_POST["id2"]));
echo "Kayıt başarıyla tamamlanmıştır.";
header("refresh:3;rehber.php?mr=duzen");
}else{
echo "kaydedilecek veri yok";
}
}
The only real issue that I can see if that the initial form constructor appears outside of the form element, whilst the form element is closed in the foreach loop. I would move the form constructor into the foreach loop. Also, as a secondary, you are using id as a constant value in your $iden constructor. This is easily resolved, but it seems you really want the index, which you can get from the foreach loop.
Please observe:
foreach ($sql as $iden => $dizi) { // <-- $iden is now the index
//$iden=$dizi[id]; <- no longer required
echo "<form action='' method='POST'>"; // <--form created inside loop
echo "<tr><td><input type='text' name='isim1' value='$dizi[isim]'></td>";
echo "<td><input type='text' name='cep1' value='$dizi[cepno]'></td>";
echo "<td><input type='text' name='ev1' value='$dizi[evno]'></td>";
echo "<input type='hidden' name='id2' value='$iden'>";
echo "<td><input type='submit' name='duzelt".$iden."' value='duzelt'></td></form></tr>";
}
Now you have the form being constructed within the loop, and the index is properly being passed along.
I have a button that generates after each table row is generated in the loop, the name of each consecutive button is generated by $a++ variable. How do i use the $_POST method on my edit_contact.php page so i can use the variable from the $_POST array?
The variable is stored in the $_POST array, i have checked with Print_r($_POST); for example when i click on the third row edit button of the table, it will display as:
Array ( [3] => edit )
Here is the code of the loop on my list_contact.php page:
$a = "0";
// print whether success or not
if ($rst)
{
if (mysql_num_rows($rst)>0) // chech there are records
{
echo "<form name=addcontact method=post action=edit_contact.php>";
echo "<table border=\"1\" cellspacing=\"0\">";
/*** print out feild names ***/
while ($row = mysql_fetch_array($rst)) // fetch each row
{
echo "<tr>";
for ($i=0; $i<mysql_num_fields($rst); $i++) //for ech row print out field values
{
echo "<td>" . $row[$i] . "</td>";
}
echo "<td>" . "<input id=button type=submit name=" . $a++ . " value=Edit" . "</td>";
echo "</tr>";
}
echo "</table>";
echo "</form>";
}
else
{
echo "There are no records in the database";
}
}
And here is the code i am having trouble with on my edit_contact.php:
$qry = "SELECT * FROM contacts WHERE ContactID = " . $_POST;
How can i get that post to reflect just my variable? ie 3
You can do it once. You don't need any more fields. Just use foreach to access its key
foreach($_POST as $key => $value){
if(strtolower(trim($value)) == "edit"){ // Validate if editing being sent
// Display it if true
echo $key; // and this is the variable you want
}
}
you could use a hidden input field so instead of:
echo "<td>" . "<input id=button type=submit name=" . $a++ . " value=Edit" . "</td>";
you could do:
echo '<td><form method="post"><input type="hidden" name="ContactID" value="'.($a++).'"><input id="button" type="submit" value="Edit"></form></td>';
then retrieve the hidden input field like:
$ContactID = $_POST['ContactID'];
Note: You will still need to properly escape your POST data before using it for SQL queries, but hopefully this will point you in the right direction.
Restructure the code so that the name is actually a constant, and the value is dynamic.
echo "<td><input id=button type=submit name=\"edit\" value=\"" . $a++ . "\"></td>";
This way you can access it with:
$_POST['edit'];
And it will yield the value of: value=\"" . $a++ . "\" for the button that was clicked.
Which will return something like 3, as you desire.
I've been trying think of a way to do this. I want it to where users can check off items, hit submit and it goes to the code on the next page and deletes all of the checked items from the database. Problem one is that in the post its only sending over the last checked item. Here is how I have it set up right now.
echo "<form name='fm1' METHOD ='POST' ACTION ='displaydelete.php' > ";
//Draws up the table headers
echo "";
echo "";
echo "Fund Number ";
echo "Hours ";
echo "Percentage";
echo "Delete";
echo "";
//While there are query results data is pushed into table cells
while ($row = mysql_fetch_array($queryResult2))
{
$hours = $row['hours'];
$percentage = $hours / 160 * 100;
echo "<tr>";
echo "<td>";
echo $row['funnumber'];
echo "</td>";
echo "<td>";
echo $hours;
echo "</td>";
echo "<td>";
echo $percentage ."%";
echo "</td>";
echo "<td>";
echo "<input type='checkbox' name='id' value='$row[id]'/>";
echo "</td>";
echo "</tr>";
}
//End of tabel
echo "</table>";
echo" ";
echo "";
What I would like to do is push all of the items into a variable and maybe delete them that way. I'm not really sure how you would handle multiple deletes. I'm doing my delete like this for something else if this helps any.
$query = "DELETE FROM users
WHERE ninenumber = '$ninenumber'";
$result = mysql_query($query)
or die("Query Failed: " .mysql_error());
mysql_close($conn);
In your form:
<input type='checkbox' name='id[]' value='$row[id]'/>
Then, in the file you post to:
if(is_array($_POST['id'])){
foreach($_POST['id'] as $id){
...do something to $id;
}
}
Instead of this:
echo "<input type='checkbox' name='id' value='$row[id]'/>";
You need this:
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
Note the difference. I added [] after the input name. This tells the client and server that there are multiple inputs with that name. $_POST['id'] will be an array you can loop through on the next page.
foreach ($_POST['id'] as $checkbox) {
// DELETE FROM users WHERE ninenumber = $checkbox
}
isset, is_array, and mysql_real_escape_string omitted for brevity.
In the form-generating code, make the name in the html have" []" after it:
...
echo "<input type='checkbox' name='id[]' value='$row[id]'/>";
...
Then, in the form-reading code, your post'ed id will be an array.
$id_array = isset($_POST['id']) && is_array($_POST['id']) ? $_POST['id'] : array();
foreach( $id_array as $id ) {
$query = "DELETE FROM users WHERE ninenumber = '" . mysql_real_escape_string($id) . "'";
// execute the delete query
}
Putting [] after the name of a control will turn it into an array in the superglobal that you can then iterate over to get all the values from.
You need to have the same name for all of your checkboxes, then all values are passed as array POST variable.
<input type='checkbox' name='id[]' value='$row[id]'/>
Change
name=id
to
name=id[]
this will then give you an array.