Javascript Undefined with PHP & MySQL - php

I have 2 PHP pages...
INDEX.PHP
with this code:
<form method="post" action="" name="f1">
<input type="text" name='p_name' size='50'><br>
<input type="text" name='p_name2' size='50'><br>
<a href="javascript:void(0);" NAME="My Window Name" title=" My title here " onClick=window.open("index2.php","Ratting","width=550,height=170,left=150,top=200,toolbar=1,status=1,");>Click here to open the child window</a>
</form>
and INDEX2.PHP
with this avascript code:
<script langauge="javascript">
function post_value()
{
opener.document.f1.p_name.value = document.frm.c_name.value;
opener.document.f1.p_name2.value = document.frm.c_name2.value;
self.close();
}
</script>
and this PHP/HTML:
<form name="frm" method="post" action="">
<?php
$sql="SELECT * from customer";
$rs=mysql_query($sql,$conn) or die(mysql_error());
while($result=mysql_fetch_array($rs))
{
echo '<input type="text" name="c_name" size="50" value="'.$result["sequence"].'" /><br>
<input type="text" name="c_name2" size="50" value="'.$result["company"].'" /><br>
<input type=button value=\'Submit\' onclick=\'post_value();\'><br><br>';
}
?>
</form>
basically, when you go to index.php, you click the link to open the popup window index2.php and that then lists customers from a database and gives each one 2 text boxes - one for the sequence/id of the customer and the other for the company name and one submit button per row.
When the button is pressed, it runs the javascript function post_value(); which puts the values from the database/child popup window (index2.php) into the text boxes in the parent window (index.php)
when i run this code, it just puts the word undefined in box boxes on the parent page, however if i remove the while loop in php and it just displays the one row from the database of customers it works fine.
its like it doesn't like the while loop in php but i cannot work out why.
any help would be much appreciated.

Edit - I just realized that your while loop is going to generate something that looks like:
<input type="text" name="c_name" size="50" value="A1" /><br>
<input type="text" name="c_name2" size="50" value="B1" /><br>
<input type=button value=\'Submit\' onclick=\'post_value();\'><br><br>
<input type="text" name="c_name" size="50" value="A2" /><br>
<input type="text" name="c_name2" size="50" value="B2" /><br>
<input type=button value=\'Submit\' onclick=\'post_value();\'><br><br>
<input type="text" name="c_name" size="50" value="A3" /><br>
<input type="text" name="c_name2" size="50" value="B3" /><br>
<input type=button value=\'Submit\' onclick=\'post_value();\'><br><br>
This isn't going to work because you have multiple elements named "c_name" and "c_name2" within the same form. I think what you want to do is put your form element inside the while loop like this:
<?php
$sql="SELECT * from customer";
$rs=mysql_query($sql,$conn) or die(mysql_error());
$ctr = 0;
while($result=mysql_fetch_array($rs))
{
echo '<form name="frm' . $ctr . '" method="post" action="">
<input type="text" name="c_name" size="50" value="'.$result["sequence"].'" /><br>
<input type="text" name="c_name2" size="50" value="'.$result["company"].'" /><br>
<input type=button value=\'Submit\' onclick=\'post_value(' . $ctr . ');\'><br><br>'
</form>';
$ctr++;
}
?>
Notice how I created a $ctr variable so you can identify each form and how it is passed into post_value. You'll need to use that to grab the correct form like this:
<script langauge="javascript">
function post_value(ctr)
{
opener.document.f1.p_name.value = document.forms["frm" + ctr].c_name.value;
opener.document.f1.p_name2.value = document.forms["frm" + ctr].c_name2.value;
self.close();
}
</script>
By default, mysql_fetch_array returns an array with numeric keys (i.e. 0, 1, 2, etc). If you want to retrieve records by their column name, you need to use:
while ($result = mysql_fetch_array($rs, MYSQL_ASSOC))
Look at example 3 here:
http://php.net/manual/en/function.mysql-fetch-array.php

Related

How to insert data from a form into a table in php without using databsaes?

I need to create a table of 17 rows where each row contains information such as row number, name, surname, email and birthday. The data is provided by this form:
<form action="index.php" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
After clicking submit the data should be displayed in the nth row of the table(row number one if it is the first "pack" of data submitted, number two if its the second and so on). This problem could easely be solved using databases but i cannot use them(by professors order).
I tried to create an array than push values into it like this:
$array_name = array();
$name = $_POST["name"];
array_push($array_name, $name);
This approach doesn't work(the index of the array stays 0 alla of the time so it keeps replacing the first value again and again) and manually incrementing the index counter of the array doesn't work either.
Normally one should use a database approach but your professor explicitly forbids it.
There are many other ways to do it. (store as TEXT/JSON/CSV file or localstorage / cookies), etc. For me I would use session to do the job
declare a session variable which is an array
if user submits the form, store the POST data into another array (subarray) containing name, surname, birthday, email
add the subarray into the main session variable array
print it out at the end as a table
So the PHP will be:
<?php
session_start();
?>
<form action="#" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="email" placeholder="email" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
<?php
if (!isset($_SESSION["arr"])){
$_SESSION["arr"]=array();
}
if ($_POST) {
$subarray=array(
"name"=>$_POST["name"],
"surname"=>$_POST["surname"],
"birthday"=>$_POST["birthday"],
"email"=>$_POST["email"]
);
$_SESSION["arr"][]=$subarray;
}
echo "<table border=1><tr><td>Name<td>Surname<td>Email<td>Birthday";
foreach($_SESSION["arr"] as $suba){
echo "<tr><td>" . $suba["name"] ;
echo "<td>" . $suba["surname"] ;
echo "<td>" . $suba["email"] ;
echo "<td>" . $suba["birthday"] ;
}
echo "</table>";
?>
However, if you need the data to be persistent (even after the user closes the browser), then you need to store the data say in file format or cookies, etc.
If you need to save data persistent and using file to save data is acceptable, i'd use something like that:
<?php
$file = 'path/to/file.txt';
$data = json_decode(file_get_contents($file), true);
if ($_POST) {
$data[] = [
"name" => $_POST['name'],
"surname" => $_POST['surname'],
"emailbirthday" => $_POST['emailbirthday'],
"birthday" => $_POST['birthday']
];
}
file_put_contents($file, json_encode($data));
?>
<form action="index.php" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
</form>
<table>
<tr>
<th>Name</th>
<th>Surname</th>
<th>Emailbirthday</th>
<th>Birthday</th>
</tr>
<?php
foreach ($data as $row) {
print '<tr>
<td>'.$row['name'].'</td>
<td>'.$row['surname'].'</td>
<td>'.$row['emailbirthday'].'</td>
<td>'.$row['birthday'].'</td>
</tr>';
}
?>
</table>
You can use the post values of hidden fields:
<form action="" method="post">
<input type="text" name="name" placeholder="name" />
<input type="text" name="surname" placeholder="surname" />
<input type="text" name="emailbirthday" placeholder="emailbirthday" />
<input type="text" name="birthday" placeholder="birthday(dd/mm/aaa)" />
<button type="reset">Reset Form</button>
<button type="submit">Submit Form</button>
<?php
if($_POST["names"] == "")
{
$value = $_POST["name"];
}
else
{
$value = $_POST["names"]."-".$_POST["name"];
}
?>
<input type="text" name="names" style='display:none;' value="<?php echo $value ?>">
</form>

cannot retrieve input field value using PHP $_POST array

I cannot get the $_POST['value'] after form submission.
I have used javascript to assign a value to an input field.
code:
function updateValue(pid, value){
// this gets called from the popup window and updates the field with a new value
document.getElementById(pid).value = value;
}
The above function is called by a popup widow to assign a value to my input field: pid
Here is the form script:
<form action="test.php" method="post">
<input type="text" name="project_name" id="pid" disabled="disabled" />
<input type="submit" id="search" name="search" value="Search" />
</form>
In my test.php, I have done:
include 'functions.php'; //Has the connection script
if (isset($_POST['search'])){
echo $project_id = $_POST['project_name'];
$sql = mysql_query("SELECT * from item
where category like '$project_id %'
");
echo $num = mysql_num_rows($sql);
}
But I am getting the error: Undefined index: project_name
Disabled inputs doesnt post. Use hidden input like this:
<form action="test.php" method="post">
<input type="text" name="project" disabled="disabled" />
<input type="hidden" name="project_name" id="pid" />
<input type="submit" id="search" name="search" value="Search" />
</form>
Try filling the hidden field when you set the value into disabled field
<form action="test.php" method="post">
<input type="text" name="project" id="pid" onchange="document.getElementById("pid-new").value=document.getElementById("pid").value" disabled="disabled" />
<input type="hidden" id="pid-new" name="project_name" />
<input type="submit" id="search" name="search" value="Search" />
</form>
your project_name input field is disabled.
remove this attribute then it will work.
It's because disabled attributes aren't passed along the form requests.
If you're setting the value through javascript, and that part works, replace your text input with this:
<input type="hidden" name="project_name" id="pid" />
this will work

form and file upload to two different controllers

I have a form that I want to submit with one submit button.
However my action to upload a file is a different controller then the database posts. it looks like this...
<form method="post" action="/admin/upholstery_product/add/">
<h3>Add a Product</h3>
Frame: <input type="text" name="productname" /><br>
Parent Category:
<select name="category">
<?php
foreach($cats AS $cat){
$sel = ($curCat->category_id == $cat->category_id) ? 'selected' : '';
echo "<option value='".$cat->category_id."' ".$sel.">" . $cat->category_name . "</option>\n";
}
?>
</select><br />
Family: <input type="text" name="family" /><br>
Width: <input type="text" name="width" size="6" /><br>
Height: <input type="text" name="height" size="6" /><br>
Depth: <input type="text" name="depth" size="6" /><br>
Seat Width: <input type="text" name="seat_width" size="6" /><br>
Seat Height: <input type="text" name="seat_height" size="6" /><br>
Seat Depth: <input type="text" name="seat_depth" size="6" /><br>
Arm Height: <input type ="text" name="arm_height" size="6" /><br>
Features: <textarea cols="40" rows="20" name="features"></textarea><br>
<form method="post" action="/upload/product_image_upload">
Image File: <input type="file" name="image" id="image"/><br>
</form>
<form method="post" action="/upload/product_image_upload">
Thumbnail File: <input type="file" name="thumbnail" id="thumbnail"/><br>
</form>
<form method="post" action="/upload/pdf_upload">
PDF File: <input type="file" name="pdf" id="pdf"/><br>
</form>
Status: <select name="status">
<option value="active">Active</option>
<option value="inactive">Inactive</option>
</select> <br>
<input type="submit" name="submit" value="Add Product" /><br>
</form>
is there a way to post the file actions to one controller and the submit to my other controller with a single submit button? right now the code doesnt work.
What you want to do is, strictly speaking, not possible: You have two separate forms on one page, andf you want to submit both simultanously.
The main problem here is this: The result of a submitted form is a new page. Different actions = different pages. Which one do you want to display?
Workaround: Submit both the file and the data to the same script; if the handlers need to be separate, make the first handler post the data to the second handler "behind the scenes".

Auto submit data to MySQL?

I am teaching myself code, and after going over PHP & MySQL tutorials, I'm still a little unsure.
I want to create a page in which the user ticks relevant checkboxes, saves the data, and can log back in another time and the ticks are saved.
I've learned how to use data that is in MySQL, but how is data auto-submitted by the user? That's got me stumped...
You need to use a form:
http://www.tizag.com/htmlT/forms.php
<form method="post" action="/your/php/script.php">
Name: <input type="text" size="10" maxlength="40" name="name"> <br />
Password: <input type="password" size="10" maxlength="10" name="password">
<input type="submit" value="Save"/>
</form>
This isn't really a question than can be answered simply, but here's the Simple answer.
First, put your checkboxes in a form:
<form action="page2.php" method="post">
<input type="checkbox" name="cb1" value="SomeValue">SomeValue</input>
</form>
Then, in page2.php, put the data (which is in the $POST array) into the MySql database using the mysql* functions (mysql_connect, mysql_select_db, mysql_query, etc).
Here is an example.
<?php
// Make a MySQL Connection
$query = "SELECT * FROM example";
$result = mysql_query($query) or die(mysql_error());
$row = mysql_fetch_array($result) or die(mysql_error());
?>
<form action="" method=post>
<b>Company Name</b> <input name="CompanyName" type="text" value="<?php echo $row['company'] ?>" /><br>
<b>First Name</b> <input name="firstname" type="text" value="<?php echo $row['firstname'] ?>"/><br>
<b>Last Name</b> <input name="lastname" type="text" value="<?php echo $row['lastname'] ?>" /><br>
<input type="submit" value="Submit">
</form>

How to pass variables in php using GET without type?

<form method="get" action=..... >
Food <input name="food" type="text" size="1" />
Pizza <input name="pizza" type="text" size="2" />
Drink <input name="drink" type="text" size="2"/>
Now I want to pass a third variable which is a concatenation of food+pizza+drink in the URL
I don't want to create a new <input name="total" type="text" size="2"/>
Is this possible?
EDIT:
I want to do it before submitting the values.
I will have a url like
http://www.abc.com/&food=tasty&pizza=cheeze&drink=pepsi
I want the url to be
http://www.abc.com/&food=tasty&pizza=cheeze&drink=pepsi&total=tastypizzacheezepepsi
Why don't just do it on the server side?
$allTogether = $_GET["food"] . $_GET["pizza"] . $_GET["drink"];
Well once it is submitted just concatenate (after validation)
$total = $_GET['food'] + $_GET['pizza'] + $_GET['drink'];
//assuming the _GETs were numbers, otherwise use `.` to concatenate
Or if you don't want to do that, you would have to do some JavaScript magic on the client side (but that is not always trustworthy)
Assuming that you don't like the answers above using PHP to concatenate, you can use Javascript to do that.
<script type="text/javascript">
function addTotal(food, pizza, drink) {
document.getElementById("total").value = food + drink + pizza;
}
</script>
<form method="get" name="fname" action="" onSubmit="addTotal(document.fname[0].value,document.fname[1].value,document.fname[2].value)" >
Food <input name="food" type="text" size="1" />
Pizza <input name="pizza" type="text" size="2" />
Drink <input name="drink" type="text" size="2"/>
<input type="hidden" name="total" id="total" value="" />
</form>
And in your PHP file, you now should get
$_GET['food'];
$_GET['pizza'];
$_GET['drink'];
$_GET['total'];
This should do the trick
$sep = ""; //if you want a space in between each just change this to a space.
$concat = implode($sep, array($_GET['food'], $_GET['pizza'], $_GET['drink']));

Categories