I have php code like this :
<?php
if(isset($_POST['submit']))
{
if(!empty($_POST['vehicles']))
{
$vehicles=$_POST['vehicles'];
$hostname='localhost';
$username='root';
$password='root';
$dbname='pet';
$connect=mysqli_connect($hostname,$username,$password,$dbname) or die("can't connect to server");
$query="UPDATE information SET transportation='$vehicles'";
$query=mysqli_query($connect,$query) or die("can't execute query");
echo "inserted";
}
else
{
echo "error";
}
}
else
{
echo "choose your vehicle";
}
?>
<!DOCTYPE html>
<html>
<head>
<title> Select transportation you have</title>
</head>
<body><h2>Select transportation you have</h2>
<form action="#" method="POST">
<input type="checkbox" name="vehicles" value="bike"/>I have bike<br/>
<input type="checkbox" name="vehicles" value="car"/>I have car<br/>
<input type="checkbox" name="vehicles" value="motor"/>I have motor<br/>
<input type="submit" name="submit" value="submit"/>
</form>
</html>
when i choose more than one options there is only one value in my database.For example i choose bike and motor.There is only motor in the database
change the name of the inputs to be an array by add [] at the end of the name
<input type="checkbox" name="vehicles[]" value="bike"/>I have bike<br/>
<input type="checkbox" name="vehicles[]" value="car"/>I have car<br/>
<input type="checkbox" name="vehicles[]" value="motor"/>I have motor<br/>
then in php you will be able to access them using the array syntax, and you can simply use implode to make a comma separated list of the vehicles.
$_POST['vehicles'][0]
$_POST['vehicles'][1]
$_POST['vehicles'][2]
//etc...
$vehicles = implode(",",$_POST['vheicles']);
$query="UPDATE information SET transportation='$vehicles'";
//$query would contain something like:
//UPDATE information SET transportation='bike,car'
Of course do sanitation on the POST variables before putting them in the db.
You need to change the html to:
<input type="checkbox" name="vehicles[]" value="bike"/>I have bike<br/>
<input type="checkbox" name="vehicles[]" value="car"/>I have car<br/>
<input type="checkbox" name="vehicles[]" value="motor"/>I have motor<br/>
Change the PHP to:
$vehicles=implode(',',$_POST['vehicles']);
Related
I have searched everywhere and still cannot find the answer. Can anybody help?
I have a PHP form that consists of a textbox (with data that will go into column name_id) and a checkbox, that has the option to go to 5 different MySQL tables:
'table A'
'table B'
'table C'
'table D'
'table E'
People can choose which table they want, and the name_id will go to the tables selected.
How can I do this?
my Answere in different from #RandD-SexyBoy- . my sql query is different from #RandD-SexyBoy- he has used $sql = "INSERT INTO $tables[$i](nameID_column); with out VALUES (:nameID_column)
were is have used $sql->prepare("INSERT INTO ".$v." (name_id) VALUES (?)"
Here are 3 cases the user responds
case first : user may select a single table
case second : user may select multiple tables. here we must use foreach() loop and dynamic sql queries.
case third : user may not select any table in this case we must give user a message table not selected
html form :
`
<html>
<head>
</head>
<body>
<form action="" method="post">
<input type="text" name="name_id" required>
<p>select your table to add data</p>
<input type="checkbox" name="tables[]" value="tblA">Table A<br>
<input type="checkbox" name="tables[]" value="tblB">Table B<br>
<input type="checkbox" name="tables[]" value="tblC">Table C<br>
<input type="checkbox" name="tables[]" value="tblD">Table D<br>
<input type="checkbox" name="tables[]" value="tblE">Table E<br>
<input type="submit" name="submit">
</form>
</body>
</html>
`
php file :
<?php
$con = new mysqli('localhost','root','admin','demo');
if(!$con){
die("Connection ".$con->connect_error);
}
if(isset($_POST['submit'])){
$name_id = $_POST['name_id'];
$tables = $_POST['tables'];
if(!empty($tables)){
foreach($tables as $key=>$v){
$sql = $con->stmt_init();
if($sql->prepare("INSERT INTO ".$v." (name_id) VALUES (?)")){
$sql->bind_param($name_id);
$sql->execute();
echo "DATA INSERTED";
}
else
{
echo "Error".$con->error;
}
}
}
else
{
echo "You have not selected tables";
}
}
?>
So one naive approach could be, when the user submits the form, on your php side, you check which checkboxes are ticked and your condition could be something like this
if(checkbox_for_table_A) {// insert query}
if(checkbox_for_table_B) {// insert query}
if(checkbox_for_table_C) {// insert query}
if(checkbox_for_table_D) {// insert query}
if(checkbox_for_table_E) {// insert query}
This way if one checkbox is selected it will save into that table, if more than one tables are selected, it will go in that table.
Hope this helps! Ask any doubt you get in the comment section.
Adapting from sources : post checkbox value and tutorial http://www.mustbebuilt.co.uk/php/insert-update-and-delete-with-pdo/, you can use this approach :
HTML Form :
<form action="checkbox-form.php" method="post">
<input type="text" name="name_id" /><br />
Select your database: <br/>
<input type="checkbox" name="formTables[]" value="A" />Table A<br />
<input type="checkbox" name="formTables[]" value="B" />Table B<br />
<input type="checkbox" name="formTables[]" value="C" />Table C<br />
<input type="checkbox" name="formTables[]" value="D" />Table D<br />
<input type="checkbox" name="formTables[]" value="E" />Table E<br />
<input type="submit" name="formSubmit" value="Submit" />
</form>
Now the PHP script :
<?php
$pdo_connection = new PDO('mysql:host=localhost;dbname=test', 'demouser', 'demopass');
$tables = $_POST['formTables'];
if(empty($tables))
{
echo("You didn't select any tables.");
}
else
{
$N = count($tables);
echo("You selected $N table(s): ");
for($i=0; $i < $N; $i++)
{
$sql = "INSERT INTO $tables[$i](nameID_column);
$stmt = $pdo_connection->prepare($sql);
$stmt->bindParam(':nameID_column', $_POST['name_id'], PDO::PARAM_STR);
$stmt->execute();
echo("Your ID Name was inserted into table $tables[$i] ! <br /> ");
}
}
?>
This is the code I have written:
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form action="db.php" method="post">
YES:<input type="radio" name="YES" value="YES">
NO:<input type="radio" name="NO" value="NO" >
<input type="submit" name="submit value="submit">
</form>
</body>
<html>
db.php
<?php
$con = mysqli_connect('localhost','my user id','my password');
if(!con)
{ echo 'not connected to server';}else { echo 'something else is wrong' ;}
if(!mysqli_select_db($con,'my user id')
{ echo 'Database error selection';}
$YES = $_POST['YES'];
$NO = $_POST['NO'];
$sql = INSERT INTO users (YES,NO) VALUES ('$YES','$NO');
if(!mysqli_query($con,$sql))
{ echo 'Answer not submitted please try again!!!!!!!!';}
else{
echo 'Your answer successfully submitted \n Thanks for participating';}
header(" refresh:2; url=index.html");
?>
There is something wrong in it.
Can anyone please tell what is wrong?
Note: If 2 users submit YES then in database YES would get int value as 2
If 1 users submit NO then in database NO would get int value as 1.
You are using radio button the wrong way. Radio button should have the same 'name'. In your case you may use name="yesno".
YES:<input type="radio" name="yesorno" value="yes">
NO:<input type="radio" name="yesorno" value="no">
For your PHP it should be like this.
<?php
if (isset($_POST['submit'])) {
$yesorno=$_POST['yesno'];
$sql = INSERT INTO users (columnName) VALUES ('$yesorno');
mysqli_query($con,$sql); // Execute query
}
?>
And please express your goal as clear as possible. For now i pinpointed what is wrong on your coding semantics.
Above looks good. Another way is to add a label:
<label for="yesorno">Question:</label>
<input type="radio" name="yesorno" value="yes">YES:
<input type="radio" name="yesorno" value="no">NO:<br />
I have a question about radio buttons in html and linking into php. And i dont know how to link it without the name part because i need the name to be all 1 otherwise you can select every radiobutton. My second question is how do i link the button into php.
This is my HTML code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Pizza</h1>
<form method="POST" action="pizza.php">
Wat op pizza:<br>
<input type="radio" value="" name="pepperoni">Pepperoni<br>
<input type="radio" value="" name="ananas">Ananas<br>
<input type="radio" value="" name="ansjovis">Ansjovis<br>
<input type="radio" value="" name="broccoli">Broccoli<br><br>
<input type="submit" value="" name="Bestellen" value="Bestellen"><br>
</form>
</body>
</html>
So how do I say when pepperoni is selected echo "You ordered pepperoni pizza."
This is my PHP Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$pep = $_POST["pepperoni"];
$ana = $_POST["ananas"];
$ans = $_POST["ansjovis"];
$bro = $_POST["broccoli"];
?>
</body>
</html>
You can give the radio buttons all the same name with different values. So you can select 1.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Pizza</h1>
<form method="POST" action="pizza.php">
Wat op pizza:<br>
<input type="radio" value="Pepperoni" name="type">Pepperoni<br>
<input type="radio" value="Ananas" name="type">Ananas<br>
<input type="radio" value="Ansjovis" name="type">Ansjovis<br>
<input type="radio" value="Broccoli" name="type">Broccoli<br><br>
<input type="submit" name="Bestellen" value="Bestellen"><br>
</form>
</body>
</html>
And in PHP you can read
<?php
echo $_POST['type']; //Pepperoni, ananas(pineapple?) etc.
?>
Good luck!
Radio buttons let a user select ONLY ONE of a limited number of choices, There for your radio button will need to have one name attribute for that particular groups of items. Then will have different values.
Your form should look like this :
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Pizza</h1>
<form method="POST" action="pizza.php">
Wat op pizza:<br>
<input type="radio" value="pepperoni" name="pizzaType">Pepperoni<br>
<input type="radio" value="ananas" name="pizzaType">Ananas<br>
<input type="radio" value="ansjovis" name="pizzaType">Ansjovis<br>
<input type="radio" value="broccoli" name="pizzaType">Broccoli<br><br>
<input type="submit" value="Bestellen" name="Bestellen" value="Bestellen"><br>
</form>
</body>
</html>
as you can see above all the radios have the same name attribute pizzaType
Then on pizza.php you need to execute the script when the submit button is clicked, then check if an option was selected, if option was selected then return the choice user selected, if they did not return a message that the user must atleast select an item.
your pizza.php should look like:
<?php
if(isset($_POST['Bestellen'])){ //button clicked
if(isset($_POST['pizzaType'])){//check if choice is checked
echo "You ordered ".$_POST['pizzaType']. " pizza";
}else{
echo "Please select an option";
die();
}
}
?>
NB: For your own good you will also need to learn how to validate and sanitize user inputs. This is very important, you must always treat form submissions as if they from a very dangerous hacker, which it's very important to filter and sanitize the user input before using it.
If you choose a pizza you can just pick 1. So you have to give every radio the Name pizzaName for example and for value you can use the Name (pepperoni). If you press submit then you can just read the values with the PHP File like this:
$chosenPizza = $_POST['pizzaName'];
echo $chosenPizza;
And the output will be pepperoni!
Instead of having different names, make all your names the same and enter what you have as names now, as values. Then get the value by using $val = $_POST["yourvalue"];
eg:
<input type="radio" value="ananas" name="samenameforall">
$val = $_POST["samenameforall"];
You've misused the radio tag attributes a bit here. The type of pizza should be the value, not the name of the radio-button. So if you change the name to type, you can use the following line in PHP to (safely) echo out the user's choice:
// If we have something submitted, process the form,
if (isset ($_POST['order'])) {
// Pepperonies are special!
if ($_POST['type'] == 'pepperoni') {
$output = "Congrats! You ordered pepperoni!";
} else {
// Use of htmlspecialchars () to prevent XSS attacks.
$output = "You ordered ".htmlspecialchars ($_POST['type'], ENT_QUOTES, 'UTF-8')." pizza.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<h1>Pizza</h1>
<form method="POST" action="pizza.php">
<fieldset>
<legend>Wat op pizza:</legend>
<input type="radio" id="pepp" value="pepperoni" name="type"><label for="pepp">Pepperoni</label>
<input type="radio" id="anna" value="ananas" name="type"><label for="anna">Ananas</label>
<input type="radio" id="ansj" value="ansjovis" name="type"><label for="ansj">Ansjovis</label>
<input type="radio" id="brocc" value="broccoli" name="type"><label for="broc">Broccoli</label>
</fieldset>
<fieldset>
<input type="submit" name="order" value="Bestellen">
</fieldset>
</form>
<?php
// Only show output if there is something to show.
if (!empty ($output)) {
echo "<p>$output</p>";
}
?>
</body>
</html>
Note the use of htmlspecialchars () here, as it's used to prevent XSS attacks.
When working with radio buttons, you should group them with the same name of the radio element. Take a look at this:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<?php
$toppings = filter_input(INPUT_POST, "toppings");
?>
<h1>Pizza</h1>
<form method="POST" action="pizza.php">
Wat op pizza:<br>
<input type="radio" value="pepperoni" name="toppings">Pepperoni<br>
<input type="radio" value="ananas" name="toppings">Ananas<br>
<input type="radio" value="ansjovis" name="toppings">Ansjovis<br>
<input type="radio" value="broccoli" name="toppings">Broccoli<br><br>
<input type="Submit" value="Bestellen">
<?php
echo "<br>";
if($toppings != "") {
echo "You ordered $toppings pizza. ";
}
?>
</form>
</body>
<input type="radio" value="pepperoni" name="type">Pepperoni<br>
<input type="radio" value="ananas" name="type">Ananas<br>
<input type="radio" value="ansjovis" name="type">Ansjovis<br>
<input type="radio" value="broccoli" name="type">Broccoli<br><br>
do like this .
i'm trying to create a dynamic web page where i have 4 radio button like the following :
Do you want to sleep ? yes No ( as button ) and a submit button.
Do you want to eat ? yes No ( as button ) and a submit button.
then I want to take the response and place it into mysql database. This is my php code :
<html>
<head>
<meta http-equiv="refresh" content="30">
<meta charset="UTF-8">
</head>
<body>
<form method="post" action="action_page.php">
<label class="heading"> do you want to eat ?<label/>
<input type="radio" name="radio" value="yes_1" checked> yes
<input type="radio" name="radio" value="no_1"> No
<input type="submit">
</form>
<br>
<br>
<?php
$dsn = 'mysql:host=localhost;dbname=mydb';
$username = 'root';
$password = '1234';
$dbh = new PDO($dsn, $username, $password);
if (isset($_POST['submit'])) {
if(isset($_POST['radio']))
{
echo "<span>You have selected :<b> ".$_POST['radio']."</b></span>";
}
else{ echo "<span>Please choose any radio button.</span>";}
}
?>
<form action="action_page.php">
<label> do you want to sleep ?<label/>
<input type="radio" name="radio" value="yes_2" checked> Oui
<input type="radio" name="radio" value="no_2"> Non
<input type="submit" name="submit" value="confirmer" />
</form>
<form action="iotpage.php">
<?php
$dsn = 'mysql:host=localhost;dbname=mydb';
$username = 'root';
$password = '1234';
$dbh = new PDO($dsn, $username, $password);
//if(isset($_POST['submit']))
//{
//foreach ($_POST['radio'] as $select2)
//{
//echo "You have selected for hum:" .$select2; // Displaying Selected Value
//}
//}
?>
</body>
</html>
I've created a table in my sql db named action and it contains 2 columns one for the first question and the second for the second question . How can I modify my code to insert into my db .
Put a form with a radio in your html
<form action="action_page.php" method="post">
<fieldset>
<label class="heading"> Do you want to eat ?<label/>
<legend>Options:</legend>
Option One <input type="radio" name="eat" value="yes"/>
Option Two <input type="radio" name="eat" value="no"/>
<input type="submit" value="Save" />
</fieldset>
<fieldset>
<label> Do you want to sleep ?<label/>
<legend>Options:</legend>
Option One <input type="radio" name="sleep" value="yes"/>
Option Two <input type="radio" name="sleep" value="no"/>
<input type="submit" value="Save" />
</fieldset>
</form>
On your PHP side(if you use php) get the post value, construct you statement and execute it:
$eat = $_POST["eat"];
$statement = "INSERT INTO MyTable(option_name) VALUES($eat) ";
$sleep = $_POST["sleep"];
$statement = "INSERT INTO MyTable(option_name) VALUES($sleep) ";
Obviously this is to illustrate the principle you need to do a lot more if you want to create a nice code.
I'm Practising PHP programming. I have made a Registration Form which has
2 Text Area (For First Name and Last)
2 Radio Buttons (For Gender Selection - Haven't started work on that yet)
8 Check boxes (4 each for Subject and Hobbies)
I have a Database Table by the name of persons which has
5 Columns (FirstName,LastName,Gender,Subject,Hobbies)
The Data from the form is being fetched, but each check box is inserted in the next row below the name.
For example David Bekham the subject php asp and hobby tv reading instead of appearing on the same row and against the name of the record, they appear on the next row.
As this is my first time, my question is
Q1 :- Is that how a record for such a form supposed to appear?
Q2 :- If not then where/what is the problem?
Q3 :- Could you either help me radio button code or provide me an easy link to learn it.
HTML FORM
<!DOCTYPE>
<html>
<head>
<title>Insert Data</title>
</head>
<body>
<h1> Insert to Register </h1>
<form name="form1" method="post" action="insert.php" >
<fieldset>
<legend> Registration Form </legend>
FirstName <input type="text" name="a" value="Enter firstname"/>
<br/><br/>
LastName <input type="text" name="b" value="Enter lastname"/>
<br/><br/>
<h3> Gender selection </h3>
Male <input type="radio" name="gender"/> female <input type="radio" name="gender"/>
<br/><br/>
<h3> Subject selection </h3>
<input type="checkbox" name="sb[]" value="php"/> PHP
<br/>
<input type="checkbox" name="sb[]" value="asp"/> ASP.NET
<br/>
<input type="checkbox" name="sb[]" value="html"/> HTML
<br/>
<input type="checkbox" name="sb[]" value="css"/> CSS
<br/><br/>
<h3> Hobbies selection </h3>
<input type="checkbox" name="hb[]" value="tv"/> Tv
<br/>
<input type="checkbox" name="hb[]" value="pc"/> Computer
<br/>
<input type="checkbox" name="hb[]" value="book"/> Reading books
<br/>
<input type="checkbox" name="hb[]" value="games"/> Games
<br/><br/>
<input type="submit" name="submit" value="Submit"/>
</fieldset>
</form>
</body>
</html>
php file
<!DOCTYPE>
<html>
<head>
<title>Processing_Insert_main</title>
</head>
<body>
<?php
// =============== code for Connection_SQLi ==============================
$con=mysqli_connect("localhost","root","","Ismat_db");
//check connection
if(mysqli_connect_errno())
{
echo "Cannot connect to mysqli:" . mysqli_connect_error();
}
// =============== code for Submit_input type ================================
if(isset($_POST['submit']))
{
// ========== code for Name_TextArea ===============
$sqlta = "INSERT INTO persons(FirstName,LastName)VALUES ('$_POST[a]','$_POST[b]')";
if (!mysqli_query($con,$sqlta))
{
die('Error: ' . mysqli_error($con));
}
echo "record added for name<br/>";
// ====== code for subject_checkbox ================
$s = $_POST['sb'];
$how_many=count($s);
for($i=0;$i<$how_many;$i++)
{
echo "You Selected: " .$s[$i]."<br/>";
if(!mysqli_query($con,"INSERT INTO persons(Subject) VALUES('$s[$i]')"))
{
echo "Not Recorded".mysqli_error($con);
}
echo "Record Added for subject<br/>";
}
// ============ Code for Hobbies_checkbox ========================
$h = $_POST['hb'];
$how_many=count($h);
for($i=0;$i<$how_many;$i++)
{
echo "You Selected: " .$h[$i]."<br/>";
if(!mysqli_query($con,"INSERT INTO persons(Hobbies) VALUES('$h[$i]')"))
{
echo "Not Recorded".mysqli_error($con);
}
echo "Record Added for Hobby<br/>";
}
//============================================================
echo '<br/>'.''. "Back" . '';
}
?>
</body>
</html>
$gender=$_POST['gender'];
$chkhobby=implode(',',$_POST['chkhobby']);
<tr>
<th>Gender</th>
<td>
Male<input type="radio" name="gender" checked="checked" value="1">
Female<input type="radio" name="gender" checked="checked" value="0">
</td>
</tr>
<tr>
<th>Hobbies</th>
<td>
read<input id="check_1" type="checkbox" name="chkhobby[]" value="read">
write<input id="check_2" type="checkbox" name="chkhobby[]" value="write">
play<input id="check_4" type="checkbox" name="chkhobby[]" value="play">
</td>
</tr>
How is your table structured? I would need to see the structure to be able to give you an actual query but it looks to me like you are inserting each value into the database as part of a separate query (which will always result in separate rows being inserted in the database). If you are storing the persons firstname, lastname, hobbies, and sports, etc in one row of your table you would need to do your query and insert values in 1 query not separate queries. So if you are currently doing:
"INSERT INTO persons(FistName, LastName)VALUES ('$_POST[a]','$_POST[b]')";
"INSERT INTO persons(Subject) VALUES('$s[$i]')"
"INSERT INTO persons(Hobbies) VALUES('$h[$i]')"
you should rather do:
"INSERT INTO persons(FistName, LastName, Subject, Hobbies) VALUES('$_POST[a]','$_POST[b]','$s[$i]','$h[$i]')"
Also for correct HTML standards compliance, readability, and accessibility for people with text readers etc. you should insert the text for each input as a label. So what I mean is instead of:
<input type="checkbox" name="sb[]" value="php"/> PHP
<br/>
<input type="checkbox" name="sb[]" value="asp"/> ASP.NET
you should use:
<input type="checkbox" name="sb[]" id="checkbox_php" value="php"/><label for="checkbox_php">PHP</label>
<br/>
<input type="checkbox" name="sb[]" id="checkbox_asp" value="asp"/><label for="checkbox_asp">ASP.NET</label>
Then you can use CSS to arrange the labels and checkboxes as you wish (float, etc). For checkboxes to appear correctly and vertically aligned with their labels I normally use tables. This is not ideal (as it's not the intended use of tables) but it gets around cross browser issues (and older browser issues) of the vertical alignment of these items in some browsers as well as keeps the label on the same line as the checkbox itself. For example:
<table>
<tr>
<td><input type="checkbox" name="sb[]" id="checkbox_php" value="php"/></td>
<td><label for="checkbox_php">PHP</label></td>
</tr>
</table>
On a side note your code is very vulnerable to SQL injection. You should read up about mysql_real_escape_string or mysqli_real_escape_string (if you use the MySQLi extensions).