Issue inserting multiple rows using PHP/SQL - php

This is the form in which I am using to try and create multiple rows to insert into a database.
<input name="input[]" type="checkbox" value="0" id="input_0" /> Directional<br /> <br/>
<input name="input[]" type="checkbox" value="1" id="input_1" /> Technical <br />
<br />
<input name="input[]" type="checkbox" value="2" id="input_2" /> Reference <br />
<br />
<input name="input[]" type="checkbox" value="3" id="input_3" /> Research <br />
<br />
<input name="input[]" type="checkbox" value="4" id="input_4" /> Phone <br /></h3>
<input type="submit" name="button" id="button" value="Submit Tally" style="height: 25px; width: 100px">
</Form>
Current issue of inserting multiple rows into mysql database from a checkbox form using implode. Would a loop work to fix this issue? I can see the array (#,#,#,#) when check boxes are selected
$type = $_POST['input'];
// $sid = $_SERVER['REMOTE_ADDR'];
$user = $_POST['user'];
if(count($type) > 0)
{
$type_string = implode(',', $type);
}
$sql = "INSERT INTO tally (tid, sid, uid, date, time, catid)
VALUE (NULL, 1, '$user', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, '$type_string')";
mysql_query($sql) or die(mysql_error());
echo "Success";
print_r($type_string);

A loop would certainly work, after you created some array from that $type variable you receive as input, and feed this into your query one at the time.
But I hope you're not going to use this code in some website just like this. As maiotano84 already commented, the way you create your query is a little dangerous. It is very easy to do some unwanted things with your data. At least you should put your variables through a function like
string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier = NULL ] )
Here is some more info on this function frm the php.net site.

compute the value of $type as below:
$i=0;
foreach ($_POST as $v) {
if(isset($v['input'.$i])) {
$type = $v;
$i++;
}
}

<Form action="" method="POST">
<input name="input[]" type="checkbox" value="0" id="input_0" /> Directional<br /> <br/>
<input name="input[]" type="checkbox" value="1" id="input_1" /> Technical <br />
<br />
<input name="input[]" type="checkbox" value="2" id="input_2" /> Reference <br />
<br />
<input name="input[]" type="checkbox" value="3" id="input_3" /> Research <br />
<br />
<input name="input[]" type="checkbox" value="4" id="input_4" /> Phone <br /></h3>
<input type="submit" name="button" id="button" value="Submit Tally" style="height: 25px; width: 100px">
</Form>
<?php
$type = $_POST['input'];
// $sid = $_SERVER['REMOTE_ADDR'];
$user = $_POST['user'];
for($i=0;$i<count($type);$i++){
$sql = "INSERT INTO tally (tid, sid, uid, date, time, catid)
VALUE (NULL, 1, '$user', CURRENT_TIMESTAMP, CURRENT_TIMESTAMP, ".$type[$i].")";
}
?>

Related

Custom HTML form submission error using admin_post hook

I have an HTML form which I have inserted using an HTML Code snippet on elementor. I want to connect it to my wordpress database. I have looked into wpdb-> insert function but can't get it to work. I am using wp-admin's action hook.
<html
<body>
<form action="https://www.example.com/wp-admin/admin-post.php" method="post" name="myform">
<!-- ####################################################### --><br><br>
<h3>Option1 </h3>
<input type="radio" name="a" id="1" value="1" /> None of the time
<input type="radio" name="a" id="1" value="2" /> Rarely
<input type="radio" name="a" id="1" value="3" /> Some of the Time
<input type="radio" name="a" id="1" value="4" /> Often
<input type="radio" name="a" id="1" value="5" /> All of the Time
<br /><br />
<!-- #############################################################-->
<h3> Option2 </h3>
<input type="radio" name="p" id="High" value="1" /> None of the time
<input type="radio" name="p" id="Medium" value="2" /> Rarely
<input type="radio" name="p" id="Low" value="3" /> Some of the Time
<input type="radio" name="p" id="Medium" value="4" /> Often
<input type="radio" name="p" id="Medium" value="5" /> All of the Time <br /><br />
<!-- ########################################################## -->
<input type="hidden" name="action" value="compass_data">
<br />
<br />
<h3><span id="msg"></span></h3>
</form>
<input type="submit" value="SUBMIT" name="submit" onclick="setTimeout(validate, 1500)" />
<br /><br />
<script>
/* Some functions here*/
</script>
</body>
</html>
Above JS has a variable that needs to be stored in the database. I am using PHP code snippet plugin to put following PHP code. My question is that where should I put this PHP code in functions.php or PHP snippet?
add_action('admin_post_compass_data','storedata_compass',11);
add_action('admin_post_nopriv_compass_data','storedata_compass',11);
function storedata_compass(){
if(isset($_POST['SUBMIT'])){
global $wpdb;
$user = wp_get_current_user();
$userId = $user->ID;
$user_data = get_userdata($user_id);
$data = array('Student Id' => $userId, 'First Name' => $user_data -> user_firstname, 'Email' => $user_data -> user_email, 'Group Id' => 2, 'Intro Selection' => 'DBTEST', 'End Selection' => 'test2');
$format = array('%d', '%s', '%s', '%d', '%s', '%s');
$wpdb->insert( 'wpqc_compass', $data, $format);
}
}
Your php code is a bit broken where you set the $tablename
It should be $tablename = $wpdb->prefix . 'compass'
And not $tablename = $wpdb-> 'compass';
But you should get an error when you are trying to run that php code. But you should maybe add it into functions.php.
And you should also not just listen to $_POST['submit'] because if you have any other form that has a button with the name "submit" it will trigger this php script also.

PHP saved twice when submitting to mySQL

I am using wordpress as a platform for my website and wrote following code to submit a form to mySQL database. The problem is, whenever I submit a from, it appears twice on the database. I am wondering what caused the problem.
<?php
echo $sql;
$name='';
$Gender=0;
$HPV=0;
$HIV=0;
$Herpes=0;
$symptoms=0;
$diagnosed=0;
$A=0;
$E=0;
$C=0;
$QNumber=0;
?>
<?php if (isset($_POST['submit'])) {
$db_host = 'localhost';
$db_user = '';
$db_pwd = '';
$database='';
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($database);
$name= $_POST['username'];
if (isset($_POST['Female'])) {$Gender=1;}
if (isset($_POST['Male'])) {$Gender=2;}
if (isset($_POST['Herpes'])) {$Herpes=1;}
if (isset($_POST['HPV'])) {$HPV=1;}
if (isset($_POST['HIV'])) {$HIV=1;}
if (isset($_POST['Symptoms'])) {$symptoms=1;}
if (isset($_POST['Diagnosed'])){ $diagnosed=1;}
if (isset($_POST['Awareness'])){ $A=1;}
if (isset($_POST['Education'])){ $E=1;}
if (isset($_POST['Counseling'])){ $C=1;}
$Qnumber=$_POST['Number'];
$sql = "INSERT INTO QuestionAnswer (name, HPV,HIV,Herpes,Reach,Gender,Awareness,Education,Counseling,Symptoms,Diagnosed)
VALUES ('" . $name . "',$HPV,$HIV,$Herpes,$QNumber,$Gender,$A,$E,$C,$symptoms,$diagnosed)";
mysql_query($sql);
mysql_close();
} ?>
<h2>Data Entery</h2>
<form enctype="multipart/form-data" method="post" action="" >
Name: <input name="username" type="text" />
Gender : <input name="Female" type="checkbox" />Female <input name="Male" type="checkbox" />Male
Diseases: <input name="Herpes" type="checkbox" />Herpes <input name="HPV" type="checkbox" />HPV <input name="HIV" type="checkbox" /> HIV
Symptoms: <input name="Symptoms" type="checkbox" /> Yes
Diagnosed: <input name="Diagnosed" type="checkbox" /> Yes
Number of Q&A : <input name="Number" type="text" />
Awareness: <input name="Awareness" type="checkbox" /> Yes
Education: <input name="Education" type="checkbox" /> Yes
Counseling: <input name="Counseling" type="checkbox" /> Yes
<input name="submit" type="submit" value="submit" />
</form>
Simply use the Redirect Header, to avoid Duplication. Some time it may hit twice, to avoid use the following header.
header('Location: page.php');
You can specify the actual file name (or) URL instead of page.php
Your PHP Source Code should be
<?php
$name='';
$Gender=0;
$HPV=0;
$HIV=0;
$Herpes=0;
$symptoms=0;
$diagnosed=0;
$A=0;
$E=0;
$C=0;
$QNumber=0;
if (isset($_POST['submit'])) {
$db_host = 'localhost';
$db_user = '';
$db_pwd = '';
$database='';
mysql_connect($db_host, $db_user, $db_pwd);
mysql_select_db($database);
$name= $_POST['username'];
if (isset($_POST['Female'])) {$Gender=1;}
if (isset($_POST['Male'])) {$Gender=2;}
if (isset($_POST['Herpes'])) {$Herpes=1;}
if (isset($_POST['HPV'])) {$HPV=1;}
if (isset($_POST['HIV'])) {$HIV=1;}
if (isset($_POST['Symptoms'])) {$symptoms=1;}
if (isset($_POST['Diagnosed'])){ $diagnosed=1;}
if (isset($_POST['Awareness'])){ $A=1;}
if (isset($_POST['Education'])){ $E=1;}
if (isset($_POST['Counseling'])){ $C=1;}
$Qnumber=$_POST['Number'];
$sql = "INSERT INTO QuestionAnswer (name, HPV,HIV,Herpes,Reach,Gender,Awareness,Education,Counseling,Symptoms,Diagnosed)
VALUES ('" . $name . "',$HPV,$HIV,$Herpes,$QNumber,$Gender,$A,$E,$C,$symptoms,$diagnosed)";
mysql_query($sql);
mysql_close();
header('Location: page.php');
} ?>
<h2>Data Entery</h2>
<form enctype="multipart/form-data" method="post" action="" >
Name: <input name="username" type="text" />
Gender : <input name="Female" type="checkbox" />Female <input name="Male" type="checkbox" />Male
Diseases: <input name="Herpes" type="checkbox" />Herpes <input name="HPV" type="checkbox" />HPV <input name="HIV" type="checkbox" /> HIV
Symptoms: <input name="Symptoms" type="checkbox" /> Yes
Diagnosed: <input name="Diagnosed" type="checkbox" /> Yes
Number of Q&A : <input name="Number" type="text" />
Awareness: <input name="Awareness" type="checkbox" /> Yes
Education: <input name="Education" type="checkbox" /> Yes
Counseling: <input name="Counseling" type="checkbox" /> Yes
<input name="submit" type="submit" value="submit" />
</form>

PHP var_dump only outputting value of bottom checkbox

Hi and thanks for reading my question. I am using a simple form to get some input :
<p>Select your favorite two countries below:</p>
<form id="world" name="world" action="/order.php" method="post">
<input type="checkbox" name="countries" value="USA" /> USA<br />
<input type="checkbox" name="countries" value="Canada" /> Canada<br />
<input type="checkbox" name="countries" value="Japan" /> Japan<br />
<input type="checkbox" name="countries" value="China" /> China<br />
<input type="checkbox" name="countries" value="France" /> France<br />
<input type="submit" value="Order">
</form>
I want to make sure order.php is geting all of the choices selected, so order.php only contains the following code :
<pre>
<?php var_dump($_POST);?>
</pre>
Unfortunately, it is only outputting whatevre is the bottom-most checkbox that is checked.
The output is like this :
array(1) {
["countries"]=>
string(6) "Canada"
}
If i try the following code for output :
<?php
foreach($_POST as $key=>$post_data){
echo "You posted:" . $key . " = " . $post_data . "<br>";
}
?>
I get this output :
You posted:countries = Canada
Can anyone tell me where i am going wrong and how i can retrieve all of the data, for every box that is ticked ?
Thank you.
You gave the same name to your checkboxes, and PHP will overwrite previously parsed name submissions with the current value. You need to use the array-notation hack:
<input type="checkbox" name="countries[]" value="Canada" /> Canada<br />
^^
which then makes $_POST['countries'] an array of all the values submitted.
echo "You posted: " . implode(',', $_POST['countries']);
<p>Select your favorite two countries below:</p>
<form id="world" name="world" action="/order.php" method="post">
<input type="checkbox" name="countries[]" value="USA" /> USA<br />
<input type="checkbox" name="countries[]" value="Canada" /> Canada<br />
<input type="checkbox" name="countries[]" value="Japan" /> Japan<br />
<input type="checkbox" name="countries[]" value="China" /> China<br />
<input type="checkbox" name="countries[]" value="France" /> France<br />
<input type="submit" value="Order">
</form>
Change it to above, this will store all your checkboxes results for you!

Using Checkbox Values in PHP

I have this page (code below) which contains a series of 5 checkboxes, all representing different values, and i need to use them to query a database.
<form id="form1" name="form1" method="post" align="center" action="section_search_results1.php">
<p>Select The <b>Section</b> You Wish To Search In Below... </p>
<p>
<label for="section"></label>
<label for="section2"></label>
<label>
<input type="checkbox" name="SectionSelect" value="Functional" id="SectionSelect_0" />
Functional</label>
<label>
<input type="checkbox" name="SectionSelect" value="Technical" id="SectionSelect_1" />
Technical</label>
<label>
<input type="checkbox" name="SectionSelect" value="Commercial" id="SectionSelect_2" />
Commercial</label>
<label>
<input type="checkbox" name="SectionSelect" value="Implementation" id="SectionSelect_3" />
Implementation</label>
<label>
<input type="checkbox" name="SectionSelect" value="Innovation" id="SectionSelect_4" />
Innovation</label>
<br />
</p>
<p>Enter the <b>Keyword(s) or Keyphrase</b> Below...</p>
<p>
<label for="kword"></label>
<input type="text" name="kword" id="kword" placeholder="Enter Keyword(s)" />
<br />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Search" /> | | <input type="reset" name="clear" id="clear" value="Clear" />
</p>
</form>
as you can see each has its own value which is the term used to query the database. the php query code on the results page is as follows
<?php
$kword = $_POST["kword"];
$section = $_POST["SectionSelect"];
function boldText($text, $kword) {
return str_ireplace($kword, "<strong>$kword</strong>", $text);
}
// Connects to your Database
mysql_connect("localhost", "root") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
mysql_real_escape_string($kword);
$data = mysql_query("select company_name, section_name, question, answer from company, rfp, section, question_keywords
where company.company_id = rfp.company_id
and rfp.rfp_id = question_keywords.rfp_id
and question_keywords.section_id = section.section_id
and section_name like '%$section%'
and keywords like '%$kword%';")
or die(mysql_error());
?>
ultimately what i want this to do is to query the database with the query to potentially have where clauses for each of the checkbox values? for example i want to select x where y like 'Technical' AND y like 'Functional' and so on...
Any help would be great
thanks
Set up your checkbox names as array-keys to use them as an array with values of all selected checkboxes:
<input type="checkbox" name="SectionSelect[0]" value="Functional" />
<input type="checkbox" name="SectionSelect[1]" value="Technical" />
echo $_POST['SectionSelect'][0]; // should print "Functional"
echo $_POST['SectionSelect'][1]; // should print "Technical"

insert proccess whith looping in php

firstly sorry my english is bad
then
i have problem
i try to make lopping insert into table but i have problem i can't make array for inputs
to can insert in table with looping from another table
maybe u can't understand me but look to the code and u will understand my problem
$select = mysql_query("SELECT * FROM table_name ");
?>
<form method="post" action="">
<?
while($row =mysql_fetch_array($select))
{
if($_POST['add'])
{
$updpol = mysql_query("insert into table_name2 (yes,no,maybe,g_id)
values
('".$_POST['yes']."','".$_POST['no']."','".$_POST['maybe']."','".$row['id']."')
")
}
else{
?>
<input type="checkbox" name="yes" value="1" />
<br />
<input type="checkbox" name="no" value="1" />
<br />
<input type="checkbox" name="maybe" value="1" />
<?
}
?>
<input type="submit" name="add_poll" value="submit" />
</form>
in your php code , your checking if:
if($_POST['add'])
While there's no input named add in your form.
I believe you meant:
if($_POST['add_poll'])
In order to have multiply instances of inputs , you can do something like:
<input type="checkbox" name="yes[]" value="1" />
<br />
<input type="checkbox" name="no[]" value="1" />
<br />
<input type="checkbox" name="maybe[]" value="1" />
So , now , when posted:
$_POST['yes'] is an array of all the checkboxes.
And as an array , it starts with $_POST['yes'][0] and continues $_POST['yes'][1] and so on.
Therefore:
$select = mysql_query("SELECT * FROM table_name ");
?>
<form method="post" action="">
<?
$i = 0;
while($row =mysql_fetch_array($select))
{
if($_POST['add_poll'])
{
$updpol = mysql_query("insert into table_name2 (yes,no,maybe,g_id)
values
('".$_POST['yes'][$i]."','".$_POST['no'][$i]."','".$_POST['maybe'][$i]."','".$row['id']."')
");
$i++;
}
else{
?>
<input type="checkbox" name="yes[]" value="1" />
<br />
<input type="checkbox" name="no[]" value="1" />
<br />
<input type="checkbox" name="maybe[]" value="1" />
<?
}
?>
<input type="submit" name="add_poll" value="submit" />
</form>

Categories