I'm facing an issue most probably due to my lack of experience.
I'm getting the data successfully from the MYSQL DATABASE and it is successfully populating the Second DROPDOWN menu.
The problem is... when I click in "Validate" to submit and record the data in the variable it cleans the previous option selected. I'm being unable to record the selected options in variables.
<?php
$location = "";
$locationf = "";
$system = "";
$systemf = "";
$conn = mysqli_connect('localhost', 'root', 'test', 'SRSBASE')
or die('Cannot connect to db');
$result = $conn->query("select distinct SUB_ACCOUNT from SRSLOAD");
if (isset($_POST["selec"]["account"])) {
$location = $_POST["selec"]["account"];
$locationf = $location;
$locationf = sprintf('%s', $locationf);
}
echo "Location: $locationf";
$conn2 = mysqli_connect('localhost', 'root', 'test', 'SRSBASE')
or die('Cannot connect to db');
$result2 = $conn2->query("select distinct SYSTEMNAME from SRSLOAD where SUB_ACCOUNT='$locationf'");
if (isset($_POST["selec"]["system"])) {
$system = $_POST["selec"]["system"];
$systemf = $system;
}
echo "System: $systemf";
$post_at = "";
$post_at_to_date = "";
$post_at_todate = "";
$queryCondition = "";
if (!empty($_POST["search"]["post_at"])) {
$post_at = $_POST["search"]["post_at"];
list($fiy, $fim, $fid) = explode("-", $post_at);
$post_at_todate = date('YY-mm-dd');
if (!empty($_POST["search"]["post_at_to_date"])) {
$post_at_to_date = $_POST["search"]["post_at_to_date"];
list($tiy, $tim, $tid) = explode("-", $_POST["search"]["post_at_to_date"]);
$post_at_todate = "$tiy-$tim-$tid";
//TESTING SELECTED TARGETS
//echo $post_at;
//echo "/";
//echo $post_at_todate;
}
//$queryCondition .= "WHERE RDATE BETWEEN '$fiy-$fim-$fid' AND '" . $post_at_todate . "'";
$queryCondition .= "WHERE RDATE BETWEEN '$post_at' AND '" . $post_at_todate . "'";
}
//$sql = "SELECT * from SRSLOAD " . $queryCondition . " ORDER BY post_at desc";
//$sql = "select * from SRSLOAD where rdate between '$post_at' AND $post_at_todate;"
$sql = sprintf("SELECT * FROM SRSLOAD WHERE RDATE BETWEEN '%s' AND '%s' AND SYSTEMNAME='%s' AND SUB_ACCOUNT='%s'", $post_at, $post_at_todate, $systemf, $locationf);
$result3 = mysqli_query($conn, $sql);
?>
<!DOCTYPE html>
<html>
<head>
<title>Storage Report System - Search</title>
<script src="jquery-1.9.1.js"></script>
<link rel="stylesheet" href="jquery-ui-1.11.4.css">
<style>
.table-content{border-top:#CCCCCC 4px solid; width:50%;}
.table-content th {padding:5px 20px; background: #F0F0F0;vertical-align:top;}
.table-content td {padding:5px 20px; border-bottom: #F0F0F0 1px solid;vertical-align:top;}
</style>
</head>
<body>
<h2 style='font-family:arial'>Storage Report System - Search</h2>
<form name='sname' id='sname' action='' method='POST'>
<select id='select' name="selec[account]" value="<?php echo $location; ?>" >
<option value='-1'>--Select the Location--</option>
<?php
while ($row = $result->fetch_assoc()) {
unset($sub_acc);
$sub_acc = $row['SUB_ACCOUNT'];
echo '<option value="' . $sub_acc . '">' . $sub_acc . '</option>';
}
?>
</select>
<input type='submit' value='Validate' />
</form>
<form name='sname' id='sname' action='' method='POST' >
<select id='system' name="selec[system]" value="<?php echo $system; ?>" >
<option value='-1'>--Select the System--</option>
<?php
while ($row2 = $result2->fetch_assoc()) {
unset($syst);
$syst = $row2['SYSTEMNAME'];
echo '<option value="' . $syst . '">' . $syst . '</option>';
}
?>
</select>
<input type='submit' value='Validate' />
</form>
<div class="demo-content">
<form name="frmSearch" method="post" action="">
<p class="search_input">
<input type="text" placeholder="From Date" id="post_at" name="search[post_at]" value="<?php echo $post_at; ?>" class="input-control" />
<input type="text" placeholder="To Date" id="post_at_to_date" name="search[post_at_to_date]" style="margin-left:10px" value="<?php echo $post_at_to_date; ?>" class="input-control" />
<input type="submit" name="go" value="Search" >
</p>
<?php if (!empty($result3)) { ?>
<table class="table-content">
<thead>
<tr>
<th width="30%"><span>SYSTEM NAME</span></th>
<th width="50%"><span>DATE</span></th>
<th width="20%"><span>HSM</span></th>
</tr>
</thead>
<tbody>
<?php
while ($row3 = mysqli_fetch_array($result3)) {
?>
<tr>
<td><?php echo $row["SYSTEMNAME"]; ?></td>
<td><?php echo $row["RDATE"]; ?></td>
<td><?php echo $row["HSM_MCDS"]; ?></td>
</tr>
<?php
}
?>
<tbody>
</table>
<?php } ?>
</form>
</div>
<script src="jquery-ui-1.10.3.js"></script>
<script>
$.datepicker.setDefaults({
showOn: "button",
buttonImage: "datepicker.png",
buttonText: "Date Picker",
buttonImageOnly: true,
dateFormat: 'yy-mm-dd'
});
$(function () {
$("#post_at").datepicker();
$("#post_at_to_date").datepicker();
});
</script>
</body>
</html>
It is because you have two forms there. Every form has its own select and submit. When you click submit, only appropriate form with select is sent.
When you want to have data from both selects, you have to have both selects in one form with one submit.
Something like this code:
<form name='sname' id='sname' action='' method='POST'>
<select id='select' name="selec[account]" value="<?php echo $location; ?>" >
<option value='-1'>--Select the Location--</option>
<?php
while ($row = $result->fetch_assoc()) {
unset($sub_acc);
$sub_acc = $row['SUB_ACCOUNT'];
echo '<option value="' . $sub_acc . '">' . $sub_acc . '</option>';
}
?>
</select>
<select id='system' name="selec[system]" value="<?php echo $system; ?>" >
<option value='-1'>--Select the System--</option>
<?php
while ($row2 = $result2->fetch_assoc()) {
unset($syst);
$syst = $row2['SYSTEMNAME'];
echo '<option value="' . $syst . '">' . $syst . '</option>';
}
?>
</select>
<input type='submit' value='Validate' />
</form>
Related
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.
I'm having an issue in submitting input values in a form from a page to another, with the post method; when I try getting the values with $_POST['input_name'], it doesn't return anything, and I get a "Undefined index" notice on the page I'm sending the data to.
The only value that is passed correclty is ['studentid'].
the form is inside of a foreach loop.
I'm pretty new to php, so I might be ignoring something really basic.
first page code:
<?php
$aStudents = NULL;
$aStudents = $MobilityClass->GetFlowStudents($id_flow, $oConn);
if (count((array) $aStudents) > 0) {
$k = 0;
foreach ($aStudents as $aResult) {
$k = $k + 1;
?>
<tr>
<td><?php echo($k); ?></td>
<td><a class="" title="edit" href="student.php?id_student=<?php echo($aResult['id_student']); ?>"><?php
echo($aResult['student_surname']);
echo(' ');
echo($aResult['student_name']);
?> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a>
<?php
$studentid = "";
$studentid = $aResult['id_student'];
?>
</td>
<td>
<?php
$data_par = null;
$datap = null;
$datap = mysqli_query($oConn, "SELECT DATE_FORMAT(data_partenza, '%d-%m-%Y') as data_partenza from flight_details where id_student = " . $studentid . ";");
$data_par = mysqli_fetch_array($datap);
if ((string) $data_par[0] == '00-00-0000') {
$data_par[0] = null;
$formdatea = null;
} else {
// echo $data_par[0];
$formdatep = DateTime::createFromFormat('d-m-Y', $data_par[0])->format('Y-m-d');
}
echo $formdatep;
?>
<input form="update_form" value="<?php echo $formdatep; ?>" class="form-control" type="date" name="data_partenza">
<input form="update_form" type="hidden" value="<?php echo $url; ?>" name="url">
</td>
<td>
<?php
$data_arr = null;
$dataa = null;
$dataa = mysqli_query($oConn, "SELECT DATE_FORMAT(data_arrivo, '%d-%m-%Y') as data_arrivo from flight_details where id_student = " . $studentid . ";");
$data_arr = mysqli_fetch_array($dataa);
if ((string) $data_arr[0] == '00-00-0000') {
$data_arr[0] = null;
$formdatea = null;
} else {
// echo $data_par[0];
$formdatea = DateTime::createFromFormat('d-m-Y', $data_arr[0])->format('Y-m-d');
}
echo $formdatea;
?>
<input form="update_form" type="date" name="data_arrivo" class="form-control" id="name" value="<?php echo $formdatea; ?>">
</td>
<td>
<?php
$orap = mysqli_query($oConn, "SELECT DATE_FORMAT(ora_partenza, '%H:%i') as ora_partenza from flight_details where id_student = " . $studentid . ";");
$ora_par = mysqli_fetch_array($orap);
?>
<input form="update_form" type="time" name="ora_partenza" class="form-control" id="name" value="<?php echo $ora_par[0]; ?>">
</td>
<td>
<?php
$oraa = mysqli_query($oConn, "SELECT DATE_FORMAT(ora_arrivo, '%H:%i') as ora_arrivo from flight_details where id_student = " . $studentid . ";");
$ora_arr = mysqli_fetch_array($oraa);
?>
<input form="update_form" type="time" name="ora_arrivo" class="form-control" id="name" value="<?php echo $ora_arr[0]; ?>">
</td>
<td>
<select form="update_form" name="luogo_partenza" class=" form-control" >
<?php
$departure = mysqli_query($oConn, "select luogo_partenza from flight_details where id_student = " . $studentid . ";");
$loc_departure = mysqli_fetch_array($departure);
$countries = array();
$countries = mysqli_query($oConn, "select id,name from countries");
foreach ($countries as $country) {
if (trim($loc_departure[0]) == trim($country['name'])) {
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="' . $country['name'] . '"' . $selected . '>' . $country['name'] . '</option>';
}
?>
</select>
</td>
<td>
<!--class="selectpicker"-->
<select form="update_form" name="luogo_arrivo" class=" form-control" >
<?php
$arrival = mysqli_query($oConn, "select luogo_arrivo from flight_details where id_student = " . $studentid . ";");
$loc_arrival = mysqli_fetch_array($arrival);
// echo $loc_arrival[0];
$countries = array();
$countries = mysqli_query($oConn, "select id,name from countries");
foreach ($countries as $country) {
if ($loc_arrival[0] == $country['name']) {
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="' . $country['name'] . '"' . $selected . '>' . $country['name'] . '</option>';
}
?>
</select>
</td>
<td style="align-content: center;">
<form id="update_form" action="update-flight-details.php" method="post">
<?php echo $studentid ?>
<input type="hidden" value="<?php echo $studentid; ?>" name="studentid">
<button type="submit" name="update" class="btn-success btn btn-sm">Save</button>
</form>
</td>
</tr>
<?php }
} ?>
second page code:
<?php
if (isset($_POST["update"])) {
$url = $_POST['url'];
echo $_POST['studentid'];
echo $_POST['data_partenza'];
echo $_POST['luogo_arrivo'];
if (!isset($_POST['data_partenza'])) {
$_POST['data_partenza'] = null;
}
if (!isset($_POST['data_arrivo'])) {
$_POST['data_arrivo'] = null;
}
if (!isset($_POST['ora_partenza'])) {
$_POST['ora_partenza'] = null;
}
if (!isset($_POST['ora_arrivo'])) {
$_POST['ora_arrivo'] = null;
}
if (!isset($_POST['luogo_partenza'])) {
$_POST['luogo_partenza'] = null;
}
if (!isset($_POST['luogo_arrivo'])) {
$_POST['luogo_arrivo'] = null;
}
mysqli_query($oConn, "
UPDATE flight_details SET
data_partenza = '" . $_POST['data_partenza'] . "',
data_arrivo = '" . $_POST['data_arrivo'] . "',
ora_partenza = '" . $_POST['ora_partenza'] . "',
ora_arrivo = '" . $_POST['ora_arrivo'] . "',
luogo_partenza = '" . $_POST['luogo_partenza'] . "',
luogo_arrivo = '" . $_POST['luogo_arrivo'] . "'
where id_student = " . $_POST['studentid'] . ";
");
}?>
I lost all day on this, help please :')
EDIT: I also created the code to update all students together, I wrote it just as the one I wrote above, and that one works.
here it is:
1st page:
<tr>
<td></td>
<td>All students</td>
<td>
<input form="update_all_form" type="date" name="data_partenza_all" class="form-control" id="name" value="">
<input form="update_all_form" type="hidden" value="<?php echo $url; ?>" name="urlall">
</td>
<td>
<input form="update_all_form"type="date" name="data_arrivo_all" class="form-control" id="name" value="">
</td>
<td>
<input form="update_all_form" type="time" name="ora_partenza_all" class="form-control" id="name" value="">
</td>
<td>
<input form="update_all_form" type="time" name="ora_arrivo_all" class="form-control" id="name" value="">
</td>
<td>
<select form="update_all_form" name="luogo_partenza_all" class=" form-control">
<?php
$countries = array();
$countries = mysqli_query($oConn, "select id,name from countries");
foreach ($countries as $country) {
echo '<option value="'.$country['name'].'">'.$country['name'].'</option>';
}
?>
</select>
</td>
<td>
<select form="update_all_form" name="luogo_arrivo_all" class=" form-control">
<?php
$countries = array();
$countries = mysqli_query($oConn, "select id,name from countries");
foreach ($countries as $country) {
echo '<option value="'.$country['name'].'">'.$country['name'].'</option>';
}
?>
</select>
</td>
<td style="align-content: center;">
<form id="update_all_form" action="update-flight-details.php" method="post">
<button type="submit" name="update_all" class="btn-success btn btn-sm">Save</button>
</form>
</td>
</tr>
</thead>
<tbody>
2nd page:
else if (isset($_POST["update_all"])){
$urlall=$_POST['urlall'];
mysqli_query($oConn,
"
UPDATE flight_details SET
data_partenza = '".$_POST['data_partenza_all']."',
data_arrivo = '".$_POST['data_arrivo_all']."',
ora_partenza = '".$_POST['ora_partenza_all']."',
ora_arrivo = '".$_POST['ora_arrivo_all']."',
luogo_partenza = '".$_POST['luogo_partenza_all']."',
luogo_arrivo = '".$_POST['luogo_arrivo_all']."';
");
}
You are opening form tag after elements are declared. Form elements should be wrapped inside opening and closing form tags to fetch data.
first page code:
<form id="update_form" action="update-flight-details.php" method="post">
<?php
$aStudents = NULL;
$aStudents = $MobilityClass->GetFlowStudents($id_flow, $oConn);
if (count((array) $aStudents) > 0) {
$k = 0;
foreach ($aStudents as $aResult) {
$k = $k + 1;
?>
<tr>
<td><?php echo($k); ?></td>
<td><a class="" title="edit" href="student.php?id_student=<?php echo($aResult['id_student']); ?>"><?php
echo($aResult['student_surname']);
echo(' ');
echo($aResult['student_name']);
?> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a>
<?php
$studentid = "";
$studentid = $aResult['id_student'];
?>
</td>
<td>
<?php
$data_par = null;
$datap = null;
$datap = mysqli_query($oConn, "SELECT DATE_FORMAT(data_partenza, '%d-%m-%Y') as data_partenza from flight_details where id_student = " . $studentid . ";");
$data_par = mysqli_fetch_array($datap);
if ((string) $data_par[0] == '00-00-0000') {
$data_par[0] = null;
$formdatea = null;
} else {
// echo $data_par[0];
$formdatep = DateTime::createFromFormat('d-m-Y', $data_par[0])->format('Y-m-d');
}
echo $formdatep;
?>
<input form="update_form" value="<?php echo $formdatep; ?>" class="form-control" type="date" name="data_partenza">
<input form="update_form" type="hidden" value="<?php echo $url; ?>" name="url">
</td>
<td>
<?php
$data_arr = null;
$dataa = null;
$dataa = mysqli_query($oConn, "SELECT DATE_FORMAT(data_arrivo, '%d-%m-%Y') as data_arrivo from flight_details where id_student = " . $studentid . ";");
$data_arr = mysqli_fetch_array($dataa);
if ((string) $data_arr[0] == '00-00-0000') {
$data_arr[0] = null;
$formdatea = null;
} else {
// echo $data_par[0];
$formdatea = DateTime::createFromFormat('d-m-Y', $data_arr[0])->format('Y-m-d');
}
echo $formdatea;
?>
<input form="update_form" type="date" name="data_arrivo" class="form-control" id="name" value="<?php echo $formdatea; ?>">
</td>
<td>
<?php
$orap = mysqli_query($oConn, "SELECT DATE_FORMAT(ora_partenza, '%H:%i') as ora_partenza from flight_details where id_student = " . $studentid . ";");
$ora_par = mysqli_fetch_array($orap);
?>
<input form="update_form" type="time" name="ora_partenza" class="form-control" id="name" value="<?php echo $ora_par[0]; ?>">
</td>
<td>
<?php
$oraa = mysqli_query($oConn, "SELECT DATE_FORMAT(ora_arrivo, '%H:%i') as ora_arrivo from flight_details where id_student = " . $studentid . ";");
$ora_arr = mysqli_fetch_array($oraa);
?>
<input form="update_form" type="time" name="ora_arrivo" class="form-control" id="name" value="<?php echo $ora_arr[0]; ?>">
</td>
<td>
<select form="update_form" name="luogo_partenza" class=" form-control" >
<?php
$departure = mysqli_query($oConn, "select luogo_partenza from flight_details where id_student = " . $studentid . ";");
$loc_departure = mysqli_fetch_array($departure);
$countries = array();
$countries = mysqli_query($oConn, "select id,name from countries");
foreach ($countries as $country) {
if (trim($loc_departure[0]) == trim($country['name'])) {
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="' . $country['name'] . '"' . $selected . '>' . $country['name'] . '</option>';
}
?>
</select>
</td>
<td>
<!--class="selectpicker"-->
<select form="update_form" name="luogo_arrivo" class=" form-control" >
<?php
$arrival = mysqli_query($oConn, "select luogo_arrivo from flight_details where id_student = " . $studentid . ";");
$loc_arrival = mysqli_fetch_array($arrival);
// echo $loc_arrival[0];
$countries = array();
$countries = mysqli_query($oConn, "select id,name from countries");
foreach ($countries as $country) {
if ($loc_arrival[0] == $country['name']) {
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="' . $country['name'] . '"' . $selected . '>' . $country['name'] . '</option>';
}
?>
</select>
</td>
<td style="align-content: center;">
<?php echo $studentid ?>
<input type="hidden" value="<?php echo $studentid; ?>" name="studentid">
<button type="submit" name="update" class="btn-success btn btn-sm">Save</button>
</td>
</tr>
<?php }
} ?>
</form>
Try the above code.
You all fields which you want in second page must be within <form id="update_form" action="update-flight-details.php" method="post"> tag
So Just cut <form id="update_form" action="update-flight-details.php" method="post"> tag and put before the <?php
$aStudents = NULL;
And cut </form> and put it after <?php }
} ?>
This will work for you. Also I just put whole code for you.
<form id="update_form" action="update-flight-details.php" method="post">
<?php
$aStudents = NULL;
$aStudents = $MobilityClass->GetFlowStudents($id_flow, $oConn);
if (count((array) $aStudents) > 0) {
$k = 0;
foreach ($aStudents as $aResult) {
$k = $k + 1;
?>
<tr>
<td><?php echo($k); ?></td>
<td><a class="" title="edit" href="student.php?id_student=<?php echo($aResult['id_student']); ?>"><?php
echo($aResult['student_surname']);
echo(' ');
echo($aResult['student_name']);
?> <span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></a>
<?php
$studentid = "";
$studentid = $aResult['id_student'];
?>
</td>
<td>
<?php
$data_par = null;
$datap = null;
$datap = mysqli_query($oConn, "SELECT DATE_FORMAT(data_partenza, '%d-%m-%Y') as data_partenza from flight_details where id_student = " . $studentid . ";");
$data_par = mysqli_fetch_array($datap);
if ((string) $data_par[0] == '00-00-0000') {
$data_par[0] = null;
$formdatea = null;
} else {
// echo $data_par[0];
$formdatep = DateTime::createFromFormat('d-m-Y', $data_par[0])->format('Y-m-d');
}
echo $formdatep;
?>
<input form="update_form" value="<?php echo $formdatep; ?>" class="form-control" type="date" name="data_partenza">
<input form="update_form" type="hidden" value="<?php echo $url; ?>" name="url">
</td>
<td>
<?php
$data_arr = null;
$dataa = null;
$dataa = mysqli_query($oConn, "SELECT DATE_FORMAT(data_arrivo, '%d-%m-%Y') as data_arrivo from flight_details where id_student = " . $studentid . ";");
$data_arr = mysqli_fetch_array($dataa);
if ((string) $data_arr[0] == '00-00-0000') {
$data_arr[0] = null;
$formdatea = null;
} else {
// echo $data_par[0];
$formdatea = DateTime::createFromFormat('d-m-Y', $data_arr[0])->format('Y-m-d');
}
echo $formdatea;
?>
<input form="update_form" type="date" name="data_arrivo" class="form-control" id="name" value="<?php echo $formdatea; ?>">
</td>
<td>
<?php
$orap = mysqli_query($oConn, "SELECT DATE_FORMAT(ora_partenza, '%H:%i') as ora_partenza from flight_details where id_student = " . $studentid . ";");
$ora_par = mysqli_fetch_array($orap);
?>
<input form="update_form" type="time" name="ora_partenza" class="form-control" id="name" value="<?php echo $ora_par[0]; ?>">
</td>
<td>
<?php
$oraa = mysqli_query($oConn, "SELECT DATE_FORMAT(ora_arrivo, '%H:%i') as ora_arrivo from flight_details where id_student = " . $studentid . ";");
$ora_arr = mysqli_fetch_array($oraa);
?>
<input form="update_form" type="time" name="ora_arrivo" class="form-control" id="name" value="<?php echo $ora_arr[0]; ?>">
</td>
<td>
<select form="update_form" name="luogo_partenza" class=" form-control" >
<?php
$departure = mysqli_query($oConn, "select luogo_partenza from flight_details where id_student = " . $studentid . ";");
$loc_departure = mysqli_fetch_array($departure);
$countries = array();
$countries = mysqli_query($oConn, "select id,name from countries");
foreach ($countries as $country) {
if (trim($loc_departure[0]) == trim($country['name'])) {
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="' . $country['name'] . '"' . $selected . '>' . $country['name'] . '</option>';
}
?>
</select>
</td>
<td>
<!--class="selectpicker"-->
<select form="update_form" name="luogo_arrivo" class=" form-control" >
<?php
$arrival = mysqli_query($oConn, "select luogo_arrivo from flight_details where id_student = " . $studentid . ";");
$loc_arrival = mysqli_fetch_array($arrival);
// echo $loc_arrival[0];
$countries = array();
$countries = mysqli_query($oConn, "select id,name from countries");
foreach ($countries as $country) {
if ($loc_arrival[0] == $country['name']) {
$selected = 'selected';
} else {
$selected = '';
}
echo '<option value="' . $country['name'] . '"' . $selected . '>' . $country['name'] . '</option>';
}
?>
</select>
</td>
<td style="align-content: center;">
<?php echo $studentid ?>
<input type="hidden" value="<?php echo $studentid; ?>" name="studentid">
<button type="submit" name="update" class="btn-success btn btn-sm">Save</button>
</td>
</tr>
<?php }
} ?>
</form>
I am developing a simple attendance system in which the attendance is taken by the a teacher and then saved to the database. However, I am having a problem with saving the data to the database. when i click on "submit attendance" the data won't be submitted to the database. i use register.php to register students but take the attendance in different file.
Below is the code i use to submit. Can someone help me? Thanks.
sorry the file i shared was supposed to save data to mysql database. Below is the file which takes the data and am still having the problem for saving it.
this is the teacher file to take the attendance
teacher.php
<?php
$pageTitle = 'Take Attendance';
include('header.php');
require("db-connect.php");
if(!(isset($_COOKIE['teacher']) && $_COOKIE['teacher']==1)){
echo 'Only teachers can create new teachers and students.';
$conn->close();
include('footer.php');
exit;
}
//get session count
$query = "SELECT * FROM attendance";
$result = $conn->query($query);
$sessionCount=0;
setcookie('sessionCount', ++$sessionCount);
if(mysqli_num_rows($result)>0){
while($row = $result->fetch_assoc()){
$sessionCount = $row['session'];
setcookie('sessionCount', ++$sessionCount);
}
}
if(isset($_GET['class']) && !empty($_GET['class'])){
$whichClass = $_GET['class'];
$whichClassSQL = "AND class='" . $_GET['class'] . "'";
} else {
$whichClass = '';
$whichClassSQL = 'ORDER BY class';
}
echo '
<div class="row">
<div class="col-md-4">
<div class="input-group">
<input type="number" id="session" name="sessionVal" class="form-control" placeholder="Session Value i.e 1" required>
<span class="input-group-btn">
<input id="submitAttendance" type="button" class="btn btn-success" value="Submit Attendance" name="submitAttendance">
</span>
</div>
</div>
<div class="col-md-8">
<form method="get" action="' . $_SERVER['PHP_SELF'] . '" class="col-md-4">
<select name="class" id="class" class="form-control" onchange="if (this.value) window.location.href=this.value">
';
// Generate list of classes.
$query = "SELECT DISTINCT class FROM user ORDER BY class;";
$classes = $classes = mysqli_query($conn, $query);
if($classes && mysqli_num_rows($classes)){
// Get list of available classes.
echo ' <option value="">Filter: Select a class</option>';
echo ' <option value="?class=">All classes</option>';
while($class = $classes->fetch_assoc()){
echo ' <option value="?class=' . $class['class'] . '">' . $class['class'] . '</option>';
}
} else {
echo ' <option value="?class=" disabled>No classes defined.</option>';
}
echo '
</select>
</form>
</div>
</div>
';
$query = "SELECT * FROM user WHERE role='student' $whichClassSQL;";
$result = $conn->query($query);
?>
<table class="table table-striped">
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Class</th>
<th>Present</th>
<th>Absent</th>
</tr>
</thead>
<tbody>
<form method="post" action="save-attendance.php" id="attendanceForm">
<?php
if(mysqli_num_rows($result) > 0){
$i=0;
while($row = $result->fetch_assoc()){
?>
<tr>
<td><input type="hidden" value="<?php echo($row['id']);?>" form="attendanceForm"><input type="text" readonly="readonly" name="name[<?php echo $i; ?>]" value="<?php echo $row['fullname'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="email[<?php echo $i; ?>]" value="<?php echo $row['email'];?>" form="attendanceForm"></td>
<td><input type="text" readonly="readonly" name="class[<?php echo $i; ?>]" value="<?php echo $row['class'];?>" form="attendanceForm"></td>
<td><input type="radio" value="present" name="present[<?php echo $i; ?>]" checked form="attendanceForm"></td>
<td><input type="radio" value="absent" name="present[<?php echo $i; ?>]" form="attendanceForm"></td>
</tr>
<?php $i++;
}
}
?>
</form>
</tbody>
</table>
<script>
$("#submitAttendance").click(function(){
if($("#session").val().length==0){
alert("session is required");
} else {
$.cookie("sessionVal", $("#session").val());
var data = $('form#attendanceForm').serialize();
$.ajax({
url: 'save-attendance.php',
method: 'post',
data: {formData: data},
success: function (data) {
console.log(data);
if (data != null && data.success) {
alert('Success');
} else {
alert(data.status);
}
},
error: function () {
alert('Error');
}
});
}
});
</script>
<?php
$conn->close();
include('footer.php');
save-attendance.
<?php
//include ("nav.php");
require("db-connect.php");
$query = "SELECT * FROM user WHERE role='student'";
$result = $conn->query($query);
$nameArray = Array();
$count = mysqli_num_rows($result);
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
}
//save record to db
if(isset($_POST['formData'])) {
//increment the session count
if(isset($_COOKIE['sessionCount'])){
$sessionCount = $_COOKIE['sessionCount'];
setcookie('sessionCount', ++$sessionCount);
}
parse_str($_POST['formData'], $searcharray);
//print_r($searcharray);die;
//print_r($_POST);
for ($i = 0 ; $i < sizeof($searcharray) ; $i++){
// setcookie("checkloop", $i);;
$name = $searcharray['name'][$i];
$email= $searcharray['email'][$i];
$class = $searcharray['class'][$i];
$present= $searcharray['present'][$i];
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
//get class id
$class_query = "SELECT * FROM class WHERE name='".$class."'";
$class_id = mysqli_query($conn, $class_query);
if($class_id){
echo "I am here";
while($class_id1 = $class_id->fetch_assoc()){
$class_id_fin = $class_id1['id'];
echo $class_id['id'];
}
}
else{
echo "Error: " . $class_query . "<br>" . mysqli_error($conn);
}
//get student id
$student_query = "SELECT * FROM user WHERE email='".$email."'";
$student_id = $conn->query($student_query);
if($student_id) {
while ($student_id1 = $student_id->fetch_assoc()) {
$student_id_fin = $student_id1['id'];
}
}
//insert or update the record
$query = "INSERT INTO attendance VALUES ( '".$class_id_fin."', '".$student_id_fin."' , '".$present."','".$sessionVal."','comment')
ON DUPLICATE KEY UPDATE isPresent='".$present."'";
print_r($query);
if(mysqli_query($conn, $query)){
echo json_encode(array('status' => 'success', 'message' => 'Attendance added!'));
} else{
echo json_encode(array('status' => 'error', 'message' => 'Error: ' . $query . '<br>' . mysqli_error($conn)));
}
}
$conn->close();
}
You did not provide a lot of information, but I understand from the comments that the error is $sessionVal is undefined.
if $_COOKIE['sessionVal'] is not set, try:
1- print_r($_COOKIE) and check if [sessionVal] is set;
2- Try to add a fallback to:
if(isset($_COOKIE['sessionVal'])){
$sessionVal = $_COOKIE['sessionVal'];
}
else {
$sessionVal = 0;
}
or
$sessionVal = (isset($_COOKIE['sessionVal'])) ? $_COOKIE['sessionVal'] : 0;
Bottom line, there is not point to check if a variable is set and not having a fallback in case it is not set.
I'm looking for help with my products list.
My Code:
<!DOCTYPE html>
<html>
<head>
<title> Produktliste </title>
</head>
<body>
<iframe name="dir" style="display:none;"></iframe>
<form action="shop.php" method="post">
<p> <h2> Produkt hinzufügen </h2> </p>
<p> Produktname: <input type="text" name="Produktname"/> </p>
<p> Produktbeschreibung: <textarea rows=2 cols=20 name="Produktbeschreibung"></textarea> </p>
<p> Preis: <input type="text" name="Preis"/> </p>
<input type="submit" name="speichern" value="Speichern"/>
</form>
<?php
$connect = new mysqli ('localhost', 'root', '');
$connect->select_db('shop');
if (#$_REQUEST["Produktname"] && #$_REQUEST["Produktbeschreibung"] && #$_REQUEST["Preis"]) {
$produktname = #$_REQUEST["Produktname"];
$beschreibung = #$_REQUEST["Produktbeschreibung"];
$preis = #$_REQUEST["Preis"];
$result = $connect->query("INSERT INTO `shop`.`produkte` (`Produktname`, `Beschreibung`, `Preis`) VALUES ('$produktname', '$beschreibung', '$preis');");
if(!$result) {
echo "SQL Fehler: " . $connect->error;
die;
} else { echo "Letzte ID: " . $connect->insert_id;
}
}
?>
<table border="2" width="30%" style="border:1px solid #000000; border-spacing:inherit; text-align:left;">
<br><br>
<tr>
<td> Produkt </td>
<td> Beschreibung </td>
<td> Preis </td>
<td> Funktionen </td>
<?php
$result = $connect->query("SELECT * FROM produkte");
while($obj = $result->fetch_object()) {
echo '<tr><td>' . $obj->Produktname . '</td><td>' . $obj->Beschreibung . '</td><td>' . $obj->Preis . ' EUR ' . '</td><td> Bearbeiten, Löschen </td></tr>';
}
?>
</tr>
</table>
<?php
if (isset($_REQUEST["delete"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
$result = $connect->query("DELETE FROM `shop`.`produkte` WHERE `ProduktID` = $ProduktID;");
header('Location: ./shop.php');
}
if(isset($_REQUEST["id"])) {
$url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$urlpart = explode('=', $url);
$ProduktID = end($urlpart);
// Update SQL Data?
}
if (!$result) {
echo "SQL Fehler: " . $connect->error;
die;
}
?>
</body>
</html>
I'm now looking for a way to retrieve the MySQL Data with the equivalent ID into the existing HTML Form and update it back to the MySQL Database... I'm currently learning PHP at the University and I can't think any further by myself.
It needs to get done withing this PHP File, like everything else is.
Thanks for any help! :)
If I understand you correct, you want to echo inserted row from database. Change the line:
$result = $connect->query("SELECT * FROM produkte");
into:
$result = $connect->query("SELECT * FROM produkte WHERE ID_prod_column = '$insertID'");
Try something like this. Just change "ID_prod_column" to correct name and $insertID to correct variable.
first I want to say that I'm a beginner in postgresql and php.. my company told me to create a database that they can view and edit on local server.. so I created the database in postgresql.. created a page that views the database:
<html>
<head>
<title>Ongoing projects</title>
</head>
<body bgcolor="666657">
<?php
//database access information
require_once("DB.php");
$host = "localhost";
$user = "admin";
$pass = "";
$db = "Project_list";
$port = "5432";
//open a connection to the database server
$connection = pg_connect("host=$host dbname=$db user=$user password=$pass port=$port");
if (!$connection)
{
die("Could not open connection to database server");
}
?>
<?php
$query = 'select * from ongoing';
$result = pg_query($query); $i = 0;
echo '<html><table bgcolor="666657" width="10" height="30" border="0" cellpadding="0" cellspacing="0"><td align="center"> <h1><font color = "#ffb200"> Ongoing projects</h1>';
echo '<html><body><table border= 2 BORDERCOLOR="000000" cellpadding="1" cellspacing="0"> <tr >';
while ($i < pg_num_fields($result)) {
$fieldName =pg_field_name($result, $i);
echo '<b>'.'<td width="2" bgcolor="666657" align="center">'.'<font color = "#ffb200">'. '</b>'.'<b>'. $fieldName . '</b>'. '</td>';
$i = $i + 1; }
echo("<td><align= center><font color = #ffb200><b>Action</td>");
echo '</tr>' ;
$i = 0;
while ($row = pg_fetch_row($result)) {
echo '<tr align="center" width="1">';
$count = count($row);
$y = 0;
while ($y < $count) {
$c_row = current($row);
echo '<td>' .'<font color = "#ffb200">'. $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo("<td><align= center><a href='editongoing.php?ProjectID=".$row[0]."'>Edit</a></td>");
echo '</tr>';
$i = $i + 1;
}
pg_free_result($result);
echo '</table></body></html>';
?>
<h3>
<a href="projects.php"</a>Back to projects page</a>
</h3>
<SCRIPT LANGUAGE="JavaScript">
if (window.print) {
document.write('<form> '
+ '<input type=button name=print value="Click" '
+ 'onClick="javascript:window.print()"> To Print!</form>');
}
// End -->
</script>
when you click the edit button, you will go to this page where you can edit the raw you want, this is the (edit) code:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>Edit Ongoing projects</title>
</head>
<body bgcolor="666657">
<?php
// attempt a connection
$connection = pg_connect("host=localhost dbname=Project_list user=admin password=");
if (!$connection) {
die("Error in connection: " . pg_last_error());
}
if ($_REQUEST['ProjectID']!=''){
$QueryStr = "Select * from ongoing where project_no='".$_REQUEST['ProjectID']."'";
$result = pg_query($connection, $QueryStr);
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
$row = pg_fetch_row($result);
print_r($row);
}
if ($_POST['submit']) {
// escape strings in input data
$project_no = pg_escape_string($_POST['project_no']);
$title = pg_escape_string($_POST['title']);
$duration = pg_escape_string($_POST['duration']);
$manager = pg_escape_string($_POST['manager']);
$country = pg_escape_string($_POST['country']);
$total_fee = pg_escape_string($_POST['totalfee']);
$performed = pg_escape_string($_POST['performed']);
$remaining = pg_escape_string($_POST['remaining']);
$gross_profit = pg_escape_string($_POST['gross_profit']);
$gp = pg_escape_string($_POST['gp']);
$performance_year = pg_escape_string($_POST['performance_year']);
$gp_year = pg_escape_string($_POST['gp_year']);
// execute query
$sql = "INSERT INTO ongoing (project_no, project_title, duration, manager, country, total_fee,
performed, remaining, gross_profit, gp, performance_year, gp_year)
VALUES('$project_no', '$title', '$duration', '$manager', '$country','$total_fee','$performed','$remaining',
'$gross_profit','$gp', '$performance_year','$gp_year')";
$result = pg_query($connection, $sql);
f (!$result) {
die("Error in SQL query: " . pg_last_error());
}
echo "Data successfully inserted!";
// free memory
pg_free_result($result);
// close connection
pg_close($connection);
}
?>
<form action= "<?php echo $_SERVER['PHP_SELF']; ?>" method="post"><b><font color = "#ffb200">
Project No.: <br> <input id="project_no" type="text" name="project_no" size="20" value=<?= $row[0] ?>>
<p>
Project Title: <br> <input id="title" type="text" name="title" value='<?= $row[1] ?>'>
<p>
Duration: <br> <input ID="duration" type="text" name="duration" value=<?= $row[2] ?>>
<p>
Project Manager: <br> <input ID="manager" type="text" name="manager" value=<?= $row[3] ?>>
<p>
Country: <br> <input ID="country" type="text" name="country" value=<?= $row[4] ?>>
<p>
Total Fee: <br> <input ID="totalfee" type="text" name="total_fee" value=<?= $row[5] ?>>
<p>
Already performed: <br> <input ID="performed" type="text" name="performed" value=<?= $row[6] ?>>
<p>
Remaining performance: <br> <input ID="remaining" type="text" name="remaining" value=<?= $row[7] ?>>
<p>
Gross Profit: <br> <input ID="gross_profit" type="text" name="gross_profit" value='<?= $row[8] ?>'>
<p>
GP%: <br> <input ID="gp" type="text" name="gp" value=<?= $row[9] ?>>
<p>
Performance actual year: <br> <input ID="performance_year" type="text" name="performance_year" value=<?= $row[10] ?>>
<p>
GP actual year: <br> <input ID="gp_year" type="text" name="gp_year" value=<?= $row[11] ?>>
<p>
<input type="submit" name="submit" value="Sumbit my table" size="30">
<P>
<a href="ongoing.php"</a>View ongoing projects</a>
<a href="editproject.php"</a>Back to editing menu</a>
</form>
</body>
</html>
My problem is, when I edit the data and click on submit my table, a new raw is inserted.. but I want it to be updated not inserted... help plz
You need to select which record (id number) you want to update, and then your query will look like
$sql = "UPDATE ongoing SET field1='value', field2='value' ... WHERE id = 'id of project you want to edit'";