Editing MySQL row via POST form - php

I've encountered a problem which i'll try to describe below...
Let's say i've got a button for each table row (table is created by acquiring the data from the database...). the button sends a massive of values via post.
<button value='$e->eventId|$e->eventType|$e->eventDate|$e->eventPrice|$e->eventDescr' name='editValue'>EDIT</button>
I've written a function to explode the values of the massive and fill the inputs on the same page.
if(!empty($_POST['editValue'])) {
$editValue_fill = explode("|", $_POST["editValue"]);
$eventId = $editValue_fill[0];
$eventType = $editValue_fill[1];
$eventDate = $editValue_fill[2];
$eventPrice = $editValue_fill[3];
$eventDescr = $editValue_fill[4];
}
Next comes the function to edit the row in the database.
function editEvent ($id, $type, $date, $price, $descr){
$mysqli = new mysqli($GLOBALS["serverHost"], $GLOBALS["serverUsername"], $GLOBALS['serverPassword'], $GLOBALS['dbName']);
$stmt = $mysqli->prepare("UPDATE events_archive SET eventType='?', eventDate='?', eventPrice='?', eventDescr='?' WHERE id='?'");
$stmt->bind_param("ssdss", $type, $date, $price, $descr, $id);
$stmt->execute();
header("Refresh:0");
if($stmt->execute()){
$eventNotice="Event successfully updated!";
}else{
$eventNotice = "Failed to save...";
}
return $eventNotice;
}
And, of course, the usage of the function which apparently doesnt work. The page just refreshes and nothing happens.
if(empty($eventTypeError)&& empty($eventDateError)&& empty($eventPriceError) && empty($eventDescrError)
&& isset($_POST['eventType']) && isset($_POST['eventDate']) && isset ($_POST['eventPrice']) && isset
($_POST['eventDescr']) && !empty($eventId)){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}
So basically, gets values from the row -> fills them into inputs in the same page -> if $eventId is set then updates the row, if not - creates a new row (diff. function)
Could anyone give me a tip or help solving the problem? I've been trying to understand the issue and failed dramatically...
<?php
require ("functions.php");
var_dump($_POST);
//kas on sisseloginud, kui ei ole siis
//suunata login lehele
//kas ?logout on aadressireal
if (isset($_GET['logout'])){
session_destroy();
header("Location: login.php");
}
if (!isset ($_SESSION["userId"])){
header("Location: login.php");
}
$confirm = "";
$eventNotice = "";
$eventTypeError = "";
$eventDateError = '';
$eventPriceError = '';
$eventDescrError = '';
$eventType = '';
$eventDescr = '';
$eventPrice = '';
$eventDate = date("Y-m-d");
if (isset ($_POST["eventType"])){
if (empty($_POST['eventType'])){
$eventTypeError = "Please choose the event type!";
} else {
$eventType = $_POST["eventType"];
}
}
if (isset ($_POST ["eventDate"])){
if (empty ($_POST ["eventDate"])){
$eventDateError = "Please choose the date!";
} else {
$eventDate = $_POST["eventDate"];
}
}
if (isset ($_POST ["eventPrice"])){
if (empty ($_POST ["eventPrice"])){
$eventPriceError = "Please type in the price!";
} else {
$eventPrice = $_POST["eventPrice"];
}
}
if (isset ($_POST ["eventDescr"])){
if (empty ($_POST ["eventDescr"])){
$eventDescrError = "Please type in the description!";
}elseif (strlen($_POST["eventDescr"])< 10) {
$eventDescrError = "Description must be longer than 10 symbols!";
$eventDescr = $_POST['eventDescr'];
}else{
$eventDescr = $_POST['eventDescr'];
}
}
$event = getAllEvents();
if(!empty($_POST['delValue'])) {
delEvent($_POST['delValue']);
}
if(!empty($_POST['editValue'])) {
$editValue_fill = explode("|", $_POST["editValue"]);
$eventId = $editValue_fill[0];
$eventType = $editValue_fill[1];
$eventDate = $editValue_fill[2];
$eventPrice = $editValue_fill[3];
$eventDescr = $editValue_fill[4];
echo ($eventId);
echo ($eventDate);
echo ($eventPrice);
echo ($eventType);
echo ($eventDescr);
}
if(empty($eventTypeError)&& empty($eventDateError)&& empty($eventPriceError) && empty($eventDescrError)
&& isset($_POST['eventType']) && isset($_POST['eventDate']) && isset ($_POST['eventPrice']) && isset
($_POST['eventDescr'])){
if(isset($_POST['editValue'])){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}elseif(!isset($_POST['editValue'])){
$eventNotice = newEvent(cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}
}
?>
<html>
<style>
#import "styles.css";
ul.tab {
list-style-type: none;
margin: 0;
padding: 0;
overflow: hidden;
border: 1px solid #ccc;
background-color: #f1f1f1;
}
ul.tab li {float: left;}
ul.tab li a {
display: inline-block;
color: black;
text-align: center;
padding: 14px 16px;
text-decoration: none;
transition: 0.3s;
font-size: 17px;
}
ul.tab li a:hover {
background-color: #ddd;
}
ul.tab li a:focus, .active {
background-color: #ccc;
}
.tabcontent {
display: none;
padding: 6px 12px;
border: 1px solid #ccc;
border-top: none;
}
</style>
<body>
<form method ="post">
<table class="table1">
<tr>
<td style="text-align:center"><h1>Data</h1></td>
</tr>
<tr>
<th><h2>Profile</h2></th>
</tr>
<tr>
<td>
<table class="table2">
<tr>
<td colspan="3"">Welcome <?=$_SESSION['email'];?>!</td>
</tr>
<tr>
<td colspan="3" style="text-align:center">Log out</td>
</tr>
</table>
<tr>
<td>
<tr>
<td>
<ul class="tab">
<li>Add/edit</li>
<li>Archive</li>
</ul>
<div id="Add/edit" class="tabcontent">
<input type="hidden" value='eventId'>
<table class="table2">
<tr>
<td>Event type:<span class = 'redtext'>*</span></td>
<td style="text-align:left">
<select name="eventType">
<?php if(empty($eventType)){?>
<option value="" selected>Choose here</option>
<?php } else { ?>
<option value="">Choose here</option>
<?php } ?>
<?php if($eventType == "Planned service"){?>
<option value="Planned service" selected>Planned service</option>
<?php } else { ?>
<option value="Planned service">Planned service</option>
<?php } ?>
<?php if($eventType == "Unplanned service"){?>
<option value="Unplanned service" selected>Unplanned service</option>
<?php } else { ?>
<option value="Unplanned service">Unplanned service</option>
<?php } ?>
<?php if($eventType == "Fuel checks"){?>
<option value="Fuel checks" selected>Fuel checks</option>
<?php } else { ?>
<option value="Fuel checks">Fuel checks</option>
<?php } ?>
<?php if($eventType == "Tuning"){?>
<option value="Tuning" selected>Tuning</option>
<?php } else { ?>
<option value="Tuning">Tuning</option>
<?php } ?>
<?php if($eventType == "Car accident"){?>
<option value="Car accident" selected>Car accident</option>
<?php } else { ?>
<option value="Car accident">Car accident</option>
<?php } ?>
</select>
</td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventTypeError?></td></tr>
<tr>
<td>Date:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><input name="eventDate" type ="date" min="1900-01-01" max = "<?=date('Y-m-d'); ?>" value = "<?=$eventDate?>" placeholder="YYYY-MM-DD"></td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventDateError?></td></tr>
<tr>
<td>Price:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><input type="text" name="eventPrice" placeholder="ex. 15.50" onkeypress="return onlyNumbersWithDot(event);" / value = "<?=$eventPrice?>"></td>
<script type="text/javascript">
function onlyNumbersWithDot(e) {
var charCode;
if (e.keyCode > 0) {
charCode = e.which || e.keyCode;
}
else if (typeof (e.charCode) != "undefined") {
charCode = e.which || e.keyCode;
}
if (charCode == 46)
return true
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
</script>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventPriceError?></td></tr>
<tr>
<td>Description:<span class = 'redtext'>*</span></td>
<td style="text-align:left"><textarea name="eventDescr" cols="50" rows="10" placeholder="Describe event here..."><?=$eventDescr?></textarea></td>
</tr>
<tr><td colspan="3" class="redtext" style="text-align:center"><?=$eventDescrError?></td></tr>
<tr>
<td colspan="3" style="text-align:center"><button type ="submit" value = "Submit">Save</button></td>
</tr>
<tr>
<td colspan="3" style="text-align:center"><p class = "redtext"><?=$eventNotice;?></p></td>
</tr>
</table>
</div>
</form>
<form method="post">
<div id="Archive" class="tabcontent">
<table class="table2">
<tr>
<td colspan="3"">
<?php
$html = "<table>";
$html .= "<tr>";
$html .= "<th>Event type</th>";
$html .= "<th>Date</th>";
$html .= "<th>Price(€)</th>";
$html .= "<th>Description</th>";
$html .= "<th>Delete</th>";
$html .= "<th>Edit</th>";
$html .= "</tr>";
foreach($event as $e){
$html .= "<tr>";
$html .= "<td>$e->eventType</td>";
$html .= "<td>$e->eventDate</td>";
$html .= "<td>$e->eventPrice</td>";
$html .= "<td>$e->eventDescr</td>";
$html .= "<td><button style='border:none; background-color: transparent;' value='$e->eventId' name='delValue' onclick=\"return confirm('Do you really want to delete this row?')\"><img src='delete.png' width='20' height='20'></button></td>";
$html .= "<td><button style='border:none; background-color: transparent;' value='$e->eventId|$e->eventType|$e->eventDate|$e->eventPrice|$e->eventDescr' name='editValue'><img src='edit.png' width='20' height='20'></button></td>";
$html .= "</tr>";
}
$html .= "</table>";
echo $html;
?>
</td>
</tr>
</div>
<script>
function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.className += " active";
}
// Get the element with id="defaultOpen" and click on it
document.getElementById("defaultOpen").click();
</script>
</td>
</tr>
</table>
</td>
</tr>
</div>
</form>
</body>
</html>
Looking forward to Your help!
Best regards :)

if(isset($_POST['editValue'])){
$eventNotice = editEvent($eventId, cleanInput($eventType), cleanInput($eventDate), cleanInput($eventPrice), cleanInput($eventDescr));
}

Related

Hide row if field is N/A or empty

I have a question regarding hiding empty rows in my table.
I want to hide an entire row in the case a field says N/A which means the field is empty.
Example:
In the event that the field is empty or N/A, I want to hide the entire row. I will also welcome javascript solutions.
<tbody style="
white-space: nowrap;
">
<?php
foreach($student_subject_list AS $SSL)
{
$subject_name = $SSL["name"];
if(in_array($subject_name, array_keys($result)))
{
$total_score = 0;
$avg = count($result[$subject_name]);
$test_results = "";
$i = 1;
foreach($result[$subject_name] AS $SN)
{
if($i == 1)
{
$ie = "1<sup>st</sup>";
}
elseif($i == 2)
{
$ie = "<br>2<sup>nd</sup>";
}
elseif($i == 3)
{
$ie = "<br>3<sup>rd</sup>";
}
else
{
$ie = "<br>4<sup>th</sup>";
}
$test_results .= "$ie Test: $SN ";
$total_score += $SN;
$avg_score = $total_score/$avg;
$i++;
}
}
else
{
$total_score = $test_results = "N/A";
}
?>
<tr>
<td style="border: 1px solid black; font-size:11px;width:120px;white-space: nowrap;height:30px;"><?=$subject_name?></td>
<td style="border: 1px solid black; font-size:11px;width:120px;text-align:center;"><?=$test_results?></td>
<td style="border: 1px solid black; font-size:11px;width:120px;text-align:center;"><?=$avg_score?></td>
<td style="border: 1px solid black; font-size:11px;width:120px;text-align:center;"><?=$remark?></td>
</tr>
<?php
}
?>
</tbody>
Could you make the html where you create the row conditional on $test_results NOT being equal to "N/A"? Something like this:
<?php if(!$test_results === "N/A"){ ?>
<tr>
<td> etc etc
<td> etc etc
<td> etc etc
<td> etc etc
</tr>
<?php } ?>

Truncate before inserting data to mysql with PHP

I'm trying to upload an excel file to a mysql DB using PHP. I've got this working.
However, if I refresh the page or upload again another file, it gets duplicated.
I would like before it uploads a new file to clear (truncate) the table and then insert the new data.
Bue I cannot find where to put or how to put the TRUNCATE TABLE existencias_2018; if the Submit button is clicked and before it inserts the data.
Another issue is the refreshing thing. It is a way to stop the refresh after I've uploaded the data? Or a way that refreshing doesn't duplicate it?
So in summary the help i need is:
Where to put and how the TRUNCATE TABLE existencias_2018;.
Stop duplicating data if page gets refreshed.
Here is my piece of code:
<?php
$conn = mysqli_connect("localhost","root","","papa");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"])){
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++){
$Reader->ChangeSheet($i);
foreach ($Reader as $Row){
$model = "";
if(isset($Row[0])) {
$model = mysqli_real_escape_string($conn,$Row[0]);
}
$cup = "";
if(isset($Row[1])) {
$cup = mysqli_real_escape_string($conn,$Row[1]);
}
$color = "";
if(isset($Row[1])) {
$color = mysqli_real_escape_string($conn,$Row[2]);
}
$description = "";
if(isset($Row[1])) {
$description = mysqli_real_escape_string($conn,$Row[3]);
}
$size36 = "";
if(isset($Row[1])) {
$size36 = mysqli_real_escape_string($conn,$Row[4]);
}
$size38 = "";
if(isset($Row[1])) {
$size38 = mysqli_real_escape_string($conn,$Row[5]);
}
$size40 = "";
if(isset($Row[1])) {
$size40 = mysqli_real_escape_string($conn,$Row[6]);
}
$size42 = "";
if(isset($Row[1])) {
$size42 = mysqli_real_escape_string($conn,$Row[7]);
}
$size44 = "";
if(isset($Row[1])) {
$size44 = mysqli_real_escape_string($conn,$Row[8]);
}
$size46 = "";
if(isset($Row[1])) {
$size46 = mysqli_real_escape_string($conn,$Row[9]);
}
$size48 = "";
if(isset($Row[1])) {
$size48 = mysqli_real_escape_string($conn,$Row[10]);
}
$size50 = "";
if(isset($Row[1])) {
$size50 = mysqli_real_escape_string($conn,$Row[11]);
}
$size52 = "";
if(isset($Row[1])) {
$size52 = mysqli_real_escape_string($conn,$Row[12]);
}
$size54 = "";
if(isset($Row[1])) {
$size54 = mysqli_real_escape_string($conn,$Row[13]);
}
if (!empty($model) || !empty($cup) || !empty($color) || !empty($description) || !empty($size36) || !empty($size38) || !empty($size40) || !empty($size42) || !empty($size44) || !empty($size46) || !empty($size48) || !empty($size50) || !empty($size52) || !empty($size54)) {
$query = "insert into existencias_2018(model,cup,color,description,size36,size38,size40,size42,size44,size46,size48,size50,size52,size54) values('".$model."','".$cup."','".$color."','".$description."','".$size36."','".$size38."','".$size40."','".$size42."','".$size44."','".$size46."','".$size48."','".$size50."','".$size52."','".$size54."')";
$result = mysqli_query($conn, $query);
if (! empty($result)) {
$type = "success";
$message = "Datos de Excel importados en la base de datos satisfactoriamente";
} else {
$type = "error";
$message = "Ha habido un problema al importar los datos de Excel";
}
}
}
}
}else{
$type = "error";
$message = "Tipo de archivo invalido. Suba un archivo de Excel.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: Arial;
width: 1000px;
}
.outer-container {
background: #F0F0F0;
border: #e0dfdf 1px solid;
padding: 40px 20px;
border-radius: 2px;
}
.btn-submit {
background: #333;
border: #1d1d1d 1px solid;
border-radius: 2px;
color: #f0f0f0;
cursor: pointer;
padding: 5px 20px;
font-size:0.9em;
}
.tutorial-table {
margin-top: 40px;
font-size: 0.8em;
border-collapse: collapse;
width: 100%;
}
.tutorial-table th {
background: #f0f0f0;
border-bottom: 1px solid #dddddd;
padding: 8px;
text-align: left;
}
.tutorial-table td {
background: #FFF;
border-bottom: 1px solid #dddddd;
padding: 8px;
text-align: left;
}
#response {
padding: 10px;
margin-top: 10px;
border-radius: 2px;
display:none;
}
.success {
background: #c7efd9;
border: #bbe2cd 1px solid;
}
.error {
background: #fbcfcf;
border: #f3c6c7 1px solid;
}
div#response.display-block {
display: block;
}
</style>
</head>
<body>
<h2>Importar existencias actualizadas</h2>
<div class="outer-container">
<form action="" method="post"
name="frmExcelImport" id="frmExcelImport" enctype="multipart/form-data">
<div>
<label>Buscar archivo Excel</label>
<input type="file" name="file" id="file" accept=".xls,.xlsx">
<button type="submit" id="submit" name="import" class="btn-submit">Importar</button>
</div>
</form>
</div>
<div id="response" class="<?php if(!empty($type)) { echo $type . " display-block"; } ?>"><?php if(!empty($message)) { echo $message; } ?></div>
<?php
$sqlSelect = "SELECT * FROM existencias_2018";
$result = mysqli_query($conn, $sqlSelect);
if (mysqli_num_rows($result) > 0){
?>
<table class='tutorial-table'>
<thead>
<tr>
<th>Modelo</th>
<th>Copa</th>
<th>Color</th>
<th>Descripcion</th>
<th>36</th>
<th>38</th>
<th>40</th>
<th>42</th>
<th>44</th>
<th>46</th>
<th>48</th>
<th>50</th>
<th>52</th>
<th>54</th>
</tr>
</thead>
<?php
$sql = "TRUNCATE TABLE existencias_2018";
while ($row = mysqli_fetch_array($result)) {
?>
<tbody>
<tr>
<td><?php echo $row['model']; ?></td>
<td><?php echo $row['cup']; ?></td>
<td><?php echo $row['color']; ?></td>
<td><?php echo $row['description']; ?></td>
<td><?php echo $row['size36']; ?></td>
<td><?php echo $row['size38']; ?></td>
<td><?php echo $row['size40']; ?></td>
<td><?php echo $row['size42']; ?></td>
<td><?php echo $row['size44']; ?></td>
<td><?php echo $row['size46']; ?></td>
<td><?php echo $row['size48']; ?></td>
<td><?php echo $row['size50']; ?></td>
<td><?php echo $row['size52']; ?></td>
<td><?php echo $row['size54']; ?></td>
</tr>
<?php
}
?>
</tbody>
</table>
<?php
}
?>
</body>
</html>
Is that what you want ?
<?php
$conn = mysqli_connect("localhost","root","","papa");
require_once('vendor/php-excel-reader/excel_reader2.php');
require_once('vendor/SpreadsheetReader.php');
if (isset($_POST["import"])){
$allowedFileType = ['application/vnd.ms-excel','text/xls','text/xlsx','application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
if(in_array($_FILES["file"]["type"],$allowedFileType)){
// Looks like we have a correct file to upload.
// Let's TRUNCATE the table first :
$query = "TRUNCATE TABLE existencias_2018;";
mysqli_query($conn, $query);
// OK, table is empty, proceed with upload....
$targetPath = 'uploads/'.$_FILES['file']['name'];
move_uploaded_file($_FILES['file']['tmp_name'], $targetPath);
$Reader = new SpreadsheetReader($targetPath);
$sheetCount = count($Reader->sheets());
for($i=0;$i<$sheetCount;$i++){
$Reader->ChangeSheet($i);
foreach ($Reader as $Row){
$model = "";
if(isset($Row[0])) {
$model = mysqli_real_escape_string($conn,$Row[0]);
}
// and so on...

Viewing queried data from mysql database in a table

I am attempting to update the code for my web page's search function, right now it is not returning anything. I have been working with it for a little while and not getting anything out of it.
This is the HTML search code:
<form method="post" action="words_results1.php">
<table align="center">
<tr>
<td>Keyword</td>
<td><input type="text" name="Keyword" /></td>
</tr>
<tr>
<td>Author</td>
<td><input type="text" name="Author" /></td>
</tr>
<tr>
<td valign=bottom>Words Posted<BR />on or before</td>
<td valign=top>
<table>
<tr>
<td width="33%">Day</td>
<td width="33%">Month</td>
<td width="34%">Year</td>
</tr>
<tr>
<td>
<select name=Day>
<?php
echo '<option></option>';
for($count = 1; $count <= 31; ++$count)
{
echo "<option>$count</option>";
}
?>
</select>
</td>
<td>
<select name=Month>
<?php
echo '<option></option>';
for($count = 1; $count <= 12; $count++)
{
echo "<option value=$count>".date("M", mktime(0,0,0,$count,1, 2000))."</option>";
}
?>
</select>
</td>
<td>
<select name=Year>
<?php
echo '<option></option>';
for($count = date("Y"); $count >= 1997; $count--)
{
echo "<option>$count</option>";
}
?>
</select>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan=2 align=center>
<BR />
<input type="submit" value="Search" />
<input type="submit" name="cancel" value="Cancel" />
</td>
</tr>
</table>
</form>
PHP
<?php
if(isset($_POST['cancel']))
{
echo("index.html");
exit;
}
$qry_string = "SELECT * FROM Words";
$search = "";
if(!empty($Keyword))
{
$End_String = "(Word LIKE '%$Keyword%' OR Title LIKE '%$Keyword%')";
$search .="&Keyword=$Keyword";
}
if(!empty($Author))
{
if(isset($End_String))
{
$End_String .= " AND (Author LIKE '%$Author%')";
}
else
{
$End_String = "(Author LIKE '%$Author%')";
}
$search .="&Author=$Author";
}
if(!empty($Day))
{
if(isset($End_String))
{
$End_String .= " AND (DAYOFMONTH(Date_Created) = '$Day')";
}
else
{
$End_String = "(DAYOFMONTH(Date_Created) = '$Day')";
}
$search .="&Day=$Day";
}
if(!empty($Month))
{
if(isset($End_String))
{
$End_String .= "AND (MONTH(Date_Created) = '$Month')";
}
else
{
$End_String = "(MONTH(Date_Created) = '$Month')";
}
$search .="&Month=$Month";
}
if(!empty($Year))
{
if(isset($End_String))
{
$End_String .= " AND (YEAR(Date_Created) = '$Year')";
}
else
{
$End_String = "(YEAR(Date_Created) = '$Year')";
}
$search .="&Year=$Year";
}
if (!isset($offset)) $offset=0;
if(isset($End_String))
{
$qry_string = $qry_string." WHERE ".$End_String . " ORDER BY Date_Created DESC LIMIT $offset,101";
}
else
{
$qry_string = $qry_string." ORDER BY Date_Created DESC LIMIT $offset,101";
}
// echo $qry_string . "<P><HR><P>";
$result = mysql_query($qry_string);
echo mysql_error();
?>
This last bit is the code that forms the table, I have an assumption that the problem lies here but honestly am not sure at this point
<table style="margin: 5px 15px; 5px 20px;" align="center" bgcolor="#666666" border="0" cellpadding="3" cellspacing="1">
<tbody><tr style="background: #04C1DE; font-family: Verdana; font-weight: bold; font-size: 18px;">
<td style="width: 50%; padding: 5px;">
Word
</td>
<td style="width: 20%; padding: 5px;">
Author
</td>
<td style="width: 10%; padding: 5px;">
Date
</td>
<td>Category</td>
<td>Active?</td>
<td> </td>
<td> </td>
</tr>
</tbody>
</tr>
<?php
$count = 1;
$bgc = 0;
while($row = mysql_fetch_array($sql))
{
if ($count > 100) break;
echo '<tr style="background: ';
if ($bgc==0) echo "#FFFFFF";
else echo "#CFEBFD";
$bgc == 0?$bgc=1:$bgc=0;
echo ';">';
echo "<td><a href=../../words/display_word.php?ID=$row[ID]>$row[Title]</a></td>";
echo "<td>$row[Author]</td><td>$row[Display_Date]</td><td>$row[category]</td>";
if($row[active])
{
echo "<td>YES</td>";
}
else
{
echo "<td>NO</td>";
}
echo "<td>$row[link_count]</td>";
if($row[Title] != "")
{
echo "<td><a href=words_edit.html?ID=$row[ID]>Edit</a></td></tr>";
}
else
{
echo "</tr>";
}
$count++;
}
?>
It seems,you are not collecting the value of
$Keyword=$_POST['Keyword'];
and add ,closing table tag to display the results in the table format correctly.

Sending Email From PHP Script

I have a page which is used for booking room for meetings. I have form on which all the details for booking is required. I have fetched email id from the MySql db.I want to send email on click of submit button. I have 2 files namely home.php & insert.php. In home.php i have the form & insert.php inserts the data into the db. I tried the email functionality code but it's not working.
Please Help
room.php
<?php session_start();
if(isset($_GET['selecteddate']))
{
$selecteddate=$_GET['selecteddate'];
}
else
{
$selecteddate=date("Y-m-d");
}
?>
<html>
<head><title>MRA</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
<style>
#heading{ text-align:right;font-size: 20px;float:right;margin:50px 20px;}
a:hover{ color:#BEBEBC; }
a{ color:black;}
#img{ margin:10px 10px; }
#td{border-radius: 5px;border-style: solid;}
.name-error,.meeting-error { color: red; margin: 0 10px; }
#plan { position: fixed; left: 50%; margin-left: -239px; top: 50%; margin-top: -150px; z-index: 10;background-color: #fff; padding: 10px; }
#plan-bg { width: 100%; height: 100%; position: fixed; background: #000; opacity: 0.8; top: 0;display: none; z-index: 5; }
.close { position: absolute; top: 5px; right: 10px; cursor: pointer; }
.close:hover { text-decoration: underline; }
#datepicker { width: 40%; float: left; }
.calender-date { padding: 10px 10px; }
#time-slot-msg,#alert-msg { position: fixed; top: 50%; left: 50%; background: #fff; font-size: 25px; padding: 10px 20px; margin: -50px 0 0 -184.5px; display: none; z-index: 10;border-radius: 5px; }
#time-slot-msg p,#alert-msg p { font-weight: bold; }
#time-slot-msg .close,#alert-msg .close { font-size: 15px; right: 20px;}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
var $index;
var systemdate = new Date();
$('.meeting-error').hide();
$(".meeting-timetable tr > td + td").click(function(e) {
if($(this).hasClass('active')) {
e.preventDefault();
alert('The selected time slot has already been assigned');
} else {
var $thisVal = $(this).prevAll('td:first-child').text();
var hour=$thisVal.substr(0,2);
var min=$thisVal.substr(3,3);
var d = new Date ("<?php print $selecteddate; ?>");
var n = d.getFullYear();
var m = d.getDate();
var k = d.getMonth();
var userdate=new Date(n,k,m,hour,min,0);
if( systemdate > userdate )
{
alert("Select Time Slot greater than the Current Time");
return;
}
$index = $(this).index();
// Start time.
$(".start-time option").each(function() {
if (($(this).text() === $thisVal)) {
$(this).attr('selected', 'selected');
$(this).prevAll().attr('disabled', 'disabled');
}
});
// Change end time.
$(".end-time option").each(function() {
if (($(this).text() === $thisVal)) {
$(this).next().attr('selected', 'selected');
$(this).attr('disabled', 'disabled');
$(this).prevAll().attr('disabled', 'disabled');
}
});
// Date input select.
var $date = $('.meeting-timetable tr:first-child th').text();
var dateFormat = $.datepicker.formatDate('yy-mm-dd', new Date($date));
$('.date').val(dateFormat);
$('#meeting').val('');
$('.meeting-error').hide();
// Show dialog box.
var _cellIndex = $(this)[0].cellIndex;
var _rowIndex = $(this).closest('tr')[0].sectionRowIndex;
var total_row = $('.meeting-timetable tr').length - 1;
if( _rowIndex == total_row && _cellIndex == 1 ) {
alert('You cannot select this time slot');
}
else $('#plan, #plan-bg').fadeIn();
}
});
// On submit click change background color.
$('.submit-button').click(function(e) {
e.preventDefault();
var selectedValue = $(".start-time option:selected").text(),
selectedEndValue = $(".end-time option:selected").text(),
$name = $('input[name=txtname]').val();
if($('#meeting').val()) {
$(".meeting-timetable tr > td").each(function() {
if ($(this).text() === selectedValue) {
$(this).parent('tr').addClass('active');
}
if ($(this).text() === selectedEndValue) {
var $parent = $(this).parent('tr').prevUntil('tr.active').addClass('active');
}
// Prev all td selected.
$($parent).each(function(){
});
});
}
// Form validation.
if ($('#meeting').val() === '') { $('.meeting-error').fadeIn(); }
// Grab form values
var formData = {
'txtrname' : $('input[name=txtrname]').val(),
'txtname' : $('input[name=txtname]').val(),
'txtemail' : $('input[name=txtemail]').val(),
'txtpurpose' : $('input[name=txtpurpose]').val(),
'attendee' : $('select[name=attendee]').val(),
'txtdate' : $('input[name=txtdate]').val(),
'btime' : $('select[name=btime]').val(),
'etime' : $('select[name=etime]').val()
};
if($('#meeting').val().trim()) {
// Ajax form submit.
$.ajax({
type: "POST",
url: "insertkarma.php",
data: formData,
success: function()
{
$('#alert-msg').fadeIn();
$('#plan').fadeOut();
}
});
} else { alert('Please enter the purpose of meeting'); } });
// on focus function
$('#meeting').focus(function() {
$('.meeting-error').fadeOut();
}).blur(function() {
if (!$(this).val()) {
$('.meeting-error').fadeIn();
}
});
$(".close").click(function() {
$('.pop-up').fadeOut();
});
// Adding calender.
$( "#datepicker" ).datepicker({
minDate: 0,
dateFormat: "yy-mm-dd",
onSelect: function (date) {
var url="karma.php?selecteddate="+date;
window.location.assign(url);
}
});
});
</script>
</head>
<body background="a9.jpg">
<img id="img" src="HITECHLOGO.jpg" width="150px" height="100px">
<h1 align="center" style="position:absolute;top:30px; left:600px;">KARMA <br>(3-SEATER)</h1>
<div id="heading">Home <?php echo ucwords($_SESSION['usr_name']); ?></font> Change Password Logout Help</div>
<hr width="100%">
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$i = 0;
$dateEntry = "SELECT `starttime` , `status_id` , `name` , floor(( time_to_sec(`endtime`)-time_to_sec(`starttime`) )/1800) as testing FROM `karmadetails` WHERE `date` = '$selecteddate' order by starttime";
if ($result=mysqli_query($conn,$dateEntry)) {
while ($obj=mysqli_fetch_object($result))
{
$starttime[$i] = $obj->starttime;
$status[$i] = $obj->status_id;
$name[$i] = $obj->name;
$testing[$i] = $obj->testing;
$i++;
}
}
mysqli_close($conn);
?>
<table border="1" align="right" width="60%" style="border:black;">
<tr><td id="td" colspan="3" align="center"><h1>Click to Book a Time Slot</h1></td></tr>
<tr><td bgcolor="red" align="center" id="td">Booked</td><td align="center" id="td">Available</td></td></tr>
<tr><td id="td" colspan="3">| Today |</td></tr></table>
<table class="meeting-timetable" border="1" align="right" width="60%" style="border:black;">
<tr><th id="td" colspan="2" class="calender-date" align="center"><?php print $selecteddate; ?></th></tr>
<tr><td id="08:00:00" align="center" style="border-radius: 5px;border-style: solid;" width="10%">08:00</td><td id="td"></td></tr>
<tr><td id="08:30:00" align="center" style="border-radius: 5px;border-style: solid;">08:30</td><td id="td"></td></tr>
<tr><td id="09:00:00" align="center" style="border-radius: 5px;border-style: solid;">09:00</td><td id="td"></td></tr>
<tr><td id="09:30:00" align="center" style="border-radius: 5px;border-style: solid;">09:30</td><td id="td"></td></tr>
<tr><td id="10:00:00" align="center" style="border-radius: 5px;border-style: solid;">10:00</td><td id="td"></td></tr>
<tr><td id="10:30:00" align="center" style="border-radius: 5px;border-style: solid;">10:30</td><td id="td"></td></tr>
<tr><td id="11:00:00" align="center" style="border-radius: 5px;border-style: solid;">11:00</td><td id="td"></td></tr>
<tr><td id="11:30:00" align="center" style="border-radius: 5px;border-style: solid;">11:30</td><td id="td"></td></tr>
<tr><td id="12:00:00" align="center" style="border-radius: 5px;border-style: solid;">12:00</td><td id="td"></td></tr>
<tr><td id="12:30:00" align="center" style="border-radius: 5px;border-style: solid;">12:30</td><td id="td"></td></tr>
<tr><td id="13:00:00" align="center" style="border-radius: 5px;border-style: solid;">13:00</td><td id="td"></td></tr>
<tr><td id="13:30:00" align="center" style="border-radius: 5px;border-style: solid;">13:30</td><td id="td"></td></tr>
<tr><td id="14:00:00" align="center" style="border-radius: 5px;border-style: solid;">14:00</td><td id="td"></td></tr>
<tr><td id="14:30:00" align="center" style="border-radius: 5px;border-style: solid;">14:30</td><td id="td"></td></tr>
<tr><td id="15:00:00" align="center" style="border-radius: 5px;border-style: solid;">15:00</td><td id="td"></td></tr>
<tr><td id="15:30:00" align="center" style="border-radius: 5px;border-style: solid;">15:30</td><td id="td"></td></tr>
<tr><td id="16:00:00" align="center" style="border-radius: 5px;border-style: solid;">16:00</td><td id="td"></td></tr>
<tr><td id="16:30:00" align="center" style="border-radius: 5px;border-style: solid;">16:30</td><td id="td"></td></tr>
<tr><td id="17:00:00" align="center" style="border-radius: 5px;border-style: solid;">17:00</td><td id="td"></td></tr>
<tr><td id="17:30:00" align="center" style="border-radius: 5px;border-style: solid;">17:30</td><td id="td"></td></tr>
<tr><td id="18:00:00" align="center" style="border-radius: 5px;border-style: solid;">18:00</td><td id="td"></td></tr>
<tr><td id="18:30:00" align="center" style="border-radius: 5px;border-style: solid;">18:30</td><td id="td"></td></tr>
<tr><td id="19:00:00" align="center" style="border-radius: 5px;border-style: solid;">19:00</td><td id="td"></td></tr>
<tr><td id="19:30:00" align="center" style="border-radius: 5px;border-style: solid;">19:30</td><td id="td"></td></tr>
<tr><td id="20:00:00" align="center" style="border-radius: 5px;border-style: solid;">20:00</td><td id="td"></td></tr>
</table>
<table></table>
<?php
$name=$_SESSION['usr_name'];
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$dbname="testmra"; // Database name
// Create connection
$conn = mysqli_connect($host, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
else{
}
$res = mysqli_query($conn,"SELECT emailid FROM users WHERE username='$name'");
while($row=mysqli_fetch_assoc($res))
{
$rows = $row['emailid'];
}
?>
<div id="plan" class="pop-up" style="display :none ">
<span class="close">Close</span>
<form align="center" method="post" id="inform">
<h1 align="center">Meeting Details</h1>
<table>
<tr><td align="right"><b>Room : </td><td><input type="text" name="txtrname" value="Karma" readonly></td></tr>
<tr><td align="right"><b>Name :</td><td><input type="text" name="txtname" readonly value="<?php echo ucwords($_SESSION['usr_name']); ?>" ></td></tr>
<tr><td align="right"><b>Email Id :</td><td><input type="text" name="txtemail" readonly value="<?php echo $rows ?>"></td></tr>
<tr><td align="right"><b>Purpose of Meeting :</td><td> <input id="meeting" type="text" name="txtpurpose"><span class="meeting-error">Enter the purpose of meeting</span></td></tr>
<tr><td align="right"><b>No. of Attendee :</td><td><select name="attendee"><option value="2">2</option><option value="3">3</option></select></td></tr>
<tr><td align="right"><b>Date :</td><td> <input class="date" type="text" name="txtdate" readonly value="yyyy/mm/dd"></td></tr>
<tr><td align="right"><b>Time : </td><td>Start Time <select class="start-time" name="btime">
<option value="08:00:00">08:00</option>
<option value="08:30:00">08:30</option>
<option value="09:00:00">09:00</option>
<option value="09:30:00">09:30</option>
<option value="10:00:00">10:00</option>
<option value="10:30:00">10:30</option>
<option value="11:00:00">11:00</option>
<option value="11:30:00">11:30</option>
<option value="12:00:00">12:00</option>
<option value="12:30:00">12:30</option>
<option value="13:00:00">13:00</option>
<option value="13:30:00">13:30</option>
<option value="14:00:00">14:00</option>
<option value="14:30:00">14:30</option>
<option value="15:00:00">15:00</option>
<option value="15:30:00">15:30</option>
<option value="16:00:00">16:00</option>
<option value="16:30:00">16:30</option>
<option value="17:00:00">17:00</option>
<option value="17:30:00">17:30</option>
<option value="18:00:00">18:00</option>
<option value="18:30:00">18:30</option>
<option value="19:00:00">19:00</option>
<option value="19:30:00">19:30</option>
<option value="20:00:00" disabled>20:00</option>
</select>
- End Time <select class="end-time" name="etime">
<option value="08:00:00">08:00</option>
<option value="08:30:00">08:30</option>
<option value="09:00:00">09:00</option>
<option value="09:30:00">09:30</option>
<option value="10:00:00">10:00</option>
<option value="10:30:00">10:30</option>
<option value="11:00:00">11:00</option>
<option value="11:30:00">11:30</option>
<option value="12:00:00">12:00</option>
<option value="12:30:00">12:30</option>
<option value="13:00:00">13:00</option>
<option value="13:30:00">13:30</option>
<option value="14:00:00">14:00</option>
<option value="14:30:00">14:30</option>
<option value="15:00:00">15:00</option>
<option value="15:30:00">15:30</option>
<option value="16:00:00">16:00</option>
<option value="16:30:00">16:30</option>
<option value="17:00:00">17:00</option>
<option value="17:30:00">17:30</option>
<option value="18:00:00">18:00</option>
<option value="18:30:00">18:30</option>
<option value="19:00:00">19:00</option>
<option value="19:30:00">19:30</option>
<option value="20:00:00">20:00</option>
</select>
</td></tr>
<tr></tr>
<tr><td></td><td><input class="submit-button" type="submit" value="Submit">
<!--<input class="reset-button" type="reset" value="Reset">--></td></tr>
</table>
</form>
</div>
<div id="plan-bg" class="pop-up"></div>
<div id="alert-msg" class="pop-up"><span class="close" onclick="window.location.reload();">Close</span><p>The selected time slot is booked.</p></div>
<div id="time-slot-msg" class="pop-up"><span class="close">Close</span><p>This time slot is already booked.</p></div>
<div id="datepicker"></div>
<?php
$user = ucwords($_SESSION['usr_name']);
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$result = mysqli_query($conn,"SELECT * FROM karmadetails WHERE name='$user' AND date='$selecteddate' AND (status_id=1 OR status_id=2)");
echo "<table border='1' style='border:black;'>
<tr>
<th id='td'>User Id</th>
<th id='td'>Purpose</th>
<th id='td'>Date</th>
<th id='td'>Start Time</th>
<th id='td'>End Time</th>
<th id='td'>Cancel Booking</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td align='center' id='td'>" . $row['id'] . </td>";
echo "<td align='center' id='td'>" . $row['purpose'] . "</td>";
echo "<td align='center' id='td'>" . $row['date'] . "</td>";
echo "<td align='center' id='td'>" . $row['starttime'] . "</td>";
echo "<td align='center' id='td'>" . $row['endtime'] . "</td>";
echo '<td align="center" id="td"> <a href="cancelkarma.php?userid='. $row['id'].'" style="color:red" onclick="return confirm(\'Are you sure you want to cancel the booking ?\')" >Cancel</a> </td>';
echo "</tr>";
}
echo "</table>";
mysqli_close($conn);
?>
<script type="text/javascript">
var jqueryarray = [];
jqueryarray = <?php echo json_encode($starttime); ?>;
var statusarray=[];
statusarray = <?php echo json_encode($status); ?>;
var namearray=[];
namearray = <?php echo json_encode($name); ?>;
var countarray = [];
countarray = <?php echo json_encode($testing); ?>;
var arr = [];
for(i = 0; i < <?php echo $i; ?>; i++)
{
arr[i] = jqueryarray[i];
}
var brr = [];
for(i = 0; i < <?php echo $i; ?>; i++)
{
brr[i] = statusarray[i];
}
var crr=[];
for(i=0; i< <?php echo $i; ?>; i++)
{
crr[i] = namearray[i];
}
var drr=[];
for(i=0; i< <?php echo $i; ?>; i++)
{
drr[i] = countarray[i];
}
var j = 0;
var k=1;
var currentrow;
$('.meeting-timetable tr').each(function() {
if(arr[j] == $(this).find('td').attr('id'))
{
if(brr[j]==1)
{
currentrow=$(this);
for(k=1;k<=parseInt(countarray[j]);k++)
{
currentrow.find('td').next().css('background-color','orange').addClass('active').attr("title",namearray[j]);
currentrow=currentrow.next('tr');
}
}
if(brr[j]==2)
{
currentrow=$(this);
for(k=1;k<=parseInt(countarray[j]);k++)
{
currentrow.find('td').next().css('background-color','red').addClass('active').attr("title",namearray[j]);
currentrow=currentrow.next('tr');
}
}
if(brr[j]==3)
{
$(this).find('td').next().css('background-color','');
}
if(brr[j]==4)
{
$(this).find('td').next().css('background-color','');
}
j++;
}
});
</script>
</body>
</html>
insert.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="testmra"; // Database name
// Connect to server and select databse.
$conn=mysqli_connect($host,$username,$password) or die("cannot connect");
mysqli_select_db($conn,$db_name);
$room = mysqli_real_escape_string($conn, $_POST['txtrname']);
$name = mysqli_real_escape_string($conn, $_POST['txtname']);
$email = mysqli_real_escape_string($conn, $_POST['txtemail']);
$purpose = mysqli_real_escape_string($conn, $_POST['txtpurpose']);
$attendee = mysqli_real_escape_string($conn, $_POST['attendee']);
$date = mysqli_real_escape_string($conn, $_POST['txtdate']);
$btime = mysqli_real_escape_string($conn, $_POST['btime']);
$etime = mysqli_real_escape_string($conn, $_POST['etime']);
$sql="INSERT INTO karmadetails (room,name,purpose,attendee,date,starttime,endtime,status_id)VALUES('$room','$name','$purpose','$attendee','$date','$btime','$etime','2')";
$to = '$email';
$subject = "Your Booking is Done!!!";
$message = "<p>Hello $name . You've received this E-Mail because you have booked room $room from Timings $btime to $etime on Date $date.";
$from = "kansaramankit#gmail.com";
$headers = "From: $from";
mail($to,$subject,$message,$headers);
if (mysqli_query($conn,$sql))
{
echo "Record added";
}
else
{
die('Error: ' . mysqli_error());
}
?>

How to update and delete data from table?

I'm new to codeigniter and I want to update and delete a data from the table. Can someone help solve this?I've tried other options but wasn't successful.
Here's my view:
<script>
function show_confirm(act) {
if (act == "edit")
var r = confirm("Do you really want to edit this?");
else
var r = confirm("Do you really want to delete this?");
if (r==true){
window.location="<?php echo base_url(); ?>site/"+act;
}
}
</script>
<style>
select{
position: absolute;
left: 35%;
height: 5%;
width: 33%;
border-radius: 5px;
font-family: arial;
}
table {
background: #333;
width: 700px;
border-collapse: 1px;
font-family: arial;
position: absolute;
top: 33%;
left: 25%;
color: #777;
}
th {
padding-top: 10px;
padding-bottom: 10px;
}
td {
background: #999;
padding: 10px;
text-align: center;
font-size: 12px;
}
.data {
color: #555;
}
.data:hover {
background: #FFF;
}
#action {
font-weight: bold;
color: #444;
text-decoration: none;
}
#action:hover {
color: #FFF;
}
</style>
</head>
<body>
<header>
<div class="menu">
<h1 class="sis">SIS</h1>
<p class="welcome">Welcome!&nbsp &nbsp| &nbsp</p>
<p class="logout">Logout</p>
<nav class="navi">
<ul>
<li>Home</li>
<li>About
<ul class="about">
<li>Vision/Mission</li>
<li>History</li>
</ul>
</li>
<li>Admission</li>
<li>Calendar</li>
<li>Students
<ul class="stud">
<li>Grade I</li>
<li>Grade II</li>
<li>Grade III</li>
<li>Grade IV</li>
<li>Grade V</li>
<li>Grade VI</li>
<li>Academic Records</li>
</ul>
</li>
<li>Teachers
<ul class="teach">
<li>Gradesheet</li>
<li>Lesson Plan</li>
</ul>
</li>
<li>Contact Us</li>
</ul>
</nav>
</div>
</header>
<header>
<div class="container">
<select>
<option placeholder="section"></option>
<option value="section">Section I</option>
<option value="section">Section II</option>
<option value="section">Section III</option>
<option value="section">Section IV</option>
<option value="section">Section V</option>
<option value="section">Section VI</option>
</select>
<table>
<tr id="field">
<th scope="col"> ID </th>
<th scope="col"> First Name </th>
<th scope="col"> Last Name </th>
<th scope="col"> Contact # </th>
<th scope="col"> Address </th>
<th scope="col" colspan="2"> Action </th>
</tr>
<?php foreach ($user_list as $u_key) { ?>
<tr class="data" >
<td><?php echo $u_key->ID; ?></td>
<td><?php echo $u_key->FNAME; ?></td>
<td><?php echo $u_key->LNAME; ?></td>
<td><?php echo $u_key->CONTACT; ?></td>
<td><?php echo $u_key->ADDRESS; ?></td>
<td width="40" align="left"><a id="action" href="#" onClick="show_confirm('edit',<?php echo $u_key->ID; ?>)">Edit</a></td>
<td width="40" align="left"><a id="action" href="#" onClick="show_confirm('delete',<?php echo $u_key->ID; ?>)">Delete</a></td>
</tr>
<?php } ?>
</table>
</div>
</header>
</body>
</html>
My Controller:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Site extends CI_Controller {
public function index(){
$this->home();
$this->load->helper('url');
}
public function home(){
$data['title'] = "Home";
$this->load->view("view_main");
}
function vismis(){
$data['title'] = "Vismis";
$this->load->view("view_vismis");
}
function history(){
$data['title'] = "History";
$this->load->view("view_history");
}
function admission(){
$data['title'] = "Admission";
$this->load->view("view_admission");
}
function contact(){
$data['title'] = "Contact";
$this->load->view("view_contact");
}
function calendar($year = null, $month = null){
$data['title'] = "Calendar";
if(!$year) {
$year = date('Y');
}
if(!$month) {
$month = date('m');
}
$this->load->model('cal_model');
if ($day = $this->input->post('day')) {
$this->cal_model->add_cal_data(
"$year-$month-$day",
$this->input->post('data')
);
}
$data['calendar'] = $this->cal_model->generate($year, $month);
$this->load->view("view_calendar",$data);
}
public function gradeI(){
$this->load->model('stud_model');
$data['title'] = "gradeI";
$data['user_list'] = $this->stud_model->get_users();
$this->load->view('view_students', $data);
}
function add_stud(){
$this->load->model('stud_model');
$udata['fname'] = $this->input->post('fname');
$udata['lname'] = $this->input->post('lname');
$udata['contact'] = $this->input->post('contact');
$udata['address'] = $this->input->post('address');
$res = $this->stud_model->insert_user_to_db($udata);
if ($res){
header('location:'.base_url()."site/gradeI");
}
}
public function edit() {
$this->load->model('stud_model');
$data['title'] = "edit";
$id = $this->uri->segment(3);
$data['user'] = $this->stud_model->getById($id);
$this->load->view('view_editstud', $data);
}
public function update_stud() {
$mdata['fname'] = $_POST['fname'];
$mdata['lname'] = $_POST['lname'];
$mdata['contact'] = $_POST['contact'];
$mdata['address'] = $_POST['address'];
$res = $this->stud_model->update_info($mdata, $_POST['id']);
if($res) {
header('location'.base_url()."site/gradeI");
}
}
public function delete() {
$this->load->model('stud_model');
$id = $this->uri->segment(3);
$res = $this->stud_model->del_stud($id);
if ($res) {
header('location:'.base_url()."site/gradeI");
}
}
function gradeII(){
$this->load->model('stud_model');
$data['title'] = "gradeII";
$data['user_list'] = $this->stud_model->get_users();
$this->load->view('view_stud_two',$data);
}
function gradeIII(){
$data['title'] = "gradeIII";
$this->load->view('view_students');
}
function gradeIV(){
$data['title'] = "gradeIV";
$this->load->view('view_students');
}
function gradeV(){
$data['title'] = "gradeV";
$this->load->view('view_students');
}
function gradeVI(){
$data['title'] = "gradeVI";
$this->load->view('view_students');
}
function acadrecs(){
$data['title'] = "acadrecs";
$this->load->view('view_acadrecs');
}
public function enroll(){
$data['title'] = "enroll";
$this->load->view('view_enroll');
}
}
and my Model:
<?php
class Stud_model extends CI_Model
{
function __construct()
{
parent::__construct();
$this->load->database("sis");
}
public function get_users() {
$query = $this->db->get('students');
return $query->result();
}
public function insert_user_to_db($udata) {
return $this->db->insert('students', $udata);
}
public function getById($id) {
$query = $this->db->get_where('students', array('id'=>$id));
return $query->row_array();
}
public function update_info($data, $id) {
$this->db->where('ID', $id);
return $this->db->update('students', $data);
}
public function del_stud($id) {
$this->db->where('ID', $id);
return $this->db->delete('students');
}
}
nothing happens when I click on delete.
On the edit link...
The view:
<form method="post" action="<?php echo base_url();?>site/update_stud">
<?php extract($user); ?>
<table>
<tr>
<th scope="row">Enter your first name</th>
<td><input type="text" name="fname" size="20" value="<?php echo $fname; ?>" /></td>
</tr>
<tr>
<th scope="row">Enter your last name</th>
<td><input type="text" name="lname" size="20" value="<?php echo $lname; ?>" /></td>
</tr>
<tr>
<th scope="row">Enter your contact number</th>
<td><input type="text" name="contact" size="20" value="<?php echo $contact; ?>" /></td>
</tr>
<tr>
<th scope="row">Enter your address</th>
<td><textarea name="address" rows="5" cols="20"><?php echo $address; ?> </textarea></td>
</tr>
<tr>
<td><input type="hidden" name="id" value="<?php echo $id; ?>" />
<input type="submit" name="submit" value="Update" /></td>
</tr>
</table>
This error will show up:
Enter your first name A PHP Error was encountered
Severity: Notice
Message: Undefined variable: fname
Filename: views/view_editstud.php
Line Number: 60
" />
and so on with other input types.
Firstly, neither of the javascript confirm links will work because you're not actually passing the id through with the act:
<script>
function show_confirm(act, id) {
if (act == "edit") {
var r = confirm("Do you really want to edit this?");
} else {
var r = confirm("Do you really want to delete this?");
}
//Just FYI, the above can be written like this:
//var r = (act == 'edit') ? confirm("Do you really want to edit this?") : confirm("Do you really want to delete this?");
//or even
//var r = confirm("Do you really want to "+act+" this?");
if (r == true) {
window.location = "<?php echo base_url(); ?>site/" + act + "/" + id;
}
//Another FYI, the above could be written like this:
// !r || window.location = "<?php echo base_url(); ?>site/" + act + "/" + id;
}
</script>
Obviously, you can delete the comments.
Secondly, you don't need to use $this->uri->segment() to pass params to a controller method as codeigniter will automatically pass them (Unless you're using URI ROUTING), you can instead:
public function delete($id)
{
$this->load->model('stud_model');
$res = $this->stud_model->del_stud($id);
//There is no point in this if statement as it will just display a
//blank page if $res evaluates to FALSE
if ($res) {
//As you aren't using a variable below you might as well use single quotes
//Also, instead of using header('Location') you should use redirect() with codeiginiter
redirect('site/gradeI');
}
}
Lastly, you should really think about validation e.g. codeigniters built in Form_validation Library.
Hope this helps!

Categories