Storing Same Record my on Submit Button - php

Hello I'm looking to get the record and save it to my data base but all the time I'm getting the same sql statement for all the select options
Course ID INSERT INTO `tbl_assign_course` (`course_id_1`, course_id_2`, `course_id_3`) VALUES ('7', '7', '7')
Here is the Options list to choose:
How I can fix this logical error I will appreciate any kind of help
<!DOCTYPE html>
<html>
<head>
<title> The University</title>
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/style.css">
</head>
<body>
<div class="topnav">
<?php $this->load->view('header'); ?>
</div>
<?php
print_r($result);
?>
<form method="post" action="<?php echo(base_url() . "University/std_course_assign/" . $result[0]['course_id'] . "/" . $result[0]['course_i'] . "/" . $result[0]['course_id']); ?>">
<table>
<tr>
<td>
<select name='course_id_1'>
<option value="">--- Select Course ---</option>
<?php
for ($i = 0; $i < count($result); $i++) { ?>
<?php echo "<option value=" . $result[$i]['course_id'] . ">" . $result[$i]['course_name'] . "</option>"; ?>
<?php
}
?>
</td>
<td>
<select name='course_id_2'>
<option value="">--- Select Course ---</option>
<?php
for ($i = 0; $i < count($result); $i++) { ?>
<?php echo "<option value=" . $result[$i]['course_id'] . ">" . $result[$i]['course_name'] . "</option>"; ?>
<?php
}
?>
</td>
<td>
<select name='course_id_3'>
<option value="">--- Select Course ---</option>
<?php
for ($i = 0; $i < count($result); $i++) { ?>
<?php echo "<option value=" . $result[$i]['course_id'] . ">" . $result[$i]['course_name'] . "</option>"; ?>
<?php
}
?>
<input type="hidden" name="std_id" value="<?= $std_id ?>">
<input type="Submit">
</td>
</tr>
</table>
</form>
</body>
</html>
Model Function
public function std_course_assign($course_id) {
$data = array('std_id' => $this->input->post('std_id'),
'course_id_1' => $this->input->post('course_id'),
'course_id_2' => $this->input->post('course_id'),
'course_id_3' => $this->input->post('course_id'),
);
$this->db->insert('tbl_assign_course', $data);
$this->db->where('std_id', $this->input->post('std_id'));
print_r($data);
}

Your insert query is wrong, change it to 'course_id' to 'course_id_1' 'course_id_2' and so on:
public function std_course_assign($course_id) {
$data= array(
'std_id'=>$this->input->post('std_id'),
'course_id_1'=>$this->input->post('course_id_1'),
'course_id_2'=>$this->input->post('course_id_2'),
'course_id_3'=>$this->input->post('course_id_3')
);
$this->db->insert('tbl_assign_course', $data);
$this->db->where('std_id',$this->input->post('std_id'));
print_r($data);
}

I think You are using WHERE condition with INSERT query, use correct INSERT query for desired result.
and use correct attribute name in insert query

Related

Using Multiple PHP Drop Downs To Filter MySQL Table

Heres a pic of my database table -> MySQL-Table
Im trying to create a search page with drop down selectors to filter through each of the last 8 columns.
I want the the drop down selectors to be able to select multiple entries (I have this working already)
I also want them to preload values from data already entered into my table columns. (I also got this working with the help of tutorials... although I admit I don't fully understand how this part works)
Using these tutorials i've created a php page that contains 8 drop down selectors that automatically pull values from their respective columns. Id like to be able to filter results from my table using either all (or some) of these column filters.
For Example... Say I want to show all entries that fall under Genre=Metal, AND KeySig=E minor, AND Tempo=Fast...
I might use a mysql command like
mysql> SELECT id, NameUrl, Genre, KeySig, TimeSig, Tempo, Tuning, EntType, Recording, RecYear FROM test_table WHERE Genre = 'Metal' AND KeySig = 'E minor' AND Tempo = 'Fast';
Essentially i'm trying to do the same thing via a php webpage.
With the code I have right now only my first drop down selector "Genre" actually filters through anything. The rest of the filters are just there.. they're not set up to do anything yet. I need help pulling $_POST requests from my remaining drop downs and coming up with code that will filter through my columns using multiple variables via the AND operator.
I hope this makes sense... Im not much of a computer guy.. more of a musician. Building this as a tool to help me out with my writing workflow.
Hope someone can help - Thanks
DBController.php
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "password";
private $database = "test";
private $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
}
?>
testsearch.php
<?php
include 'DBController.php';
$db_handle = new DBController();
$GenreResult = $db_handle->runQuery("SELECT DISTINCT Genre FROM test_table ORDER BY Genre ASC");
$TempoResult = $db_handle->runQuery("SELECT DISTINCT Tempo FROM test_table ORDER BY Tempo ASC");
$KeySigResult = $db_handle->runQuery("SELECT DISTINCT KeySig FROM test_table ORDER BY KeySig ASC");
$TimeSigResult = $db_handle->runQuery("SELECT DISTINCT TimeSig FROM test_table ORDER BY TimeSig ASC");
$TuningResult = $db_handle->runQuery("SELECT DISTINCT Tuning FROM test_table ORDER BY Tuning ASC");
$EntTypeResult = $db_handle->runQuery("SELECT DISTINCT EntType FROM test_table ORDER BY EntType ASC");
$RecordingResult = $db_handle->runQuery("SELECT DISTINCT Recording FROM test_table ORDER BY Recording ASC");
$RecYearResult = $db_handle->runQuery("SELECT DISTINCT RecYear FROM test_table ORDER BY RecYear ASC");
?>
<html>
<head>
<link href="style.css" type="text/css" rel="stylesheet" />
<title>Riff Bank - Search & Upload</title>
</head>
<body>
<h2>Riff Bank - Search & Upload</h2>
<form method="POST" name="Genre" action="testsearch.php">
<div id="demo-grid">
<div class="search-box">
<select id="Place" name="Genre[]" multiple="multiple">
<option value="0" selected="selected">Select Genre</option>
<form method="POST" name="search" action="testsearch.php">
<?php
if (! empty($GenreResult)) {
foreach ($GenreResult as $key => $value) {
echo '<option value="' . $GenreResult[$key]['Genre'] . '">' . $GenreResult[$key]['Genre'] . '</option>';
}
}
?>
</select><br> <br>
<form method="POST" name="search" action="testsearch.php">
<div id="demo-grid">
<div class="search-box">
<select id="Place" name="KeySig[]" multiple="multiple">
<option value="0" selected="selected">Select Key</option>
<form method="POST" name="search" action="testsearch.php">
<?php
if (! empty($KeySigResult)) {
foreach ($KeySigResult as $key => $value) {
echo '<option value="' . $KeySigResult[$key]['Tempo'] . '">' . $KeySigResult[$key]['KeySig'] . '</option>';
}
}
?>
</select><br> <br>
<form method="POST" name="search" action="testsearch.php">
<div id="demo-grid">
<div class="search-box">
<select id="Place" name="TimeSig[]" multiple="multiple">
<option value="0" selected="selected">Select TIme Signature</option>
<form method="POST" name="search" action="testsearch.php">
<?php
if (! empty($TimeSigResult)) {
foreach ($TimeSigResult as $key => $value) {
echo '<option value="' . $TimeSigResult[$key]['TimeSig'] . '">' . $TimeSigResult[$key]['TimeSig'] . '</option>';
}
}
?>
</select><br> <br>
<form method="POST" name="search" action="index.php">
<div id="demo-grid">
<div class="search-box">
<select id="Place" name="Tempo[]" multiple="multiple">
<option value="0" selected="selected">Select Tempo</option>
<form method="POST" name="search" action="index.php">
<?php
if (! empty($TempoResult)) {
foreach ($TempoResult as $key => $value) {
echo '<option value="' . $TempoResult[$key]['Tempo'] . '">' . $TempoResult[$key]['Tempo'] . '</option>';
}
}
?>
</select><br> <br>
<form method="POST" name="search" action="testsearch.php">
<div id="demo-grid">
<div class="search-box">
<select id="Place" name="Tuning[]" multiple="multiple">
<option value="0" selected="selected">Select Tuning</option>
<form method="POST" name="search" action="testsearch.php">
<?php
if (! empty($TuningResult)) {
foreach ($TuningResult as $key => $value) {
echo '<option value="' . $TuningResult[$key]['Tuning'] . '">' . $TuningResult[$key]['Tuning'] . '</option>';
}
}
?>
</select><br> <br>
<form method="POST" name="search" action="testsearch.php">
<div id="demo-grid">
<div class="search-box">
<select id="Place" name="EntType[]" multiple="multiple">
<option value="0" selected="selected">Select Entry Type</option>
<form method="POST" name="search" action="testsearch.php">
<?php
if (! empty($EntTypeResult)) {
foreach ($EntTypeResult as $key => $value) {
echo '<option value="' . $EntTypeResult[$key]['EntType'] . '">' . $EntTypeResult[$key]['EntType'] . '</option>';
}
}
?>
</select><br> <br>
<form method="POST" name="search" action="testsearch.php">
<div id="demo-grid">
<div class="search-box">
<select id="Place" name="Recording[]" multiple="multiple">
<option value="0" selected="selected">Select Recording Type</option>
<form method="POST" name="search" action="testsearch.php">
<?php
if (! empty($RecordingResult)) {
foreach ($RecordingResult as $key => $value) {
echo '<option value="' . $RecordingResult[$key]['Recording'] . '">' . $RecordingResult[$key]['Recording'] . '</option>';
}
}
?>
</select><br> <br>
<form method="POST" name="search" action="index.php">
<div id="demo-grid">
<div class="search-box">
<select id="Place" name="RecYear[]" multiple="multiple">
<option value="0" selected="selected">Select Year</option>
<form method="POST" name="search" action="index.php">
<?php
if (! empty($RecYearResult)) {
foreach ($RecYearResult as $key => $value) {
echo '<option value="' . $RecYearResult[$key]['RecYear'] . '">' . $RecYearResult[$key]['RecYear'] . '</option>';
}
}
?>
</select><br> <br>
<button id="Filter">Search</button>
</div>
<?php
if (! empty($_POST['Genre'])) {
?>
<table cellpadding="10" cellspacing="1">
<thead>
<tr>
<th><strong>id</strong></th>
<th><strong>Name</strong></th>
<th><strong>Genre</strong></th>
<th><strong>Key</strong></th>
<th><strong>Time Sig</strong></th>
<th><strong>Tempo</strong></th>
<th><strong>Tuning</strong></th>
<th><strong>Type</strong></th>
<th><strong>Recording</strong></th>
<th><strong>Year</strong></th>
</tr>
</thead>
<tbody>
<?php
$query = "SELECT * from test_table";
$i = 0;
$selectedOptionCount = count($_POST['Genre']);
$selectedOption = "";
while ($i < $selectedOptionCount) {
$selectedOption = $selectedOption . "'" . $_POST['Genre'][$i] . "'";
if ($i < $selectedOptionCount - 1) {
$selectedOption = $selectedOption . ", ";
}
$i ++;
}
$query = $query . " WHERE Genre in (" . $selectedOption . ")";
$result = $db_handle->runQuery($query);
}
if (! empty($result)) {
foreach ($result as $key => $value) {
?>
<tr>
<td><div class="col" id="user_data_1"><?php echo $result[$key]['id']; ?></div></td>
<td><div class="col" id="user_data_2"><?php echo $result[$key]['NameUrl']; ?> </div></td>
<td><div class="col" id="user_data_3"><?php echo $result[$key]['Genre']; ?> </div></td>
<td><div class="col" id="user_data_4"><?php echo $result[$key]['KeySig']; ?> </div></td>
<td><div class="col" id="user_data_5"><?php echo $result[$key]['TimeSig']; ?> </div></td>
<td><div class="col" id="user_data_6"><?php echo $result[$key]['Tempo']; ?> </div></td>
<td><div class="col" id="user_data_7"><?php echo $result[$key]['Tuning']; ?> </div></td>
<td><div class="col" id="user_data_8"><?php echo $result[$key]['EntType']; ?> </div></td>
<td><div class="col" id="user_data_9"><?php echo $result[$key]['Recording']; ?> </div></td>
<td><div class="col" id="user_data_10"><?php echo $result[$key]['RecYear']; ?> </div></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</div>
</form>
</body>
</html>
</div>
</form>
</body>
</html>
ADAM UPDATE: DBController.php ... Like This??
<?php
class DBController {
public $host = "localhost";
public $user = "root";
public $password = "password";
public $database = "test";
public $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this-
>password,$this->database);
return $conn;
$stmt = $db_handle->conn->prepare($query);
}
function runQuery($query) {
$result = mysqli_query($this->conn,$query);
while($row=mysqli_fetch_assoc($result)) {
$resultset[] = $row;
}
if(!empty($resultset))
return $resultset;
}
}
?>
testsearch.php Browser Search - Image
testsearch.php Browser Results - Image
I would get filters in one multidimensional array
include 'DBController.php';
$db_handle = new DBController();
$filters = [];
$filters['Genre'] = array_column($db_handle->runQuery("SELECT DISTINCT Genre FROM test_table ORDER BY Genre ASC"), 'Genre');
$filters['Tempo'] = array_column($db_handle->runQuery("SELECT DISTINCT Tempo FROM test_table ORDER BY Tempo ASC"), 'Tempo');
$filters['KeySig'] = array_column($db_handle->runQuery("SELECT DISTINCT KeySig FROM test_table ORDER BY KeySig ASC"), 'KeySig');
$filters['TimeSig'] = array_column($db_handle->runQuery("SELECT DISTINCT TimeSig FROM test_table ORDER BY TimeSig ASC"), 'TimeSig');
$filters['Tuning'] = array_column($db_handle->runQuery("SELECT DISTINCT Tuning FROM test_table ORDER BY Tuning ASC"), 'Tuning');
$filters['EntType'] = array_column($db_handle->runQuery("SELECT DISTINCT EntType FROM test_table ORDER BY EntType ASC"), 'EntType');
$filters['Recording'] = array_column($db_handle->runQuery("SELECT DISTINCT Recording FROM test_table ORDER BY Recording ASC"), 'Recording');
$filters['RecYear'] = array_column($db_handle->runQuery("SELECT DISTINCT RecYear FROM test_table ORDER BY RecYear ASC"),'RecYear');
in < html > you should have only one < form > and all < select > in it & the < button > with type="submit" attribute .
Close your < div >s properly. You should use id's value in any tag only once like (id="Place").
You don't need an empty option tag in multiple select unless the value of it is used.
Prepare your query statement with the values sent to server from client to prevent sql injections!!!
Example:
<html>
<head>
<link href="style.css" type="text/css" rel="stylesheet"/>
<title>Riff Bank - Search & Upload</title>
<style>
.search-box select {
min-width: 200px;
}
</style>
</head>
<body>
<h2>Riff Bank - Search & Upload</h2>
<form method="POST" name="Genre">
<div id="demo-grid">
<div class="search-box">
Select Genre<br>
<select id="Genre" name="Genre[]" multiple="multiple">
<?php
if (!empty($filters['Genre'])) {
foreach ($filters['Genre'] as $key => $value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
}
?>
</select>
<br>
<br>
</div>
<div class="search-box">
Select Key<br>
<select id="KeySig" name="KeySig[]" multiple="multiple">
<?php
if (!empty($filters['KeySig'])) {
foreach ($filters['KeySig'] as $key => $value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
}
?>
</select>
<br>
<br>
</div>
<div class="search-box">
Select Time Signature<br>
<select id="TimeSig" name="TimeSig[]" multiple="multiple">
<?php
if (!empty($filters['TimeSig'])) {
foreach ($filters['TimeSig'] as $key => $value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
}
?>
</select>
<br>
<br>
</div>
<div class="search-box">
Select Tempo<br>
<select id="Tempo" name="Tempo[]" multiple="multiple">
<?php
if (!empty($filters['Tempo'])) {
foreach ($filters['Tempo'] as $key => $value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
}
?>
</select>
<br>
<br>
</div>
<div class="search-box">
Select Tuning<br>
<select id="Tuning" name="Tuning[]" multiple="multiple">
<?php
if (!empty($filters['Tuning'])) {
foreach ($filters['Tuning'] as $key => $value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
}
?>
</select>
<br>
<br>
</div>
<div class="search-box">
Select Entry Type<br>
<select id="EntType" name="EntType[]" multiple="multiple">
<?php
if (!empty($filters['EntType'])) {
foreach ($filters['EntType'] as $key => $value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
}
?>
</select>
<br>
<br>
</div>
<div class="search-box">
Select Recording Type<br>
<select id="Recording" name="Recording[]" multiple="multiple">
<?php
if (!empty($filters['Recording'])) {
foreach ($filters['Recording'] as $key => $value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
}
?>
</select>
<br>
<br>
</div>
<div class="search-box">
Select Year<br>
<select id="RecYear" name="RecYear[]" multiple="multiple">
<?php
if (!empty($filters['RecYear'])) {
foreach ($filters['RecYear'] as $key => $value) {
echo '<option value="' . $value . '">' . $value . '</option>';
}
}
?>
</select>
<br>
<br>
</div>
<button id="Filter" type="submit">Search</button>
</div>
</form>
<?php
if (!empty($_POST) && count($_POST)) {
//filter the array $_POST with the keys representing your filters & fields in your DB that you trust
$request_filters = array_intersect_key($_POST, array_flip(['Genre','Tempo','KeySig','TimeSig','Tuning','EntType','Recording']));
if(count($request_filters)) {
?>
<table cellpadding="10" cellspacing="1">
<thead>
<tr>
<th>
<strong>id</strong>
</th>
<th>
<strong>Name</strong>
</th>
<th>
<strong>Genre</strong>
</th>
<th>
<strong>Key</strong>
</th>
<th>
<strong>Time Sig</strong>
</th>
<th>
<strong>Tempo</strong>
</th>
<th>
<strong>Tuning</strong>
</th>
<th>
<strong>Type</strong>
</th>
<th>
<strong>Recording</strong>
</th>
<th>
<strong>Year</strong>
</th>
</tr>
</thead>
<?php
//then build up your prepare query statement
$params = [];
$query = "SELECT * from test_table WHERE ";
$extra_query = [];
foreach ($request_filters as $field => $values) {
$extra_query[] = "{$field} IN (?" . str_repeat(', ?', count($values) - 1) . ")";
$params = array_merge($params, $values);
}
$query .= implode(' AND ',$extra_query);
$stmt = $db_handle->conn->prepare($query);
$stmt->bind_param(str_repeat('s',count($params)), ...$params);
if($stmt->execute()){
$stmt_result = $stmt->get_result();
if($stmt_result && $stmt_result->num_rows){
?>
<tbody>
<?php
while($row = $stmt_result->fetch_assoc()){
?>
<tr>
<td>
<div class="col"><?php echo $row['id']; ?></div>
</td>
<td>
<div class="col"><?php echo $row['NameUrl']; ?></div>
</td>
<td>
<div class="col"><?php echo $row['Genre']; ?></div>
</td>
<td>
<div class="col"><?php echo $row['KeySig']; ?></div>
</td>
<td>
<div class="col"><?php echo $row['TimeSig']; ?></div>
</td>
<td>
<div class="col"><?php echo $row['Tempo']; ?></div>
</td>
<td>
<div class="col"><?php echo $row['Tuning']; ?></div>
</td>
<td>
<div class="col"><?php echo $row['EntType']; ?></div>
</td>
<td>
<div class="col"><?php echo $row['Recording']; ?></div>
</td>
<td>
<div class="col"><?php echo $row['RecYear']; ?></div>
</td>
</tr>
<?php
}
?>
</tbody>
<?php
} else {
?>
<tbody>
<tr>
<td colspan="10">No results!</td>
</tr>
</tbody>
<?php
}
}
?>
</table>
<?php
}
}
?>
</body>
</html>
The Controller:
<?php
class DBController {
private $host = "localhost";
private $user = "root";
private $password = "password";
private $database = "test";
public $conn;
function __construct() {
$this->conn = $this->connectDB();
}
function connectDB() {
$conn = mysqli_connect($this->host,$this->user,$this->password,$this->database);
return $conn;
}
function runQuery($query) {
$result = $this->conn->query($query);
$resultset = [];
while($row=$result->fetch_assoc()) {
$resultset[] = $row;
}
return $resultset;
}
}
?>
I hope it helps.

Why can't I unselect the last option in multiselect after I save it to a session variable?

I have a multi-select which saves the currently selected options using a session variable. However when I un-select all options, the last selected option stays. How do I fix this? Here is my code:
<!DOCTYPE html>
<?php
session_start();
if(isset($_POST['occupation']))
$_SESSION['occupation'] = $_POST['occupation'];
?>
<html>
<head>
</head>
<body>
<form method="post" action="">
<h2>Industy</h2>
<select name="occupation[]" multiple >
<?php
$occ = array("Accounting", "Education", "Healthcare", "Information Technology", "Retail", "Sales");
$len = count($occ);
for($i = 0; $i<$len; $i++ )
{
if(in_array($occ[$i], $_SESSION['occupation']))
echo '<option value="' . $occ[$i] . '" selected>' . $occ[$i] .'</option>';
else
echo '<option value="' . $occ[$i] . '" >' . $occ[$i] .'</option>';
}
?>
</select>
<br/><br/>
<button type="submit" value="Search" class="my-button" name="search_button" >Search</button>
</form>
</body>
</html>
Just add to your code that if you submitted without any value, just overwrite the session array empty.
Here's the idea:
<?php
session_start();
$occ = array("Accounting", "Education", "Healthcare", "Information Technology", "Retail", "Sales");
if (empty($_SESSION['occupation'])) { // initialize
$_SESSION['occupation'] = array();
}
if(isset($_POST['search_button'])) { // if submitted
// set session occupation else just set empty
$_SESSION['occupation'] = !empty($_POST['occupation']) ? $_POST['occupation'] : array();
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form method="post" action="">
<h2>Industy</h2>
<select name="occupation[]" multiple>
<?php foreach ($occ as $o) { ?>
<option value="<?php echo $o; ?>" <?php echo in_array($o, $_SESSION['occupation']) ? 'selected' : ''; ?>>
<?php echo $o; ?>
</option>
<?php } ?>
</select>
<br/><br/>
<button type="submit" value="Search" class="my-button" name="search_button" >Search</button>
</form>
</body>
</html>

PHP: How to popualate list from sqlite table

I want to populate my Php form list from sqlite table. Following is the code:
<?php
$db = new PDO("sqlite:c:/sqlite/test.db");
$smt = $db->prepare('select person_name From persons');
$smt->execute();
$data = $smt->fetchAll(); ?>
<!DOCTYPE HTML>
<html lang = "en">
<head>
<title>formDemo.html</title>
<meta charset = "UTF-8" />
</head>
<body>
<h1>Form Demo</h1>
<form>
<fieldset>
<legend>choose Profile Collection Id and Call Type </legend>
<p>
<label>Profile_Collection_Id 1</label>
<select id = "myList">
<?php
foreach ($data as $row)?>
< option><?php $row["person_name"]?></option>
endforeach ?>
</select>
</form>
</body>
</html>
I am not getting where i am going wrong as list is empty when I run this code. Can someone help.
Assuming your query is returning results:
<select id="myList">
<?php
foreach ($data as $row){
echo '<option value="' . $row['Person_Name'] . '">' . $row['Person_Name'] . '</option>';
}
?>
</select>
echo is missing
<?php
foreach ($data as $row)?>
< option><?php echo $row["person_name"]?></option>
endforeach
?>

value is not appearing in the drop downlist

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.

php:process the select tag

this code run but when test it .. the data not correct i select data from database and i make it in array ad show it id by select tag but when select any id and submit .. example i select 5 and click on submit the record will delete is 2 not 5
<?php
require_once "config.php";
$qid="select id from info_user";
$arrayid=array();
$result=mysql_query($qid);
while($res=mysql_fetch_array($result)){
$arrayid[]=$res['id'];
}
var_dump($arrayid);
if(isset($_POST['sub'])){
$id=$_POST['id'];
$q="delete from info_user where id=$id ";
$qq=mysql_query($q);
if($qq){
echo "you delete record ";
}
else{
echo "error in deleting";
}}
?>
<html>
<head>
<title>delete</title>
</head>
<form action="delete.php" method="post">
<select name="id"><?php for($i=0;$i<count($arrayid);$i++){?>
<option value="<?php echo $i;?>"><?php echo $arrayid[$i];} ?></option></select> <br />
<input type="submit" name="sub" />
</form>
</html>
I think that problem is in value for the options.
Try changing option line to
<option value="<?php echo $arrayid[$i];?>"><?php echo $arrayid[$i];} ?></option></select> <br />
Your <option> markup is wrong. Make your markup like this;
<select name="id">
<?php for ($i = 0; $i < count($arrayid); $i++) { ?>
<option value="<?php echo $i; ?>"><?php echo $arrayid[$i]; ?></option>
} ?>
</select>
Tip: You'll find debugging easier if you indent your code. IDE's generally have this option. NetBeans is my favourite.
Instead of sending the ids, you're sending an array key associated to the id.
For instance, assume that: $arrayid = array(10, 11, 12);.
This is equivalent to: $arrayid = array(0 => 10, 1 => 11, 2 => 12);.
You'll see the options 10, 11 and 12, but you'll send either 0, 11 or 12, because that's what you're setting to the options values:
<select name="id">
<option value="0">10</option>
<option value="1">11</option>
<option value="2">12</option>
</select>
If you select the option "11", the SQL statement to delete an entry will be:
delete from info_user where id=1
I did not test this code and I'm assuming the ids are integers, but try it:
<?php
require_once "config.php";
$qid = "select id from info_user";
$arrayid = array();
$result = mysql_query($qid);
while( $res = mysql_fetch_array($result) ){
$arrayid[] = $res['id'];
}
if( isset($_POST['sub']) ){
$id = (int)$_POST['id']; // make sure it's an integer to avoid SQL injections
$q = "delete from info_user where id=$id";
$qq = mysql_query($q);
if( $qq ) {
$error = "you delete record ";
} else {
$error = "error in deleting";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>delete</title>
</head>
<body>
<?php
if( isset($error) ) :
echo '<p>', htmlspecialchars($error), '</p>';
elseif( !empty($arrayid) ) :
var_dump($arrayid);
endif;
?>
<form action="delete.php" method="post">
<select name="id">
<?php foreach($arrayid as $id): ?>
<option value="<?php echo (int)$id;?>">
<?php echo (int)$id; ?>
<?php endforeach; ?>
</option>
</select>
<br />
<input type="submit" name="sub" />
</form>
</body>
</html>

Categories