...

View Full Version : How to insert multiple checkbox values into one mysql table (field) using php



mohammedsali
08-06-2012, 09:41 PM
Hi Guys,

Looking for some desperately.

I am new to php, with a lot search I have been able to put together some form of working script. The problem I am now facing is I have multiple checkboxes for the users to select from but the selected checkbox value does not get inserted into the table instead shows as “Array”. With some help I plan to get all the selected checkbox values into one table.

I have two files one "testpage.html" which contains the form and the other "test_post.php" to process the form data. Please find below html and php file codes. Have to // in front of every code in html so the code can be seen.

Really appreciate your help in advance :p.

HTML form:

<!DOCTYPE html>
<html>
<body background="blue">
<form action="test_post.php" method="post">

Full Name: <input name="FullName" type="text" id="FullName" /><br />
<br />
Number: <input name="Number" type="text" id="Number" /><br />
<br />
Email Address: <input name="EmailAddress" type="text" id="EmailAddress" /><br /><br />
<br />
Address: <input name="Address" type="text" id="Address" /><br />
<br />
Which animal do you want to keep?<br />
<input type="checkbox" name="petathome[]" value="Dog" />Dog<br />
<input type="checkbox" name="petathome[]" value="Cat" />Cat<br />
<input type="checkbox" name="petathome[]" value="Lion" />Lion<br />
<input type="checkbox" name="petathome[]" value="Tiger" />Tiger<br />
<input type="checkbox" name="petathomel[]" value="Leopard" />Leopard

<input type="submit" name="submit" value="Submit" />

</form>
</body>
</html>



PHP code:
<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$FullName=$_POST['FullName'];
$MobileNumber=$_POST['Number'];
$EmailAddress=$_POST['EmailAddress'];
$Address=$_POST['Address'];
$petathome=$_POST['petathome'];

// Insert data into mysql
$sql="INSERT INTO $tbl_name(FullName,Number, EmailAddress, Address, petathome)VALUES('$FullName', '$Number', '$EmailAddress', '$Address', '$petathome')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='testpage.html'>Back to main page</a>";
}

else {
echo "ERROR";
}
?>

<?php
// close connection
mysql_close();
?>

mlseim
08-06-2012, 11:06 PM
$petathome=$_POST['petathome'];

// You have to loop through the array of checked box values ...
$pets="";
foreach($petathome as $entry){
$pets .= $entry.",";
}

// Insert data into mysql
$sql="INSERT INTO $tbl_name(FullName,Number, EmailAddress, Address, petathome)VALUES('$FullName', '$Number', '$EmailAddress', '$Address', '$pets')";

mohammedsali
08-06-2012, 11:39 PM
Hi Mlseim,

Thanks a ton for the reply.

Still seem to be facing a problem, after entering the above into the php file and get the message:

ERROR

Any suggestions?

Thanks & Regards,
mohammedsali

mlseim
08-07-2012, 01:28 PM
Repost your entire script again with the changes made.

mohammedsali
08-07-2012, 01:59 PM
Hi Mlseim,

Thank you for taking the time to help me :D

The html and php code is as below.

HTML form:

<!DOCTYPE html>
<html>
<body background="blue">
<form action="test_post.php" method="post">

Full Name: <input name="FullName" type="text" id="FullName" /><br />
<br />
Number: <input name="Number" type="text" id="Number" /><br />
<br />
Email Address: <input name="EmailAddress" type="text" id="EmailAddress" /><br /><br />
<br />
Address: <input name="Address" type="text" id="Address" /><br />
<br />
Which animal do you want to keep?<br />
<input type="checkbox" name="petathome[]" value="Dog" />Dog<br />
<input type="checkbox" name="petathome[]" value="Cat" />Cat<br />
<input type="checkbox" name="petathome[]" value="Lion" />Lion<br />
<input type="checkbox" name="petathome[]" value="Tiger" />Tiger<br />
<input type="checkbox" name="petathomel[]" value="Leopard" />Leopard

<input type="submit" name="submit" value="Submit" />

</form>
</body>
</html>



PHP code:
<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$FullName=$_POST['FullName'];
$MobileNumber=$_POST['Number'];
$EmailAddress=$_POST['EmailAddress'];
$Address=$_POST['Address'];
$petathome=$_POST['petathome'];

// You have to loop through the array of checked box values ...
$pets="";
foreach($petathome as $entry){
$pets .= $entry.",";
}

// Insert data into mysql
$sql="INSERT INTO $tbl_name(FullName, Number, EmailAddress, Address, petathome)VALUES('$FullName', '$Number', '$EmailAddress', '$Address', '$pets')";

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='testpage.html'>Back to main page</a>";
}

else {
echo "ERROR";
}
?>

<?php
// close connection
mysql_close();
?>

Please let me know if you want me to start all over again. With fresh table and form, php file. If so please let me know what is to be done.

Thank you once again :)

Regards,
mohammedsali

mlseim
08-07-2012, 05:03 PM
Try this:



<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$FullName=$_POST['FullName'];
$MobileNumber=$_POST['Number'];
$EmailAddress=$_POST['EmailAddress'];
$Address=$_POST['Address'];
$petathome=$_POST['petathome'];

// Loop through the array of checked box values ...
$pets="";
$flag=0;
foreach($petathome as $entry){
$pets .= $entry."|";
$flag=1;
}
if($flag==1){
$pets=rtrim($pets);
}

// Insert data into mysql
$sql="INSERT INTO $tbl_name(FullName, Number, EmailAddress, Address, petathome)VALUES('$FullName', '$Number', '$EmailAddress', '$Address', '$pets')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='testpage.html'>Back to main page</a>";
}

else {
echo "ERROR";
}
?>

<?php
// close connection
mysql_close();
?>






.

mohammedsali
08-07-2012, 06:01 PM
Hi mlseim,

That worked like a charm. Thanks a ton :D

Need one more help with the checkbox is it possible to have multiple check boxes and have one check box with a text filled for user to add their choice which is not part of the check boxes. And this check box, text filed data is added along with the other checkbox values, data.

Thanks again you are a life saver :D

Regards,
mohammedsali

mlseim
08-07-2012, 07:35 PM
You'll need a text box.
You will not need to add another checkbox though.
If they put text in the box, that means they want it added to the list.
If they leave the text box blank, it won't get added.

Try this change first.
I'm hoping that using the same name ("petathome[]") for the textbox
will append it to the array, along with the checkbox values.



<!DOCTYPE html>
<html>
<body background="blue">
<form action="test_post.php" method="post">

Full Name: <input name="FullName" type="text" id="FullName" /><br />
<br />
Number: <input name="Number" type="text" id="Number" /><br />
<br />
Email Address: <input name="EmailAddress" type="text" id="EmailAddress" /><br /><br />
<br />
Address: <input name="Address" type="text" id="Address" /><br />
<br />
Which animal do you want to keep?<br />
<input type="checkbox" name="petathome[]" value="Dog" />Dog<br />
<input type="checkbox" name="petathome[]" value="Cat" />Cat<br />
<input type="checkbox" name="petathome[]" value="Lion" />Lion<br />
<input type="checkbox" name="petathome[]" value="Tiger" />Tiger<br />
<input type="checkbox" name="petathome[]" value="Leopard" />Leopard<br />
Also: <input type="text" name="petathome[]"><br />
<input type="submit" name="submit" value="Submit" />

</form>
</body>
</html>



You are allowing user (form) values to be put into your MySQL table.
That can be a security risk (SQL Injections) ... so escape them first ...



// Get values from form
$FullName=mysql_real_escape_string($_POST['FullName']);
$MobileNumber=mysql_real_escape_string($_POST['Number']);
$EmailAddress=mysql_real_escape_string($_POST['EmailAddress']);
$Address=mysql_real_escape_string($_POST['Address']);
$petathome=mysql_real_escape_string($_POST['petathome']);



EDIT,
I noticed a type on your Leopard checkbox line.
I fixed it in my form (example above).
It might still be bad in your form.

<input type="checkbox" name="petathomel[]" value="Leopard" />Leopard



.

mohammedsali
08-07-2012, 08:28 PM
Hi mlseim,

Thanks again :D

There is a error when processing the script, all the fields expect the petathome fields are filled.

The error is:
Warning: mysql_real_escape_string() expects parameter 1 to be string, array given in /database/test_post.php on line 17
Warning: Invalid argument supplied for foreach() in /database/test_post.php on line 22

The html code is:

<!DOCTYPE html>
<html>
<body background="blue">
<form action="test_post.php" method="post">

Full Name: <input name="FullName" type="text" id="FullName" /><br />
<br />
Number: <input name="Number" type="text" id="Number" /><br />
<br />
Email Address: <input name="EmailAddress" type="text" id="EmailAddress" /><br /><br />
<br/>
Address: <input name="Address" type="text" id="Address" /><br />
<br />
Which animal do you want to keep?<br />
<input type="checkbox" name="petathome[]" value="Dog" />Dog<br />
<input type="checkbox" name="petathome[]" value="Cat" />Cat<br />
<input type="checkbox" name="petathome[]" value="Lion" />Lion<br />
<input type="checkbox" name="petathome[]" value="Tiger" />Tiger<br />
<input type="checkbox" name="petathome[]" value="Leopard" />Leopard<br />
Also: <input type="text" name="petathome[]"><br />
<input type="submit" name="submit" value="Submit" />

</form>
</body>
</html>

The full php code is:
<?php
$host="host"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$Name=mysql_real_escape_string($_POST['Name']);
$Number=mysql_real_escape_string($_POST['Number']);
$EmailAddress=mysql_real_escape_string($_POST['EmailAddress']);
$Address=mysql_real_escape_string($_POST['Address']);
$petathome=mysql_real_escape_string($_POST['petathome']);

// Loop through the array of checked box values ...
$pets="";
$flag=0;
foreach($petathome as $entry){
$pets .= $entry.", ";
$flag=1;
}
if($flag==1){
$pets=rtrim($pets);
}

// Insert data into mysql
$sql="INSERT INTO $tbl_name(Name, Number, EmailAddress, Address, petathome)VALUES('$Name', '$Number', '$EmailAddress', '$Address', '$pets')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='testpage.html'>Back to main page</a>";
}

else {
echo "ERROR";
}
?>

<?php
// close connection
mysql_close();
?>

mlseim
08-07-2012, 08:45 PM
Change this line:
$petathome=mysql_real_escape_string($_POST['petathome']);

To this:
$petathome=$_POST['petathome'];


Add the line in red ...

if($flag==1){
$pets=rtrim($pets);
}
$pets=mysql_real_escape_string($pets);

mohammedsali
08-07-2012, 09:15 PM
Hi mlseim,

Works perfectly, thank you :D

But when replace checkbox with radio the user is able to select any one radio options but what the enter in "Also:" textbox also gets entered into the database.

Is there a way around this by putting a radio button in front of "Also:" and only if this radio button is select the text filed is enabled? Any thing you think will help will be great.
Regards,
mohammedsali

Fou-Lu
08-07-2012, 09:51 PM
Why are you inserting many values into a single field?
Normalize that structure and create a second table to handle a many to one / many to many relationship. As it sits right now, you cannot properly select, update, or delete a single petsathome within this dataset without iterating EVERY record that's within it. If you have say 100K records, and you try searching for everyone whom has a Lion at home, you need to get every record in order to determine first if they have a lion at home. This is not ideal; doing so will see the time required even just for selections increment with each record added.
And heaven forbid if you need to delete Lion or update Dog.

mohammedsali
08-07-2012, 10:46 PM
Hi Fou-Lu,

I am very new to MySQL and php not sure of how to create relationship(s) and don't think i would like to get into it as it may be very complex for me to handle later on.

As far as the filtering and making changes to petathome goes the data under it is user filled and will not be changed.

I do have a simple, raw .php file to search, filter based on FullName and export the complete database that i would like to make into one, but will come to that next.

Thank you once again Fou-Lu for the suggestions, i really appreciate it :D

Regards,
mohammedsali

mlseim
08-07-2012, 11:27 PM
Fou-Lu,
I'm guessing there are so many other things not quite right, there's no
way the OP will be able to process it all. It appears as he said, a learning thing.
But one might say, "learn it right, from the beginning". No way we're going to be
able to do an online course using codingforums. So, I'm just letting it go with the flow.

Mo ...
OK ... so now you're wanting radio buttons instead of checkboxes?
Create the new form with radio buttons, but the value of the one
in front of <text> box will be value="x"
Next, there will be some javascripting to detect if the radio button is
clicked, and then enable the text box. I think you should do some Googling
for: javascript radio button enable text box

See what you find.

If you can get the javascript to enable the text box, the PHP processing
script will see if the radio button value is "x". If it is, it will use the text
in the text box instead of the radio button value. If the radio button
value is NOT "x", it will use the radio button value.



.

mohammedsali
08-08-2012, 12:39 AM
Hi mlseim,

Thank you for pointing me the right direction :D

Found a script and was able to make changes to fit my html file and it works :)

The changes where needed only in the html file

Html code:

<!DOCTYPE html>
<html>
<body background="blue">
<form action="test_post.php" method="post">

Full Name: <input name="FullName" type="text" id="FullName" required="required" /><br />
<br />
Number: <input name="Number" type="text" id="Number" required="required" /><br />
<br />
Email Address: <input name="EmailAddress" type="text" id="EmailAddress" required="required" /><br /><br />
<br/>
Address: <input name="Address" type="text" id="Address" required="required" /><br />
<br />
Which animal do you want to keep?<br />
<script type="text/javascript">
var currentEnabled = null;
function enableElement(elem) {
if (currentEnabled) {
currentEnabled.disabled = true;
}
elem.disabled = false;
currentEnabled = elem;
}
</script>
<form action="">
<input type="radio" name="petathome[]" value="Dog"
onclick="enableElement(this.form.elements['inp1']);"> Dog
<br>
<input type="radio" name="petathome[]" value="Cat"
onclick="enableElement(this.form.elements['inp2']);"> Cat
<br>
<input type="radio" name="petathome[]" value="Lion"
onclick="enableElement(this.form.elements['inp3']);"> Lion
<br>
<input type="radio" name="petathome[]" value="Tiger"
onclick="enableElement(this.form.elements['inp4']);"> Tiger
<br>
<input type="radio" name="petathome[]" value="Leopard"
onclick="enableElement(this.form.elements['inp5']);"> Leopard
<br>
<input type="radio" name="petathome[]" value="Others"
onclick="enableElement(this.form.elements['inp6']);">
Others: <input type="text" name="inp6" disabled="disabled">

<br>
<br />

<input type="submit" name="submit" value="Submit" />

</form>
</body>
</html>

mlseim
08-08-2012, 04:25 AM
but now, in your PHP script you need to do something with this: name="inp6"

"inp6" is the value of the text box, but is not part of the "petathome[]" array.

So your $pets will have a value of "Others", because of the radio button.
It will not have the value of the things they type into the text box.

mohammedsali
08-08-2012, 04:24 PM
Hi mlseim,

Yes, it only show Other value of the radio box but does not insert the text box values. Did not notice that earlier.

The php code is as below where do i enter "name="inp6" so it enters the values entered in the text box along with the valus of petathome[]

<?php
$host="host"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$FullName=mysql_real_escape_string($_POST['FullName']);
$Number=mysql_real_escape_string($_POST['Number']);
$EmailAddress=mysql_real_escape_string($_POST['EmailAddress']);
$Address=mysql_real_escape_string($_POST['Address']);
$petathome=$_POST['petathome'];

// Loop through the array of checked box values ...
$pets="";
$flag=0;
foreach($petathome as $entry){
$pets .= $entry.", ";
$flag=1;
}
if($flag==1){
$pets=rtrim($pets);
}
mysql_real_escape_string($pets);

// Insert data into mysql
$sql="INSERT INTO $tbl_name(FullName, Number, EmailAddress, Address, petathome)VALUES('$FullName', '$Number', '$EmailAddress', '$Address', '$pets')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='testpage.html'>Back to main page</a>";
}

else {
echo "ERROR";
}
?>

<?php
// close connection
mysql_close();
?>

mlseim
08-08-2012, 05:01 PM
You're using radio buttons now instead of checkboxes,
therefore, you will only be entering one animal. You
can't select more than one radio button.

So I don't understand what this means:

quote:
"... the values entered in the text box along with the values of petathome[]"

along with?
it can't be along with.

do you mean "use the text box value instead of the petathome values?



.

mohammedsali
08-08-2012, 09:12 PM
Hi mlseim,

Thank you once again and sorry for the confusion.

Yes, there would one radio option selected at any given point of time.

Along with the list of animals i have one radio box with text field next to it. Only on clicking this radio button the text field is highlighted. Clicking on this radio box the customer can any thing in it which will be inserted into petathome.

Html code is:
<!DOCTYPE html>
<html>
<body background="blue">
<form action="test_post.php" method="post">

Full Name: <input name="FullName" type="text" id="FullName" required="required" /><br />
<br />
Number: <input name="Number" type="text" id="Number" required="required" /><br />
<br />
Email Address: <input name="EmailAddress" type="text" id="EmailAddress" required="required" /><br /><br />
<br/>
Address: <input name="Address" type="text" id="Address" required="required" /><br />
<br />
Which animal do you want to keep?<br />
<script type="text/javascript">
var currentEnabled = null;
function enableElement(elem) {
if (currentEnabled) {
currentEnabled.disabled = true;
}
elem.disabled = false;
currentEnabled = elem;
}
</script>
<form action="">
<input type="radio" name="petathome[]" value="Dog"
onclick="enableElement(this.form.elements['inp1']);"> Dog
<br>
<input type="radio" name="petathome[]" value="Cat"
onclick="enableElement(this.form.elements['inp2']);"> Cat
<br>
<input type="radio" name="petathome[]" value="Lion"
onclick="enableElement(this.form.elements['inp3']);"> Lion
<br>
<input type="radio" name="petathome[]" value="Tiger"
onclick="enableElement(this.form.elements['inp4']);"> Tiger
<br>
<input type="radio" name="petathome[]" value="Leopard"
onclick="enableElement(this.form.elements['inp5']);"> Leopard
<br>
<input type="radio" name="petathome[]" value="Others"
onclick="enableElement(this.form.elements['inp6']);">
Others: <input type="text" name="inp6" disabled="disabled">

<br>
<br />

<input type="submit" name="submit" value="Submit" />

</form>
</body>
</html>

Php code is:
<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$FullName=mysql_real_escape_string($_POST['FullName']);
$Number=mysql_real_escape_string($_POST['Number']);
$EmailAddress=mysql_real_escape_string($_POST['EmailAddress']);
$Address=mysql_real_escape_string($_POST['Address']);
$petathome=$_POST['petathome'];

// Loop through the array of checked box values ...
$pets="";
$flag=0;
foreach($petathome as $entry){
$pets .= $entry.", ";
$flag=1;
}
if($flag==1){
$pets=rtrim($pets);
}
mysql_real_escape_string($pets);

// Insert data into mysql
$sql="INSERT INTO $tbl_name(FullName, Number, EmailAddress, Address, petathome)VALUES('$FullName', '$Number', '$EmailAddress', '$Address', '$pets')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='testpage.html'>Back to main page</a>";
}

else {
echo "ERROR";
}
?>

<?php
// close connection
mysql_close();
?>

mlseim
08-08-2012, 10:44 PM
If you're no longer using checkboxes, you no longer need to use arrays ...

So this ... I still don't understand the use of radio buttons, but it is what it is ...




<input type="radio" name="petathome" value="Dog"
onclick="enableElement(this.form.elements['inp1']);"> Dog
<br>
<input type="radio" name="petathome" value="Cat"
onclick="enableElement(this.form.elements['inp2']);"> Cat
<br>
<input type="radio" name="petathome" value="Lion"
onclick="enableElement(this.form.elements['inp3']);"> Lion
<br>
<input type="radio" name="petathome" value="Tiger"
onclick="enableElement(this.form.elements['inp4']);"> Tiger
<br>
<input type="radio" name="petathome" value="Leopard"
onclick="enableElement(this.form.elements['inp5']);"> Leopard
<br>
<input type="radio" name="otherpet" value="Others"
onclick="enableElement(this.form.elements['inp6']);">
Others: <input type="text" name="inp6" disabled="disabled">







// Get values from form
$FullName=mysql_real_escape_string($_POST['FullName']);
$Number=mysql_real_escape_string($_POST['Number']);
$EmailAddress=mysql_real_escape_string($_POST['EmailAddress']);
$Address=mysql_real_escape_string($_POST['Address']);
$petathome=$_POST['petathome'];
$otherpet=$_POST['otherpet'];
$other_text=mysql_real_escape_string($_POST['inp6']);

// Loop through the array of checked box values ...
$pets=$petathome;
if($otherpet=="Others"){
$pets .= "|".$other_text;
}
mysql_real_escape_string($pets);

Len Whistler
08-08-2012, 10:57 PM
Below is a db structure that I think would make updating and changing the info easier. It has three tables: MEMBERS, PETS and MEMBERS_PETS.

MEMBERS
member_id | name | email | address

0001 | Ben | ben@yahoo.com | 1234 Main St.
0002 | Brian | brian@hotmail.com | 12 Elm St.
0003 | Jill | jill_smith@yahoo.com | 546 12th Avenue
0004 | Kevin | k@gmail.com | 111 Spruce St.
0005 | Jackie | Jackie@yahoo.com | 7777 5th St.
0006 | Ben W | ben.w@gmail.com | 1284 West St.


PETS
pet_id | pet
001 | Dog
002 | Cat
003 | Lion
004 | Tiger
005 | Leopard


MEMBERS_PETS
id | pet_id | member_id
0001 | 005 | 0002
0002 | 005 | 0006
0003 | 001 | 0002
0004 | 003 | 0001
0005 | 002 | 0005
0006 | 002 | 0002
0007 | 002 | 0001


Bold = Primary Keys
Italic = Foreign Keys

Fou-Lu
08-08-2012, 11:59 PM
I suggested as well a more normalized solution to the database for ease (although without example).
I would use the above structure, except I would drop the id from MEMBERS_PETS and use a composite key instead. I don't like the surrogates at all, so I'd probably take it off the PETS, but likely leave it on the members (or shift it to email assume it has to be unique).

mohammedsali
08-09-2012, 12:49 AM
Hi mlseim,

Thank you for your reply :)

It works fine, expect one small thing.

On the html page when selecting:
Dog
Cat
Lion
Tiger
Leopard

it all is fine, but when click on Others, there are two dots. One on Others and the other or the last selected option.

But the important thing is if any other option is selected after selecting Others the Others field is disable which is great.

Please let me know if this is something that can be fixed?

Thanks & Regards,
mohammedsali

mlseim
08-09-2012, 01:32 AM
Because you're using radio buttons.

When you click a radio button, an animal is selected.
But then you can't remove the choice ... you can only
select a different one.

I don't understand the specs.

Can I select a Tiger AND select "other" ... typing Monkey in the text box?

Or can I only select an animal OR select "other", but not both?

Still ... stumped on the radio button thing.
The relationship between the animals and the "other" button is odd.

Normalizing the database is pretty far-fetched ... he can't even
figure-out the radio button snafu. I can't figure-out what the site
is even supposed to do.

Mo, I think you'll have to go through some online tutorials.



.

mohammedsali
08-09-2012, 01:59 AM
Hi mlseim,

Sorry if any confusion. Will try to clear it up.

The radio button options are:
() Dog
() Cat
() Lion
() Tiger
() Leopard
() Others [____________] <<Text box

The user has the option to select any one of the radio button options. If the animal is not part of the listed options, the user will click on "Others" radio button and enter the animal name.

Which every is the selected value:
Dog or Cat or Lion or Tiger or Leopard or the value user has entered.

So the user can only select one option at any given time which gets entered into the database.

Thanks & Regards,
mohammedsali

mlseim
08-09-2012, 03:58 AM
There is no reason to enable or disable the text box.
The text box value does nothing unless the "Others" radio button is selected.
Whether there is text or not makes no difference if any other animal is selected.





<!DOCTYPE html>
<html>
<body background="blue">
<form action="test_post.php" method="post">

Full Name: <input name="FullName" type="text" id="FullName" required="required" /><br />
<br />
Number: <input name="Number" type="text" id="Number" required="required" /><br />
<br />
Email Address: <input name="EmailAddress" type="text" id="EmailAddress" required="required" /><br /><br />
<br/>
Address: <input name="Address" type="text" id="Address" required="required" /><br />
<br />
Which animal do you want to keep?<br />
<script type="text/javascript">
var currentEnabled = null;
function enableElement(elem) {
if (currentEnabled) {
currentEnabled.disabled = true;
}
elem.disabled = false;
currentEnabled = elem;
}
</script>
<form action="">
<input type="radio" name="petathome" value="Dog"> Dog <br>
<input type="radio" name="petathome" value="Cat"> Cat <br>
<input type="radio" name="petathome" value="Lion"> Lion <br>
<input type="radio" name="petathome" value="Tiger"> Tiger <br>
<input type="radio" name="petathome" value="Leopard"> Leopard <br>
<input type="radio" name="petathome" value="Others"
onclick="enableElement(this.form.elements['inp6']);">
Others: <input type="text" name="inp6" disabled="disabled"> <br>
<br />

<input type="submit" name="submit" value="Submit" />

</form>
</body>
</html>




Php code is:


<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$FullName=mysql_real_escape_string($_POST['FullName']);
$Number=mysql_real_escape_string($_POST['Number']);
$EmailAddress=mysql_real_escape_string($_POST['EmailAddress']);
$Address=mysql_real_escape_string($_POST['Address']);
$petathome=$_POST['petathome'];
$inp6=mysql_real_escape_string($_POST['inp6']);

$pets = $petathome;
if($petathome == "Others"){
$pets = $inp6;
}
$pets=mysql_real_escape_string($pets);

// Insert data into mysql
$sql="INSERT INTO $tbl_name(FullName, Number, EmailAddress, Address, petathome)VALUES('$FullName', '$Number', '$EmailAddress', '$Address', '$pets')";
$result=mysql_query($sql);

// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
echo "<a href='testpage.html'>Back to main page</a>";
}

else {
echo "ERROR";
}
?>

<?php
// close connection
mysql_close();
?>

Len Whistler
08-09-2012, 09:10 AM
Hi mlseim,

The radio button options are:
() Dog
() Cat
() Lion
() Tiger
() Leopard
() Others [____________] <<Text box

The user has the option to select any one of the radio button options. If the animal is not part of the listed options, the user will click on "Others" radio button and enter the animal name.

Which every is the selected value:
Dog or Cat or Lion or Tiger or Leopard or the value user has entered.

So the user can only select one option at any given time which gets entered into the database.

The above example is why a table for pets will make things so much better. Take the DB structure I posted for the PETS table.


PETS
pet_id | pet
001 | Dog
002 | Cat
003 | Lion
004 | Tiger
005 | Leopard

The above would generate your radio buttons, plus your others option. Someone picks others and enters Hamster. Hamster gets entered into the PETS table and is added to the radio buttons automatically, you can also output the radio buttons alphabetically to make selections easier to find. Any typos you would manually fix and if it matches an existing entry it doesn't get entered again.


Updated PETS table after Hamster is entered in the others text box.

PETS
pet_id | pet
001 | Dog
002 | Cat
003 | Lion
004 | Tiger
005 | Leopard
006 | Hamster


----

Len Whistler
08-09-2012, 09:42 PM
Based on mlseim's code for the radio button form I added some PHP with an array of pets.




<form action="">
<?php
//php sorted array - inplace of mysql db for demo purposes.
$pets = array('Dog','Cat','Lion','Tiger','Leopard',);
sort($pets);
//////////////////////////////////////////////////////////

foreach ($pets as $pet) {
echo "<input type=\"radio\" name=\"petathome\" value=\"$pet\"> $pet <br> ";
}
?>
<input type="radio" name="petathome" value="Others"
onclick="enableElement(this.form.elements['inp6']);">
Others: <input type="text" name="inp6" disabled="disabled"> <br>
<br />
<input type="submit" name="submit" value="Submit" />
</form>

mlseim
08-10-2012, 12:39 AM
Len is predicting the next thing ...
Mo will want to populate the radio buttons using the database.
... good one :thumbsup:

mohammedsali
08-13-2012, 08:18 PM
Hi mlseim,

Sorry for the delayed reply :(

Thank you for the help, have it working now :)

Thank you Len Whistler for the suggestions :)

Regards,
mohammedsali

mohammedsali
08-13-2012, 10:30 PM
Hi Guys,

Back again and need some help.

I am trying to export the database into a .csv file with custom headers.

I was able to find this script but getting stuck.



<?php

$DB_host="localhost"; // Host name
$DB_username="username"; // Mysql username
$DB_password="dbpassword"; // Mysql password
$db_name="dbname; // Database name

#
# Create the connection to MySQL
#

$con = mysql_connect("$DB_host","$DB_username","$DB_password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}


#
# Create the Column Headings
#

$csv_output .= '"Id",';
$csv_output .= '"Full Name",';
$csv_output .= '"Number",';
$csv_output .= '"Email Address",';
$csv_output .= '"City",';
$csv_output .= '"Address",';
$csv_output .= '"Which animal do you want to keep?"';
$csv_output .= "\n";


#
# Get Users Details form the DB
#

$result = mysql_query( "SELECT * from tablename WHERE id = '$id'" );

while ( $a_row = mysql_fetch_array( $result ) ){

$csv_output .= '"'.str_replace('"', '""', $a_row['id']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['FullName']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['Number']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['EmailAddress']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['City']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['Address']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['compathome']).'"';
$csv_output .= "\n";
}


#
# Close the MySql connection
#

mysql_close($con);

#
# Set the headers so the file downloads
#

header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($csv_output));
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=resultExport.csv");
echo $csv_output;
exit;

?>



I get the error with row having:
while ( $a_row = mysql_fetch_array( $result ) ){

Error is: Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in.........

And:
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($csv_output));
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=resultExport.csv");

Error is:
Warning: Cannot modify header information - headers already sent by

Thank you in advance for helping :)

Regards,
mohammedsali

Len Whistler
08-13-2012, 11:23 PM
Error is:
Warning: Cannot modify header information - headers already sent by


That error is because some html has been sent to the page before the header function.


header("Cache-Control: must-revalidate, post-check=0, pre-check=0");

Even white space will cause the error. You might have to use the backspace key to remove any spaces that might be considered white space, perhaps it's some tabs or spaces that have to be removed.

Another solution is to use the php function ob_flush at the start and end of the page . I haven't used it in years so you might have to check the manual for exact use of ob_flush.



---

mohammedsali
08-13-2012, 11:38 PM
Hi Len Whistler,

Thank you for the reply :)

Tried to remove spaces under $csv_output example:
$csv_output .= '"FullName",';


Also removed spaces under:
header("Cache-Control:must-revalidate,post-check=0,pre-check=0");


Very new to php and not sure of ob_flush, but if you can help would really appreciate it :)

But it did not help :(

Thanks & Regards,
mohammedsali

mlseim
08-13-2012, 11:48 PM
Worry about this one for now ...

Error is: Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in.........

Are you sure there are results? Maybe it didn't find anything.

Len Whistler
08-13-2012, 11:53 PM
Below is how I would remove all spaces, before the header function. Even the comments are removed. Is there any code above the php opening tag?



<?php
$DB_host="localhost"; // Host name
$DB_username="username"; // Mysql username
$DB_password="dbpassword"; // Mysql password
$db_name="dbname; // Database name
$con = mysql_connect("$DB_host","$DB_username","$DB_password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
$csv_output .= '"Id",';
$csv_output .= '"Full Name",';
$csv_output .= '"Number",';
$csv_output .= '"Email Address",';
$csv_output .= '"City",';
$csv_output .= '"Address",';
$csv_output .= '"Which animal do you want to keep?"';
$csv_output .= "n";
$result = mysql_query( "SELECT * from tablename WHERE id = '$id'" );
while ( $a_row = mysql_fetch_array( $result ) ){
$csv_output .= '"'.str_replace('"', '""', $a_row['id']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['FullName']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['Number']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['EmailAddress']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['City']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['Address']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['compathome']).'";
$csv_output .= "\n";
}
mysql_close($con);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($csv_output));
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=resultExport.csv");
echo $csv_output;
exit;
?>

mohammedsali
08-13-2012, 11:55 PM
Hi mlseim,

Thank you for the reply :)

There is data in the Table to be shown. I have this script which exports the data from table but the headers are not custom.




<?php
$host = 'localhost'; // <-- db address
$user = 'username'; // <-- db user name
$pass = 'dbpassword'; // <-- password
$db = 'dbname'; // db's name
$table = 'tblname'; // table you want to export
$file = 'tbl_export'; // csv name.

$link = mysql_connect($host, $user, $pass) or die("Can not connect." . mysql_error());
mysql_select_db($db) or die("Can not connect.");

$term = $_POST['term'];

$result = mysql_query("select * from tblname where FullName like '%$term%'");
$i = 0;

if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$csv_output .= $row['Field'].",";
$i++;}
}
$csv_output .= "\n";
$values = mysql_query("select * from tblname where FullName like '%$term%'");

while ($rowr = mysql_fetch_row($values)) {
for ($j=0;$j<$i;$j++) {
$csv_output .= $rowr[$j].", ";
}
$csv_output .= "\n";
}

$filename = $file."_".date("d-m-Y_H-i",time());

header("Content-type: application/vnd.ms-excel");
header("Content-disposition: csv" . date("Y-m-d") . ".csv");
header( "Content-disposition: filename=".$filename.".csv");

print $csv_output;

exit;
?>



If there is a way to insert custom headers in this script too will help.

Thanks & Regards,
mohammedsali

mohammedsali
08-14-2012, 12:08 AM
Hi Len Whistler,

Thank you for the corrected script :)

Was getting in link number 6, added "$db_name" to $con = mysql_connect that solved the problem but now get the error:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE

Thanks & Regards,
mohammedsali

Len Whistler
08-14-2012, 12:09 AM
Haven't used it in years so there might be errors below. But it's something to have in mind for headers already sent errors.




<?php
ob_start();




rest of code







ob_flush();
?>

mohammedsali
08-14-2012, 12:20 AM
Hi Len Whistler

Thank you for the suggestion, tried the following.




<?php
$DB_host="localhost"; // Host name
$DB_username="username"; // Mysql username
$DB_password="dbpassword"; // Mysql password
$db_name="dbname; // Database name
$con = mysql_connect("$DB_host","$DB_username","$DB_password", "$db_name");
if (!$con){
die('Could not connect: ' . mysql_error());
}
ob_start();
$csv_output .= '"Id",';
$csv_output .= '"Full Name",';
$csv_output .= '"Number",';
$csv_output .= '"Email Address",';
$csv_output .= '"City",';
$csv_output .= '"Address",';
$csv_output .= '"Which animal do you want to keep?"';
$csv_output .= "n";
$result = mysql_query( "SELECT * from hr_candidates WHERE id = '$id'" );
while ( $a_row = mysql_fetch_array( $result ) ){
$csv_output .= '"'.str_replace('"', '""', $a_row['id']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['FullName']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['MobileNumber']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['EmailAddress']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['City']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['Address']).'",';
$csv_output .= '"'.str_replace('"', '""', $a_row['petathome']).'";
$csv_output .= "\n";
}
mysql_close($con);
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Content-Length: " . strlen($csv_output));
header("Content-type: text/x-csv");
header("Content-Disposition: attachment; filename=resultExport.csv");
echo $csv_output;
exit;
ob_flush();
?>



But still get the same error:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE in..

Thanks,
mohammedsali

Len Whistler
08-14-2012, 12:30 AM
Hi Len Whistler

Thank you for the suggestion, tried the following.

But still get the same error:
Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE in..

Thanks,
mohammedsali


Removing all the extra space was a possible solution for the header already sent error. The above error should give a line number you can look at.


----

djm0219
08-14-2012, 09:12 AM
You're missing the closing quote on this line:


$db_name="dbname; // Database name

Should be


$db_name="dbname"; // Database name

Hint, look at the code you posted and you'll see where things turn red when they shouldn't be.

mohammedsali
08-15-2012, 10:31 PM
Hi Guys,

Thank you for your suggestions and help :)

Found a script, works perfectly:




// output headers so that the file is downloaded rather than displayed
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename=data.csv');

// create a file pointer connected to the output stream
$output = fopen('php://output', 'w');

// output the column headings
fputcsv($output, array('Column 1', 'Column 2', 'Column 3'));

// fetch the data
mysql_connect('localhost', 'username', 'password');
mysql_select_db('database');
$rows = mysql_query('SELECT field1,field2,field3 FROM table');

// loop over the rows, outputting them
while ($row = mysql_fetch_assoc($rows)) fputcsv($output, $row);

mohammedsali
08-17-2012, 10:13 PM
Hi Guys,

I am trying to create a page to view records.

1) Have a fixed header for the column headers so browsing down the user does not lose sight of the column headers.


2) I could like to make it that the user can either view all the records in one page or user can set number of records to be shown on the page and go page by page or go directly to any particular page.

I have the below code which shows all the records but lose sight of the headers when browse down.



<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$sql="SELECT * FROM $tbl_name";
$result=mysql_query($sql);
?>

<table align="center" width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table align="center" width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<td align="center" colspan="4"><strong>View all records</strong> </td>
</tr>

<tr>
<td align="center"><strong>Id</strong></td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Number</strong></td>
<td align="center"><strong>Email Address</strong></td>
<td align="center"><strong>City</strong></td>
<td align="center"><strong>Address</strong></td>
<td align="center"><strong>petathome?</strong></td>
<td align="center"><strong>Edit Record</strong></td>
</tr>

<?php
while($rows=mysql_fetch_array($result)){
?>

<tr>

<td><? echo $rows['Id']; ?></td>
<td><? echo $rows['Name']; ?></td>
<td><? echo $rows['Number']; ?></td>
<td><? echo $rows['EmailAddress']; ?></td>
<td><? echo $rows['City']; ?></td>
<td><? echo $rows['Address']; ?></td>
<td><? echo $rows['petathome']; ?></td>

<td align="center"><a href="update.php?id=<? echo $rows['id']; ?>">edit</a></td>
</tr>

<?php
}
?>

</table>
</td>
</tr>
</table>

<?php
mysql_close();
?>


Thank you in advance for helping :)

Regards,
mohammedsali

Len Whistler
08-17-2012, 10:40 PM
1) Have a fixed header for the column headers so browsing down the user does not lose sight of the column headers.

I believe you can use CSS to fix a div in a specific location, such as the top of the page. But I find it extremely distracting to have objects fixed in a position and as you scroll it always pops up. I see it with menus, and advertisements.

I would have a slightly different color for each column, and let the column headers scroll out of sight.




2) I could like to make it that the user can either view all the records in one page or user can set number of records to be shown on the page and go page by page or go directly to any particular page.

The term is pagination, and yes it's a good idea to limit the number of records per page. PHP handles pagination very well.




----

mohammedsali
08-18-2012, 03:26 AM
Hi Len,

Thank you guiding me in the right direction :)

With a lot of difficulty and searching was able to find and put together this script which works. The only problem i am not able to figure out is it does not list the first row of the every page correctly.

Example first page is to start with the id 1, but instead it starts from id 2
Same happens to every page, example if the next page is to start with id 21, it will instead shows 22.

Can please let me know the exact correction i will need to make?

If possible can you help me with the correct script?

And also was not able to any head way in fixed column headers. If you have any working script or can guide me to one would be of great help.

I really appreciate you help once again :)

Regards,
mohammedsali




<html>
<head>
<title>View Results</title>
</head>

<body>

<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

define('MAX_REC_PER_PAGE', 25);
mysql_connect("$host", "$username", "$password") or die("Couldn't connect to db!");
mysql_select_db("$db_name") or die("Couldn't select db!");
$result = mysql_query("SELECT COUNT(*) FROM $tbl_name") or die("Count query error!");
list($total) = mysql_fetch_row($result);
$total_pages = ceil($total / MAX_REC_PER_PAGE);
$page = intval(@$_GET["page"]);
if (0 == $page){
$page = 1;
}
$start = MAX_REC_PER_PAGE * ($page - 1);
$max = MAX_REC_PER_PAGE;
$result = mysql_query("SELECT id, Name, Number, EmailAddress, City, Address, petathome FROM $tbl_name ORDER BY id ASC LIMIT $start,
$max") or die("$tbl_name query error!");
?>
<table align="center" width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td>
<table align="center" width="400" border="1" cellspacing="0" cellpadding="3">
<tr>
<td align="center" colspan="9"><strong>View all records</strong> </td>
</tr>

<tr>
<td align="center"><strong>Id</strong></td>
<td align="center"><strong>Name</strong></td>
<td align="center"><strong>Number</strong></td>
<td align="center"><strong>Email Address</strong></td>
<td align="center"><strong>City</strong></td>
<td align="center"><strong>Address</strong></td>
<td align="center"><strong>petathome?</strong></td>
<td align="center"><strong>Edit Record</strong></td>
</tr>
<?php
while (list($id, $Name, $Number, $EmailAddress, $City, $Address, $petathome) = mysql_fetch_row($result)) {
while($rows=mysql_fetch_array($result)){
?>

<td><? echo $rows['id']; ?></td>
<td><? echo $rows['Name']; ?></td>
<td><? echo $rows['Number']; ?></td>
<td><? echo $rows['EmailAddress']; ?></td>
<td><? echo $rows['City']; ?></td>
<td><? echo $rows['Address']; ?></td>
<td><? echo $rows['petathome']; ?></td>

<td align="center"><a href="update.php?id=<? echo $rows['id']; ?>">edit</a></td>
</tr>
<?php
}
?>
<?php
}
?>
</table>
<table border="0" cellpadding="3" align="center">
<tr>
<td>Goto Page:</td>
<?php
for ($i = 1; $i <= $total_pages; $i++) {
$txt = $i;
if ($page != $i)
$txt = "<a href=\"" . $_SERVER["PHP_SELF"] . "?page=$i\">$txt</a>";
?>
<td align="center"><?= $txt ?></td>
<?php
}
?>
</tr>
</table>
<hr>
</div>
</body>
</html>

mohammedsali
08-21-2012, 11:31 PM
Hi Guys,

Still unable to find a fix for the above problem. Any suggestions?

I really appreciate you help once again

Regards,
mohammedsali

Len Whistler
08-22-2012, 12:32 AM
Hi Guys,

Still unable to find a fix for the above problem. Any suggestions?

I really appreciate you help once again

Regards,
mohammedsali


Echo out the value of $start. On the 1st page it should be 1, 2nd page 26.


$start = MAX_REC_PER_PAGE * ($page - 1);


---

havish
10-05-2012, 07:55 PM
Try this:



<?php
$host="localhost"; // Host name
$username="username"; // Mysql username
$password="password"; // Mysql password
$db_name="dbname"; // Database name
$tbl_name="tblname"; // Table name

// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// Get values from form
$FullName=$_POST['FullName'];
$MobileNumber=$_POST['Number'];
$EmailAddress=$_POST['EmailAddress'];
$Address=$_POST['Address'];
$petathome=$_POST['petathome'];
.

// Loop through the array of checked box values ...
$pets="";
$flag=0;
foreach($petathome as $entry){
$pets .= $entry."|";
$flag=1;
}
if($flag==1){
$pets=rtrim($pets);
}










I am new to PHP and have a similar requirement. May i plz know why $flag and rtrim function is used here??

idah
11-25-2013, 12:45 PM
i tried foreach() function an an error "Invalid argument supplied for foreach()" was displayed. i need some help, thank you:)

heres my form:
<form name="form" class="formtest" method="post" action="doPostUpcomingTrips.php" ENCTYPE="multipart/form-data">
<fieldset>
<label for="country_name">Name of Country:</label>
<input type="text" name="country_name"/></br></br>

<label for="country_city">City of Country:</label>
<input type="text" name="country_city"/></br></br>

<label for="course">Course:</label>
<input type="checkbox" name="course" value="1"/>DBA
<input type="checkbox" name="course" value="2"/>DBIS
<input type="checkbox" name="course" value="3"/>DIT
<input type="checkbox" name="course" value="4"/>DIDM
<input type="checkbox" name="course" value="5"/>DISM
<input type="checkbox" name="course" value="6"/>DMSD
<br><br>

<label for="date_of_departure">Date of Departure:</label>
<input type="date" name="date_of_departure"/></br></br>

<label for="date_of_return">Date of return:</label>
<input type="date" name="date_of_return"/></br></br>

<label for="date_of_closed_registration">Closed Registration Date:</label>
<input type="date" name="date_of_closed_registration"/></br></br>

<label for="description">Description:</label>
<textarea wrap="virtual" name="description" rows=15 cols=50></textarea></br></br>

<label for="imagesfile">Image1:</label>
<input type="FILE" name="image1"/></br></br>

<label for="imagesfile">Image2:</label>
<input type="FILE" name="image2"/></br></br>

<label for="imagesfile">Image3:</label>
<input type="FILE" name="image3"/></br></br>

<label for="submit"></label><input name="submit" value="Submit" type="submit">

</fieldset>
</form>





and my insert portion:
<!DOCTYPE>
<html>
<head>

</head>
<body>
<table>

</table>
<table border="10" width="1001" align="center" cellspacing="0" >
<?php
session_start();
$ID=$_SESSION['id'];

$HOST = "localhost";
$USERNAME = "root";
$PASSWORD = "";
$DB = "fyp";
$link = mysqli_connect($HOST,$USERNAME,$PASSWORD,$DB) or die(mysqli_connect_error());

$country_name= $_POST['country_name'];
$country_city= $_POST['country_city'];
$date_of_departure=$_POST['date_of_departure'];
$date_of_return=$_POST['date_of_return'];
$date_of_closed_registration=$_POST['date_of_closed_registration'];
$description=$_POST['description'];
$course=$_POST['course'];

$soiCourse="";
$flag=0;
foreach($course as $entry){
$soiCourse .= $entry.", ";
$flag=1;
}
if($flag==1){
$soiCourse=rtrim($soiCourse);
}
$soiCourse=mysql_real_escape_string($soiCourse);

$query1 = "INSERT INTO trips(description,date_of_closed_registration,country_name,country_city,date_of_departure,date_of_re turn,course_name, staff_id)
VALUES ('$description','$date_of_closed_registration','$country_name','$country_city','$date_of_departure', '$date_of_return','$soiCourse','$ID')";
$result1= mysqli_query($link, $query1) or die('Error querying database');
if ($result1) {
echo "Article has been sucessfully uploaded,to view go <a href='index.php'>Home</a>";
} else {
echo" Article failed to be uploaded.<br> <a href='addArticle.php'>Try again/a>";
}
?>




</body>



</html>

mlseim
11-25-2013, 09:43 PM
When you use an array, it must have square brackets ...

<input type="checkbox" name="course[]" value="1"/>DBA

Try that and you may find that it works.

atchutarao
09-17-2014, 06:38 PM
hi mills pleas hel me for the following..
I am updating the record.. but i am getting this error.

Getting ERrror like =>Parse error: syntax error, unexpected 'if' (T_IF) in line 17
line 17 is =>if (isset($_POST['save']))


here i am passing BookId from index.php
Code is
----------

<?php
require("db.php");
$id =$_REQUEST['BookID'];

$result = mysql_query("SELECT * FROM books WHERE BookID = '$id'");
$test = mysql_fetch_array($result);
if (!$result)
{
die("Error: Data not found..");
}
$Title=$test['Title'] ;
$Author= $test['Author'] ;
$PublisherName=$test['PublisherName'] ;
$CopyrightYear=$test['CopyrightYear'] ;
$Gender=$test['Gender'];
$Languages=$test['Languages']
if (isset($_POST['save']))

{
$title_save = $_POST['title'];
$author_save = $_POST['author'];
$name_save = $_POST['name'];
$copy_save = $_POST['copy'];
$gender_save=$_POST['gender'];
$lang_save=$_POST['lang']

$languages_save="";
$flag=0;
foreach($lang_save as $entry){
$languages_save = $languages_save .$entry.",";
$flag=1;
}
if($flag==1){
$languages_save=rtrim($languages_save);
}

mysql_query("UPDATE books SET Title ='$title_save', Author ='$author_save',
PublisherName ='$name_save',CopyrightYear ='$copy_save',Gender='$gender_save',Languages='$languages_save' WHERE BookID = '$id'")
or die(mysql_error());
echo "Saved!";

header("Location: index.php");
}
mysql_close($conn);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
</head>

<body>
<form method="post">
<table>
<tr>
<td>Title:</td>
<td><input type="text" name="title" value="<?php echo $Title ?>"/></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" name="author" value="<?php echo $Author ?>"/></td>
</tr>
<tr>
<td>Publisher Name</td>
<td><input type="text" name="name" value="<?php echo $PublisherName ?>"/></td>
</tr>
<tr>
<td>Copyright Year</td>
<td><input type="text" name="copy" value="<?php echo $CopyrightYear ?>"/></td>
</tr>
<tr><td>Gender</td><td><?php echo $Gender ?></td> </tr>
<tr><td><input type="radio" name="gender" value="Male">male</td><td><input type="radio" name="gender" value="FeMale">female</td></tr>

<tr><td>Languages</td><td><?php echo $Languages ?></td> </tr>
<tr>
<td><input type="checkbox" name="lang[]" value="Telugu">tel </td>
<td><input type="checkbox" name="lang[]" value="English">eng </td>
<td><input type="checkbox" name="lang[]" value="Hindi">hin</td>
<td><input type="checkbox" name="lang[]" value="Tamil">tml </td>
<td><input type="checkbox" name="lang[]" value="Marathi">mar </td>
</tr>

<tr>
<td>&nbsp;</td>
<td><input type="submit" name="save" value="save" /></td>
</tr>
</table>

</body>
</html>

but that statment like=> isset($_post['save']) is working for insertin record,,but for this iam getting error,, can yu help me ?? thnks in advance..



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum