add values into selection table from multiple table - php

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 /> ");
}
}
?>

Related

In my HTML form with radio buttons and an 'other' text field the values of the radio buttons are not understood

I'm trying to create a HTML form which inserts all entered values into a MySQL database through php.
Specifically for this case, the user enters a product number and a supplier.
The supplier should be defined by radio buttons and an additional 'other' text field where the user can specify another option...
When the user chooses the 'other' option, the value typed there is inserted in the MySQL DB correctly, however when choosing one of the radio buttons, not the supplier is inserted but the text 'on'...
I don't understand why the script does this, since I don't have the value 'on' anywhere in the script.
I've searched google and stackoverflow, and tried many things, but I'm still failing to get it to work. I'm a php and html newb so please go easy on me.
Below is a trimmed down version of the code. (In real, the script also submits more fields from the form, the session username, and a timestamp.)
Does anyone see where the 'on' may come from and how to solve this? Thank you.
The php part of the code:
<?php
if (isset($_POST['submit'])) {
// These set your initial variables. q1_* is for the queried entries in the form
$q2_productname = $_POST['q2_productname'];
$q3_supplier = $_POST['q3_supplier'];
if ($q3_supplier =='other'){
$q3_supplier = $_POST['q3_supplier_other'];
}
if (isset($q2_productname)) {
$q2_productname = trim($q2_productname);
$q2_productname = strip_tags($q2_productname);
$q2_productname = stripslashes($q2_productname);
$q2_productname = htmlspecialchars($q2_productname);
}
if (isset($q3_supplier)) {
$q3_supplier = trim($q3_supplier);
$q3_supplier = strip_tags($q3_supplier);
$q3_supplier = stripslashes($q3_supplier);
$q3_supplier = htmlspecialchars($q3_supplier);
}
$dbc = #mysql_connect (DBHOST, DBUSER, DBPASS) or die('Failure: ' . mysql_error() );
mysql_select_db(DBNAME) or die ('Could not select database: ' . mysql_error() );
$query = "INSERT INTO orders VALUES ('$q2_productname','$q3_supplier')";
$q = mysql_query($query);
if (!$q) {
exit("<p>MySQL Insertion failure.</p>");
} else {
mysql_close();
}
Then the html/echo/script part of the code:
<?php
if (isset($_POST['submit'])) {
echo "<p style='padding: .5em; border: 2px solid red;'>Thank you. Your product has been added to the order list!</p>";
}
?>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<div>
<label for="q2">Full product name:</label><br />
<textarea id="q2" name="q2_productname" rows="1" cols="50"></textarea>
</div>
</fieldset><br /><br />
<fieldset>
<div>
<label for="q3">Supplier (e.g. Sigma-Aldrich, VWR, ...):</label><br />
<input type="radio" name="q3_supplier" id="q3" onchange="disableTxt()" checked="checked" />Sigma-Aldrich
<input type="radio" name="q3_supplier" id="q3" onchange="disableTxt()" />VWR
<input type="radio" name="q3_supplier" id="q3" onchange="enableTxt()" />Other:
<input type="text" name="q3_supplier_other" id="other" disabled="disabled" />
<script>
function disableTxt() {
document.getElementById("other").disabled = true;
}
function enableTxt() {
document.getElementById("other").disabled = false;
}
</script>
</div>
</fieldset><br /><br />
</form>
Set the value attribute of your radio inputs. This value will be posted to your server. The value will be 'on' unless you specify it.
<input type="radio" name="q3_supplier" id="q3" onchange="disableTxt()" checked="checked" value='Sigma-Aldrich'/>Sigma-Aldrich
<input type="radio" name="q3_supplier" id="q3" onchange="disableTxt()" value='VWR' />VWR
<input type="radio" name="q3_supplier" id="q3" onchange="enableTxt()" value='Other' />Other:
The default value of input[type=radio] is on.
I suggest you learn how to use Firebug or Chrome dev tools, in order to actually see what is really submitted and what comes back from the server.

how do i select multiple mysql records based on checked checkboxes?

on page 1 i have a form, then on page 2 which is the processor file, i want to select records based on the checked checkboxes that were checked on page 1.
<form action="output.php" method="post">
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="something else" />
<input type="checkbox" id="" class="" name="check_list[]" value="yet another thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
<input type="checkbox" id="" class="" name="check_list[]" value="some name" />
<input type="checkbox" id="" class="" name="check_list[]" value="some other name" />
<input type="submit" value="Submit" name="submit">
</form>
the following foreach can display all the values of everything that was checked, but i don't know how to take it further into my sql select statement to select all the records that have a column field by that name.
foreach($_POST['check_list'] as $check) {
echo $check . '<br>';
}
lets say in a table called stuff there are these fields
id, first_title, second_title
so i want to do the following, but obviously this isn't the way to write it. this is the part i need help with.
SELECT * FROM stuff WHERE first_title = $check or second_title = $check
lets us further say that these records exist in the table...
id first_title second_title
-----------------------------------------
1 something something else
2 yet another thing one more thing
3 some name some other name
then lets say these checkboxes were checked:
<input type="checkbox" id="" class="" name="check_list[]" value="something" />
<input type="checkbox" id="" class="" name="check_list[]" value="one more thing" />
so what i want to happen is for my select statement to select record 1 and record 2 and not record 3, because "something" is in the first_title column of the first record, and "one more thing" is in the second_title of the second record, and nothing was checked that is in third record.
i hope i gave as much detail as is needed. let me know if you need further explanation.
Use the SQL IN operator to test if a column is in a list of values. Here's how to write it with MySQLI:
$in_str = implode(', ', array_map(function($title) use ($con) {
return "'" . $con->real_escape_string($title) . "'";
}, $_POST['check_list']));
$sql = "SELECT * FROM stuff WHERE first_title IN ($in_str) OR second_title IN ($in_str)";
$result = $con->query($sql);
try this dynamic where condition in your code
<?php
$arr_where = array();
foreach($_POST['check_list'] as $check) {
$arr_where[] = " first_name='$check' OR last_name='$check' ";
}
$where_text = implode("OR", $arr_where);
$sql = "SELECT * FROM stuff WHERE ".$where_text;
?>

data overwriten when using checkbox

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']);

Registration Form - Checkbox Is Inserted on new rows in Database

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).

Bulk action using PHP for mysql entries

We are showing results in a table from a MySQL database with checkboxes inside it. How can we delete many rows simultaneously if the user ticks 5 rows and clicks the delete button?
HTML:
<form method="post">
<input type="checkbox" name="id[]" value="123" /> Element 1 <br/>
<input type="checkbox" name="id[]" value="5434" /> Element 2 <br/>
<input type="checkbox" name="id[]" value="24" /> Element 3 <br/>
<input type="checkbox" name="id[]" value="76" /> Element 4 <br/>
<input type="submit" value="delete" />
</form>
PHP:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$ids = array_walk($_POST['id'], 'intval');
mysql_query('DELETE FROM table WHERE id IN (' . implode(',', $ids) . ')');
}
P.S. I want points !
I won't give you the PHP code, but building an SQL query like this will solve your problem:
DELETE FROM foo WHERE id IN ( … );
See the manual for details.
With PDOStatement like this
$statement = "DELETE FROM table WHERE id = ?";
$conn = new PDO($dns,$user,$pass);
$conn->beginTransaction();
$query = $conn->prepare($statement);
foreach($params as $p){ //$params are your checked id's
$query->bindParam(1,$p);
if($query->execute()){
echo "ok";
}else{
$conn->rollBack();
exit("Error");
}
}
$conn->commit();

Categories