Explode Checkbox looping php - php

I want explode data from table "school_minat"
into checklist in checbox looping table from "dayaminat".
I already try, but my checklist show only one. whereas my data minat_id in table school_minat 4 data = smk2,smk3,smk1,smk4
<center>
<?php $sql = "select * from dayaminat";
$rs = mysql_query($sql);
$i = 0;
while($row = mysql_fetch_array($rs)){ // Looping data from Table "dayaminat"
?>
<input name='minat[]'
<?php
$values = $result['minat_id']; // Data "minat_id" already Selected in Database table "school_minat"
$array_of_values = explode(",", $values); //Explode Data "Minat" already Selected in Database table "school_minat"
if (in_array($row['minat_id'],$array_of_values)) {
echo 'checked="checked"';
}
?>
value='<?php echo $row['minat_id']?>' type='checkbox'> <?php echo $row['minat'] ?>
<?php
$i ++;
}?>
</center>
Help me. Thank's :)

You must loop in your $array_of_values
<center>
<?php $sql = "select * from dayaminat";
$rs = mysql_query($sql);
while($row = mysql_fetch_array($rs)){ // Looping data from Table "dayaminat"
$values = $result['minat_id']; // Data "minat_id" already Selected in Database table "school_minat"
$array_of_values = explode(",", $values); //Explode Data "Minat" already Selected in Database table "school_minat"
for($i = 0; $i < count($array_of_values); $i++) {
echo "<input name='minat[]' ";
if (in_array($row['minat_id'], $array_of_values)) {
echo 'checked="checked"';
}
?>
value='<?php echo $array_of_values[$i]; ?>' type='checkbox'> <?php echo $array_of_values[$i]; ?>
<?php
}
}?>
</center>

You are looping only through the database row. As there is just 1 row you get only 1 result.
So try looping through the array! Probably using foreach loop..
<center>
<?php $sql = "select * from dayaminat";
$rs = mysql_query($sql);
$i = 0;
while($row = mysql_fetch_array($rs)){ // Looping data from Table "dayaminat"
$values = $result['minat_id']; // Data "Minat" already Selected in Database table "school_minat"
$array_of_values = explode(",", $values); //Explode Data "Minat" already Selected in Database table "school_minat"?>
foreach ($array_of_values as $arrayItem){
<input name='minat<?php echo $i;?>'
<?php
if (in_array($row['minat_id'],$arrayItem)) {
echo 'checked="checked"';
}
?>
value='<?php echo $arrayItem ?>' type='checkbox'> <?php echo $arrayItem ?>
<?php
$i ++;
}
}?>
</center>

Related

Duplicate checkbox remove in php

I have two tables named bookings and packages. Checked checkboxes are retrieved from bookings table and are working perfectly. But I also need unchecked check boxes from packages table. The problem is checked checkbox values display again.
<?php
$get_pro = "select * from booking";
$result = mysqli_query($con, $get_pro);
$book_packages = $row_pro['Book_Packages'];
$book_packages = substr(trim($book_packages) , 0, -1);
$split_pkg = (explode(",", $book_packages));
if (!empty($split_pkg)) {
foreach ($split_pkg as $book_pkg) {
$checked = (in_array($book_pkg, $split_pkg)) ? 'checked="checked"' : '';
?>
<input type="checkbox" name="pkg_list_name[]" value="<?php echo $book_pkg; ?>" size="17" <?php echo $checked; ?>> <?php echo $book_pkg; ?> <br>
<?php
}
}
$get_pros = "select * from package";
$results = mysqli_query($con, $get_pros);
while ($row_pros = mysqli_fetch_array($results)) {
$package_name = $row_pros['Pkg_Name'];
if ($package_name != $split_pkg) {
echo "<input type='checkbox' data-parsley-required='true' value='$package_name' data-parsley-trigger='click' id='checkbox1' name='pkg_list_name[]'>
<label>$package_name</label><br> ";
} else {
}
}
?>
You shouldn't have two loops. You should only create the checkboxes from the package table. When you're creating those checkboxes, add checked="checked" if the package name is in $split_pkg.
$book_packages = trim($row_pro['Book_Packages']);
$split_pkg = array_map('trim', explode(',', $book_packages));
$get_pros = "select * from package";
$results = mysqli_query($con, $get_pros);
while ($row_pros = mysqli_fetch_array($results)) {
$package_name = $row_pros['Pkg_Name'];
$checked = (in_array($package_name, $split_pkg)) ? 'checked="checked"' : '';
echo "<label><input type='checkbox' data-parsley-required='true' value='$package_name' data-parsley-trigger='click' name='pkg_list_name[]' $checked>
$package_name</label><br> ";
}
BTW, it's not a good idea to to put comma-separated values in database columns. You should have a separate row for each booking. Then you would be able to join the two tables easily.

How to create dynamic insert query using php and mysql? [duplicate]

hi friends i'm creating a php page to import the data from a csv file into sql database..
here database table and number of fields are specified by user itself..
if user specifies 4 fields, then it is created using a for loop as follows..
<?php
include('connect.php');
$name = $_POST['table_name'];
//echo $name;
$create_tab = "CREATE TABLE $name(id varchar(15) PRIMARY KEY)";
if(mysql_query($create_tab,$con))
{
echo "Table <b><i>$name</i></b> created successfully... <br/> <br/>Add columns...";
}
else {
die('Error1'.mysql_error());
}
$field = $_POST['number_of_fields'];
//echo $name.$field;
echo '<form id="form1" name="form1" method="post" action="update-table.php">';
echo "<p>
<label for='tablename'></label>
<input type='hidden' name='tablename' id='tablename' value='$name' size='5'/>
</p>";
echo "<p>
<label for='fields'></label>
<input type='hidden' name='fields' id='fields' value='$field' size='5'/>
</p>";
echo '<table border="1" cellpadding="5" cellspacing="5">';
for ( $i = 1; $i <= $field; $i ++) {
echo '<tr>';
echo '<td>';
echo "<p>
$i
</p>";
echo'</td>';
echo '<td>';
echo "<p>
<label for='textfield$i'></label>
<input type='text' name='field$i' id='textfield$i' />
</p>";
echo'</td>';
echo '<td>';
echo "
<select name='select$i' id='select$i'>
<option value='varchar(200)'>varchar</option>
<option value='int'>int</option>
<option value='float'>float</option>
<option value='date'>date</option>
</select>";
echo '</td>';
echo '</tr>';
}
echo '</table>';
?>
<p>File Location :
<input type="text" name="fileField" id="fileField" />
</p>
<br/>
<INPUT type="image" name="search" src="images/alter.gif" border="0" height="75" width=120">
</form>
then table create and alter as follows..
<?php
include('connect.php');
$field = $_POST[fields];
$name = $_POST[tablename];
for ( $i = 1; $i <= $field; $i++) {
//getting field names
$varname = ($txtfield . $i);
$$varname = $_POST[field.$i];
// echo $$varname;
$fi = $$varname;
//getting field types
$selname = ($selfield . $i);
$$selname = $_POST[select.$i];
$dt = $$varname;
$sql = "ALTER TABLE $name ADD $fi $dt";
if(mysql_query($sql,$con))
{
echo "Field <b><i>$fi</i></b> added successfully...<br/>";
}
else {
die('Error1'.mysql_error());
}
}
?>
as above database table and fields are crated...
i got the concept of inserting data using static variables as follows..
<?php
// data import
include('connect.php');
$field = $_POST['fileField']; //file directory
echo "<br/><br/>Import file path: ";
echo $field;
$file = $field;
$lines = file($file);
$firstLine = $lines[0];
foreach ($lines as $line_num => $line) {
if($line_num==0) { continue; } //escape the header column
$arr = explode(",",$line);
$column1= $arr[0];
$column2= $arr[1];
// ' escape character
if (strpos($column2, "'") == FALSE)
{
$column21 = $column2;
}
else{
$column21 = str_replace ("'", "\'", $column2);
}
$column3= $arr[2];
$column4= $arr[3];
//print data from csv
echo "<table border='1' width='800' cellpadding='5' cellspacing='2'>";
echo "<tr>";
echo "<td width='8'>";
echo $column1;
echo "</td>";
echo "<td width='100'>";
echo $column21;
echo "</td>";
echo "<td width='5'>";
echo $column3;
echo "</td>";
echo "<td width='5'>";
echo $column4;
echo "</td>";
echo "</tr>";
echo "</table>";
$import="INSERT into $name (id,name,year1,year2) values(
'$column1','$column21','$column3','$column4')";
mysql_query($import) or die(mysql_error());
}
?>
now, my question is how can i make this insert statement dynamic as such it creates field names and values dynamically inside insert query from the data obtained from for loop in table create and alter query???
If I understand your question correctly, it sounds like you want to combine your inserts into one query (which is very smart performance wise). SQL allows you to insert multiple rows at once like so:
INSERT INTO table (id, first, last) VALUES(NULL, 'Ryan', 'Silvers'),(NULL, 'Oscar', 'Smith'),(NULL, 'Jessica', 'Owens')
So by using creating an array of VALUES and using implode to join them you can make one query:
//Create rows
foreach($rows as $row) {
$queryRows[] = "(NULL, '".$row['first']."', '".$row['last']."')";
}
//Create query
$query = 'INSERT INTO table (id, first, last) VALUES'.implode(',', $queryRows);
Now that I understand your real question, I can give you a basic overview of what you need to do to achieve this. You need to create a form that allows a user to enter data that will be inserted into the table.
<form method="post" action="process.php">
<input name="field1" />
<!-- and more -->
</form>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
<?php
//Check form submission and validate entries, then...
$stmt = $pdo->prepare('INSERT INTO table (field1) VALUES(:field1)');
$stmt->execute(array(':field1', $_POST['field1']));
?>
Then you need to write a PHP script to process the form submission and insert the data into MySQL:
function insert($tablet,$datad)
{
if(empty($tablet)) { return false; }
if(empty($this->CONN)){ return false; }
$conn = $this->CONN;
$query1 = "select * from user";
$result1 = mysql_query($query1);
$numcolumn = mysql_num_fields($result1);
$addd = "";
$count = 0;
for ( $i = 1; $i < $numcolumn; $i++ )
{
$columnnames = mysql_field_name($result1, $i);
if(($numcolumn-1) == $i)
{
$addd .= $columnnames;
$data .= "'".$datad[$count]."'";
}
else
{
$addd .= $columnnames.",";
$data .= "'".$datad[$count]."',";
}
$count++;
}
$ins = "INSERT INTO ".$tablet."(".$addd.")"."VALUES(".$data.")";
mysql_query($ins);
header('Location: index.php');
exit;
}

PHP - Explode or Implode Values into an Array?

I'm creating a simple survey and I want the values in the column to be just (1) one row and separated with "|". But the only problem is, how do I save those values that I've got from the $_POST into an array on my database? For example:
Male|Employed|Married| instead of this...
<?php
$cnt = 1; // VARIABLE FOR QUESTIONS //
$query = "SELECT * FROM questions";
$result = mysqli_query($connection, $query);
while ($row = mysqli_fetch_object($result))
{
$choices = explode ("|", $row->choices);
if(isset($_POST['submit_post']))
{ // eq - radio button name (choices) for $cnt - question # //
$choice = $_POST["eq$cnt"]; // What to do in this $_POST part? //
$query = "INSERT INTO users(answers)";
$query .= "VALUES ('{$choice}')";
$create_post_query = mysqli_query($connection, $query);
}
?>
<form action="" method="post">
<?php
if($row->num ==0)
{
$num=" ";
} else
{
$num=$row->num.". ";
}
?>
<p id="eqIdentify_<?php echo $cnt ?>"><strong><?php echo $num; echo $row->questions; ?></strong> <?php ?> <?php echo $cnt; ?>
<?php
// VARIABLE FOR CHOICES //
for($a=0;$a<count($choices);$a++)
{
?>
<br/><label><input type="radio" name="eq<?php echo $cnt;?>" value="<?php echo $choices[$a] ?>" /><?php echo $choices[$a]?></label>
<?php
}
?>
<?php
$cnt = $cnt + 1;
}
?>
<input type="submit" name="submit_post">
</form>
change your table structure so you have a field for each of the questions.
like
ID Question1 Question2
and then change your insert query such
INSERT INTO `answers`( `question1`, `question2`, `question3`, `question4`) VALUES ([value-2],[value-3],[value-4],[value-5])
But please please look in to PDO and prepared query's

Saving 2 textbox array in database PHP/MYSQL

I have 2 textbox array,
questions & correct answer...
the problem is , i cannot save it to the the database
questions should be saved to "test" field in database
and correct answer should be saved to "test2" field...
code for the textbox
echo "<label for='textfield[]' align='left'> Question </label>";
echo "<br/>";
echo "<input type='text' name='textfield[]'>";
echo "<br/>";
echo "<label for='textfield2[]' align='left'> Correct Answer </label>";
echo "<br/>";
echo "<input type='text' name='textfield2[]'>";
echo "<br/>";
code for inserting values in database
$sql = array();
foreach($_POST['textfield'] as $textfield){
foreach($_POST['textfield2'] as $textfield2){
$sql[] = "INSERT INTO practice (test,test2) VALUES ('{$textfield}','{$textfield2}')";
}
}
foreach($sql as $query){
mysqli_query($con,$query);
}
}
You can insert like this,
<?php
$post_count = count($_POST['textfield']);
$post1 = array();
$post2 = array();
$post1 = $_POST['textfield'];
$post2 = $_POST['textfield2'];
for ($i = 0; $i <= $post_count; $i++) {
$sql[] = "INSERT INTO practice (test,test2) VALUES ('".$post1[$i]."','".$post2[$i]."')";
}
foreach ($sql as $query) {
mysqli_query($con, $query);
}
?>

PHP Foreach loop problem with mySQL INSERT INTO

I am having a big issue.
This is the first time I sue a foreach and I do not even know if it's the right thing to use.
I have a textarea where my members can add some text.
They also have all the accounts where to send the posted text.
Accounts are of two types F and T.
They are shown as checkboxes.
So when a member types "submit" the text should be INSERTED in a specific table for EACH of the selected accounts. I thought php foreach was the right thing. But I am not sure anymore.
Please take in mind I do not know anything about foreach and arrays. So please when helping me, consider to provide the modded code =D . Thank you so much!
<?php
require_once('dbconnection.php');
$MembID = (int)$_COOKIE['Loggedin'];
?>
<form action="" method="post">
<p align="center"><textarea id="countable1" name="addit" cols="48" rows="10" style="border-color: #ccc; border-style: solid;"></textarea>
<br>
<?
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$on="on";
$queryF ="SELECT * FROM `TableF` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryF) or die("Errore select from TableF: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "F" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="f[<?php echo $rowid?>]" <?php echo $checkit;?>>
</div>
<?
}//END WHILE MYSQL
}else{
echo "you do not have any Active account";
}
$DB = new DBConfig();
$DB -> config();
$DB -> conn();
$queryTW ="SELECT * FROM `TableT` WHERE `Active`='$on' AND `memberID`='$MembID' ORDER BY ID ASC";
$result=mysql_query($queryTW) or die("Errore select TableT: ".mysql_error());
$count = mysql_num_rows($result);
if ($count > 0)
{
while($row = mysql_fetch_array($result)) {
?><div style="width:400px; height:100px;margin-bottom:50px;"><?
$rowid = $row['ID'];
echo $row['Name'] . '</br>';
$checkit = "checked";
if ($row['Main'] == "")
$checkit = "";
if ($row['Locale'] =="")
$row['Locale'] ="None" . '</br>';
echo $row['Locale'] . '</br>';
if ($row['Link'] =="")
$row['Link'] ="javaScript:void(0);";
?>
<!-- HERE WE HAVE THE "T" CHECKBOXES. $rowid SHOULD BE TAKEN AND INSERTED IN THE FOREACH BELOW FOR ANY SELECTED CHECKBOX IN THE FIELD "Type".SEE BELOW -->
<input type="checkbox" name="t[<?php echo $rowid?>]" <?php echo $checkit;?> >
</div>
<?
}//END 2° WHILE MYSQL
}else{
echo "you do not have any Active account";
}
?>
<input type="submit" value="submit">
</form>
<?
//WHEN CHECKBOXES "F" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "F" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['f'])){
$thispostF = $_POST['f'];
$f="F";
foreach ($thispostF as $valF)
//THE MOST IMPORTANT FIELD HERE IS "Type". THE ARRAY INSERT "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddF="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$f."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
//WHEN CHECKBOXES "T" ARE FOUND, FOR EACH CHECKBOX IT SHOULD INSERT INTO TableG THE VALUES BELOW, FOR EACH SELECTED "T" CHECKBOX
if(!empty($_POST['addit']) && !empty($_POST['t'])){
$thispostT = $_POST['t'];
$t="T";
foreach ($thispostT as $valF)
//THE MOST IMPORTANT VALUE HERE IS "Type". THE ARRAY GIVES "on", I NEED INSTEAD THE VALUE $rowid AS ABOVE
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
?>
foreach ($thispostT as $valF)
{
$queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
please put start and ending bracket to your foreach loop and try i have not read the whole code but just found you missing the brackets. hope that helps you.
I think I know what you're doing...
You're going to need to do:
foreach($_POST as $key => $value) {
$type = substr($key,0,1);
$id = substr($key,1);
if($type == 't') {
// do insert for t table here
} else if($type == 'f') {
// do insert for f table here
}
}
I didn't test it but it should be something like this.
My suggestion is
create field name as t[] (array)
onchecked value will be passed on the next page
the form checkbox field should be like that
<input type="checkbox" name="t[]" value="< ?php echo $rowid?>" <?php echo $checkit;? > >
and when you Submit the form
GET THE VALUE and insert in to database;
< ?
if($_POST['t'])
{
foreach($_POST['t'] as $v)
{
queryaddT="INSERT INTO TableG (ID,memberID,Type,IDAccount,Tuitting) VALUES (NULL,".$MembID.",'".$t."','".$valF."', '".$_POST['addit']."')";
$resultaddF=mysql_query($queryaddF) or die("Errore insert G: ".mysql_error());
}
}
? >

Categories