I have a php code that add/delete new row (tr)to the html table. One column(td) has text field and second column(td) has a drop down. Dropdown source is mysql table.
First row(tr) value are coming correctly. But dropdonwn list is null when I add new row(tr)
code is:
<html>
<head>
<title></title>
<style type="text/css">
input {
display: block; /* makes one <input> per line */
}
</style>
</head>
<?php
include 'dbconnection\dbconnection.php'; // Database connection
$count=1;
if(isset($_POST['btnadd']) == "ADD NEW ITEM") {
// add 1 to the row counter
if (isset($_POST['count'])) $count = $_POST['count'] + 1;
// set value for first load
else $count = 1;
}
if(isset($_POST['btnremove']) == "DELTE ITEM") {
// decrement the row counter
$count = $_POST['count'] - 1;
// set minimum row number
if ($count < 1) $count = 1;
}
?>
<body>
<!-- call same file on submit -->
<form name="form1" method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<?php
$cdquery="select cmc_id,cmc_name from cat_main_category";
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
echo '<table>';
// print $count rows
for ($i=1; $i<=$count; $i++) {
echo ' <tr> <td> <input type="text" name="text'.$i.'" align="center"> </td>';
echo '<td> <select id="basicgroup'.$i.'" name="basicgroup'.$i.'" onchange=reload(this.form)>';
echo '<option value=0>Select</option>';
while ($row=mysqli_fetch_array($result2)) {
$cdTitle=$row["cmc_name"];
$id=$row["cmc_id"];
//if($id==#$basicgroup){
echo "<option selected value=$id>
$cdTitle
</option>";
/*}
else{echo "<option value=$id>
$cdTitle
</option>""."<BR>";;*/
}
echo '</select></td></tr> ';
}
?>
</table>
<!-- you only need one set of buttons and only one counter for this script
because every button would do the same -->
<input type="submit" name="btnadd" id="btnadd" value="ADD NEW ITEM" >
<input type="submit" name="btnremove" id="btnremove" value="DELETE ITEM">
<input type="hidden" name="count" value="<?php echo $count; ?>">
</form>
</body>
</html>
After you executed MySQL query:
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
Save the results in the array like:
$categories = [];
while ($row=mysqli_fetch_array($result2)) {
$categories[$row["cmc_id"]] = $row["cmc_name"]
}
Then in your main loop:
for ($i=1; $i<=$count; $i++) {
echo ' <tr> <td> <input type="text" name="text'.$i.'" align="center"> </td>';
echo '<td> <select id="basicgroup'.$i.'" name="basicgroup'.$i.'" onchange=reload(this.form)>';
echo '<option value=0>Select</option>';
foreach ($categories as $id => $cdTitle) {
echo "<option selected value=$id>
$cdTitle
</option>";
}
echo '</select></td></tr>';
}
You current problem is on the first iteration you exhausting your MySQL query with mysqli_fetch_array and second select is empty
Change
<?php
$cdquery="select cmc_id,cmc_name from cat_main_category";
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
echo '<table>';
for ($i=1; $i<=$count; $i++) {
echo '<tr><td><input type="text" name="text'.$i.'" align="center"></td>';
echo '<td><select id="basicgroup'.$i.'" name="basicgroup'.$i.'" onchange=reload(this.form)>';
echo '<option value=0>Select</option>';
while ($row=mysqli_fetch_array($result2)) {
$cdTitle=$row["cmc_name"];
$id=$row["cmc_id"];
echo "<option selected value=$id>$cdTitle</option>";
}
echo '</select></td></tr>';
}
?>
</table>
To
<?php
echo '<table>';
for ($i=1; $i<=$count; $i++) {
$cdquery="select cmc_id,cmc_name from cat_main_category";
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
echo '<tr><td><input type="text" name="text'.$i.'" align="center"></td>';
echo '<td><select id="basicgroup'.$i.'" name="basicgroup'.$i.'" onchange=reload(this.form)>';
echo '<option value=0>Select</option>';
while ($row=mysqli_fetch_array($result2)) {
$cdTitle=$row["cmc_name"];
$id=$row["cmc_id"];
echo "<option selected value=$id>$cdTitle</option>";
}
echo '</select></td></tr>';
}
?>
</table>
Put,
$cdquery="select cmc_id,cmc_name from cat_main_category";
$result2=mysqli_query($conn,$cdquery) or die(mysqli_error());
inside for loop.
Related
I stored values from a form in SESSION variables but it seems that they are emptied after if(isset($_POST['submit']) even though I can echo them earlier in my code. The code runs and the insert works except for $toto and $tata which are empty.
In the code below _id, master_label, client_label are inserted correctly. And the target table fields match so the error does not come from there.
<?php
session_start();
[...]
echo "<form id='organization' action='?' method='POST' enctype='multipart/form-data' >" ;
echo "<select name='organization' onchange='this.form.submit()'>"; //
echo '<option value="">Select ORGANIZATION</option>';
while ($row=mysqli_fetch_array($result00)) {
echo '<option value="'.$row['company_id'].'">'.$row['company_id'].'</option>';
}
echo "</select>";
echo "</form>";
$cie_ticker = $_POST['organization'] ;
$_SESSION['company_id'] = $cie_ticker ;
$sql="(SELECT company_id, databasefile, company_name FROM `settings` WHERE company_id='$cie_ticker') LIMIT 1";
$result=mysqli_query($connect,$sql) or die('Could not execute the query ' . mysqli_error()) ;
$data_bis=$result->fetch_array() ;
$_SESSION['selected_cie_id'] = $data_bis['company_id'];
$_SESSION['selected_cie_name'] = $data_bis['company_name'];
<form id='demoForm' action="?" method="POST" enctype="multipart/form-data" target="_top">
<?php
$file = fopen('./company/'.$cie_ticker.'/'.$_SESSION['selected_cie_db'], "r") ; // $file = fopen('./company/'.$_SESSION["company_id"].'/'.$_SESSION['selected_cie_db'], "r") ;
$headers=fgetcsv($file, 1000, "|");
fclose($file);
?>
<table id="user_table">
<tr><th>HEADERS </th><th>MASTER DB HEADERS</th></tr>
<?php foreach ($headers as $entete) {
$query01="SELECT master_label FROM `mastertable`";
$result01=mysqli_query($connect,$query01); ?>
<tr id="<?php echo $entete;?>">
<td> <?php echo $entete ?></td>
<td id="<?php echo $row['_id'];?>">
<?php
echo "<br>";
echo "<select name=".$entete.">";
echo '<option value="MASTER DATA">Select MASTER DATA</option>';
while ($row=mysqli_fetch_array($result01)) {
echo '<option value="'.$row['master_label'].'">'.$row['master_label'].'</option>';
}
echo "</select>";
?>
</td>
</tr>
<?php } ?>
</table>
<input id="checkBtn" type="submit" name="submitbutton" value="SAVE" class="button"/>
</form>
if(isset($_POST['submitbutton'])) {
$toto = $data_bis['company_id'] ;
$tata = $data_bis['company_name'];
$selected=$_POST;
foreach($selected as $x => $x_value) {
$query= $connect->prepare("INSERT INTO `mytable` (_id, master_label, client_label, org_label, client_id) VALUES ('',?,?,?,?) ");
$query->bind_param('ssss',$x_value, $x, $toto, $tata );
$query->execute();
}
}
?>
I have found the answer:
In this case one must add hidden input for the $_SESSION variables otherwise they were lost after submitting the form.
I am having trouble creating an addition table for my php program. I created my multiplication table just fine (it creates the right output), but when I try and make an addition one the numbers arent inside the table and I cant figure out what I am doing wrong. I will post what my output looks like when I create an addition table, and what it is supposed to look like and also the code that I have wrote. I feel like I am very close to completing this program, but right now I am stuck, thanks for the help in advance.
Here is the output that I am supposed to get for a 4x5 addition table.
0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8
5 6 7 8 9
Here is my output .
11112222333344445555
0 1 2 3 4
1
2
3
4
5
And here is my code. Any help is appreciated.
<html>
<head/>
<body>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>" >
<table border="1">
<tr><td>Number of Rows:</td><td><input type="text" name="rows" /></td></tr>
<tr><td>Number of Columns:</td><td><select name="columns">
<option value="1">1</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="8">8</option>
<option value="16">16</option>
</select>
</td></tr>
<tr><td>Operation:</td><td><input type="radio" name="operation" value="multiplication" checked="yes">Multiplication</input><br/>
<input type="radio" name="operation" value="addition">Addition</input>
</td></tr>
</tr><td colspan="2" align="center"><input type="submit" name="submit" value="Generate" /></td></tr>
</table>
</form>
<?php
if(isset($_POST["submit"])){
//check to see if num of rows is numberic
if ( isset($_POST["rows"]) && is_numeric($_POST["rows"])){
//check to see if rows is a positive number
if($_POST["rows"] > 0){
if(isset($_POST) && $_POST["operation"] == "multiplication"){
echo 'This is a '. $_POST["rows"] . ' x ' . $_POST["columns"] .'multiplication table';
echo "<table border=1";
echo'<tr>';
for($b = 0; $b <= $_POST["columns"];$b++){
echo '<th>'.$b.'</th>';}
echo '</tr>';
for($r = 1; $r <= $_POST["rows"]; $r++){
echo'<tr><th>'.$r.'</th>';
for($c = 1; $c <= $_POST["columns"]; $c++){
echo '<td>' .$c*$r. '</td>';
}
echo '</tr>';
}
echo "</table>";
}
else if (isset($_POST) && $_POST["operation"] == "addition")
{
echo 'This is a '. $_POST["rows"]. ' x ' . $_POST["columns"] .' addition table';
echo "<table border = 1";
echo'<tr>';
for($a = 0; $a <= $_POST["columns"];$a++){
echo '<th>'.$a.'</th>';}
echo '</tr>';
for($r = 1; $r <= $_POST["rows"]; $r++){
echo '<tr><th>'.$r.'</th>';
for($c = 1; $c <= $_POST["columns"]; $c++)
{
echo '<td>' .$c+$r. '</td>';
}
echo '</tr>';
}
echo "</table>";
}
else{
echo 'Invalid rows columns parameters';
exit();
}
}
exit();
}}
?>
</body>
</html>
try this.
Note: i only changed elseif statement which you used for additioin, so you can just copy and paste this as i changes nothing else.
so i divided the solution in three part and leave comment in bold for you to know which part i changed. thanks.
and post the comment what should you do next. In case it did not give you desired out come.
<html>
<head/>
<body>
<form method="POST" action="<?= $_SERVER['PHP_SELF'] ?>" >
<table border="1">
<tr><td>Number of Rows:</td><td><input type="text" name="rows" /></td></tr>
<tr><td>Number of Columns:</td><td><select name="columns">
<option value="1">1</option>
<option value="2">2</option>
<option value="4">4</option>
<option value="8">8</option>
<option value="16">16</option>
</select>
</td></tr>
<tr><td>Operation:</td><td><input type="radio" name="operation" value="multiplication" checked="yes">Multiplication</input><br/>
<input type="radio" name="operation" value="addition">Addition</input>
</td></tr>
</tr><td colspan="2" align="center"><input type="submit" name="submit" value="Generate" /></td></tr>
</table>
</form>
<?php
if(isset($_POST["submit"])){
//check to see if num of rows is numberic
if ( isset($_POST["rows"]) && is_numeric($_POST["rows"])){
//check to see if rows is a positive number
if($_POST["rows"] > 0){
if(isset($_POST) && $_POST["operation"] == "multiplication"){
echo 'This is a '. $_POST["rows"] . ' x ' . $_POST["columns"] .'multiplication table';
echo "<table border=1";
echo'<tr>';
for($b = 0; $b <= $_POST["columns"];$b++){
echo '<th>'.$b.'</th>';}
echo '</tr>';
for($r = 1; $r <= $_POST["rows"]; $r++){
echo'<tr><th>'.$r.'</th>';
// for($c = 1; $c <= $_POST["columns"]; $c++){
// echo '<td>' .$c*$r. '</td>';
//}
echo '</tr>';
}
echo "</table>";
}
From here i change the code In case it does not give you desired outcomes. you only have to change for loop part just change $_post['rows'] to $_post['columns'] in the first foreach loop. And in the second for loop chnage $_post['columns'] to $_post['rows']. Thanks
else if (isset($_POST) && $_POST["operation"] == "addition")
{
for($x=0; $x<$_POST['rows']+1; $x++)
{
$i=0;
$y= $i+$x;
echo '<table border 1px solid black>';
echo '<tr>';
//$value[]=$x;
echo '<td>'.$y.'</td>';
for($value=1;$value<$_POST['columns']+1;$value++){
$c=$y+$value;
// $c=$y+$value;
echo '<td>'.$c;
echo '</td>';
}
echo '</tr>';
echo '</table>';
}
My changes finished Every thing is your code as it is.
echo "</table>";
}
else{
echo 'Invalid rows columns parameters';
exit();
}
}
exit();
}}
?>
</body>
</html>
It is actually a simple bug!
There is no error in your logic. The bug is in your echo statement for addition.
You just can't echo the addition directly. Use a bracket to surround them instead. It will work :-)
Like this;
echo '<td>'.($c+$r).'</td>';
Please let us know if it solved your problem.
Thanks,
I'm doing form in php but I have some problem.
First I will have 3 different form in the same page.
What I want is only 1 form appear and then with the answer a second form will appear and so on.
The answer of the form will be display on the same page.
For now my first form work and after get the answer go to the 2nd form but I want to submit the 2nd form the problem appear.
It delete the answer of my first form and don't do anything (everything start like I am in my first form).
I try to find the problem but can't have idea about how to solve it.
Here is my code:
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1?
<input type="number" name="nbtemplate" min="1" max="30">
<input type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php
if(!isset($submitbutton1)) {
if (!empty($_POST['nbtemplate']) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for ($i = 1; $i <= $Nnbtemplate; $i++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
if(isset($submitbutton1) && !isset($submitbutton2)) {
if (!empty($_POST['nbtime']) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST['nbtime'];
for ($j = 1; $j <= $nbtime; $j++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time" name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
}
}
?>
That is some gnarly code you got there, brother. This is a really simple task when handled with some javascript. Then you can have a single post to your php. I like using the jQuery framework so here's a couple links I found quickly: this one and this one
Example code in response to comment about building form elements dynamically:
<html>
<head>
<!-- load jquery library -->
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</head>
<body>
<form action="toyourpage.php">
How Many?:
<input type="text" name="number" id="number">
<div id="add"></div>
</form>
<!-- javascript go -->
<script type="text/javascript">
$(document).ready(function()
{
$('input#number').keyup(function()
{
var num = $(this).val(); // get num
if(!isNaN(num)) // check if number
{
$('div#add').html(''); // empty
for(i = 1; i <= num; i++) // add
{
$('div#add').append('New Field ' + i + ': <input type="text" name="next_' + i + '" id="next' + i + '"><br>');
}
}
else
{
alert('Valid number required');
}
});
});
</script>
</body>
</html>
I did some changes on Your code, and have tested, it works.
You had any mistakes in your {} brackets and if conditions. Also as I commented I added extract($_POST).
<?php
extract ( $_POST );
if (! isset ( $submitbutton1 ) && !isset($submitbutton2)) {
?>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
Q1? <input type="number" name="nbtemplate" min="1" max="30"> <input
type="submit" name="submitbutton1" value="Confirm!">
</form>
<?php ;
}
if (isset ( $submitbutton1 )) {
if (! empty ( $_POST ['nbtemplate'] ) != "") {
echo "<b>{$_POST['nbtemplate']}</b> !\n";
echo "<br />";
$Nnbtemplate = $_POST ['nbtemplate'];
$result = mysql_query("UPDATE tb SET day='$Nnbtemplate'") or
die(mysql_error());
?>
<form action='<?php echo $_SERVER['PHP_SELF'];?>' method='post'>
Q2? <br>
<?php
for($i = 1; $i <= $Nnbtemplate; $i ++) { // start loop
echo "Template ";
echo $i;
?>
<input type="number" name="nbtime" min="1" max="96">
<?php
}
echo '<input type="submit" name="submitbutton2" value="Confirm!">';
echo '</form>';
}
}
if ( isset ( $submitbutton2 )) {
if (! empty ( $_POST ['nbtime'] ) != "") {
echo "<b>{$_POST['nbtime']}</b> !\n";
echo "<br />";
$nbtime = $_POST ['nbtime'];
for($j = 1; $j <= $nbtime; $j ++) {
echo "Time";
echo $j;
?>
Q3:
<input type="time" name="starttime"> To <input type="time"
name="endtime">
<?php
}
echo '<input type="submit">';
echo '</form>';
}
}
?>
I am trying to get records from my DB using 2 seperate tables. The query is
public function get_pages_by_campign_id($campaignID) {
$campaignID = $this->real_escape_string($campaignID);
return $this->query("SELECT pid, campaignid FROM pages,campaigns WHERE 'pages.campaignid = campaigns.id'");
}
And this is called into play by :
$counter = 1;
$userID = PageDB::getInstance()->get_user_id_by_name($_SESSION['user']);
$result = PageDB::getInstance()->get_pages_by_campaign_id($campaignID);
$i=0;
while ($row = mysqli_fetch_array($result)):
$style = "";
if($i%2==0)
{
$style = ' style="background-color: #EFEFEF"';
}
echo "<tr".$style.">";
echo "<td style='width:140px;'> Page " . $counter . "</td>";
echo "<td> </td>";
echo "<td></td>";
//The loop is left open
?>
<td>
<form style="display:none;"></form>
<form name="editPage" action="editPage.php" method="GET">
<input type="hidden" name="pageID" value="<?php echo $pageID = $row['pid']; ?>"/>
<input type="submit" name="editPage" value="Edit"/>
</form>
</td>
<td>
<form name="deletePage" action="deletePage.php" method="POST">
<input type="hidden" name="pageID" value="<?php echo $pageID = $row['pid']?>"/>
<input type="submit" name="deletePage" value="Delete" onclick = "javascript: return confirm('Delete Page <?php echo $counter ?> ?');"/>
</form>
</td>
<?php
$pageID = $row['pid'];
$counter++;
$i++;
echo "</tr>\n";
endwhile;
mysqli_free_result($result);
?>
This should list all "page" Records, but it is returning nothing.
I have set up the "id" column in table "campaigns" to correspond with "campaignid" in table "pages" using foreign keys.
I manged to fix it with this :
public function get_pages_by_campaign_id($campaignID) {
$campaignID = $this->real_escape_string($campaignID);
return $this->query("SELECT pid, campaignid FROM pages WHERE campaignid = 'campaigns.id'");
}
"SELECT pid, campaignid FROM pages,campaigns WHERE pages.campaignid = campaigns.id"
?
I am trying to echo out an array using for each but it's not displaying any values. The only values i can echo out is within a second for each.
Can anyone tell me what i'm doing wrong?
What i am trying to echo is the price, item, description etc but i am getting nothing.
If you need to see the output of the array it's here http://operationbraveheart.org.uk/jcart/testshop.php
while ($row = $result->fetch()) {
$superitem[$row['itemid']][] = $row;
}
foreach($superitem AS $subitem) {
list($prodid,$item,$size,$description,$price) = $subitem[0];
if ($count % NUMCOLS == 0) echo "<tr>"; # new row
echo '<td>';
var_dump($subitem);
//Your normal code up until the select box...
echo '<form method="post" action="" class="jcart">
<fieldset>
<input type="hidden" name="jcartToken" value="'.$_SESSION['jcartToken'].'" />
<input type="hidden" name="my-item-id" value="'.$subitem['prodid'].'" />
<input type="hidden" name="my-item-price" value="'.$subitem['price'].'" />
<input type="hidden" name="my-item-url" value="http://yahoo.com" />';
if(count($subitem) > 1) {
echo '<li><select name="my-item-name" id="foo">';
foreach($subitem AS $subsubitem) {
echo "<option value='".$subsubitem['size']."'>".$subsubitem['size']."</option>";
}
echo "</select></li>";
}
else {
echo '<input type="hidden" name="my-item-name" value="'.$subitem['item'].'" />';
}
echo'<li>Price: $<span class="price">'.$subitem['price'].'</span></li>
<li>
<label>Qty: <input type="text" name="my-item-qty" value="1" size="3" /></label>
</li>
</ul>
<input type="submit" name="my-add-button" value="add to cart" class="button" />
</fieldset>
</form>';
echo '</td>';
$count++;
$counter++;
if ($count % NUMCOLS == 0) echo "</tr>\n"; # end row
}
Current it looks like $subitem contains an array of length 1 where the first index is a row. Change...
$superitem[$row['itemid']][] = $row;
should be...
$superitem[$row['itemid']] = $row;
and...
list($prodid,$item,$size,$description,$price) = $subitem[0];
should be...
list($prodid,$item,$size,$description,$price) = $subitem;