multiple search field on form using php and mysql - javascript

I stuck with this problem for a few days already.
The logic of the system i want to develop is here
This is the code for the image
<?php
session_start();
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <link rel="stylesheet" type="text/css" href="style.css"/> -->
</head>
<body>
<form action="process/searchprocess.php" method="GET">
<table width="100%">
<tr>
<th>
Client Ic<br><input type="text" name="client_name" />
</th>
<th>
Client Ic<br><input type="text" name="client_ic" />
</th>
<th>
Client Address <br><input type="text" name="client_add" />
</th>
</tr>
</table>
<table width="100%">
<tr>
<th>
<br><input type="submit" value="Search" align="center" />
</th>
</tr>
</table>
</form>
</body>
</html>
This is my process code
<?php
session_start();
mysql_connect("localhost", "root", "") or die("Error connecting to database: ".mysql_error());
mysql_select_db("waveevo") or die(mysql_error());
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Search results</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- <link rel="stylesheet" type="text/css" href="style.css"/> -->
<style>
table tr:nth-child(even) {
background-color: #eee;
}
table tr:nth-child(odd) {
background-color:#fff;
}
table th {
background-color: black;
color: white;
}
</style>
</head>
<body>
<?
php
$query = $_GET['client_name'];
$query2 = $_GET['client_ic'];
$query3 = $_GET['client_add'];
if ($query == null && $query2 == null && $query3 == null)
{
echo "Please at least insert one the value";
}
else
{
$query = htmlspecialchars($query);
$query2 = htmlspecialchars($query2);
$query3 = htmlspecialchars($query3);
$query = mysql_real_escape_string($query);
$query2 = mysql_real_escape_string($query2);
$query3 = mysql_real_escape_string($query3);
$raw_results = mysql_query("SELECT * FROM client WHERE ('client_name' LIKE '%".$query."%') OR ('client_ic' LIKE '%".$query2."%') OR ('client_add_1' && ' ' && 'client_add_2' && ' ' && 'client_add_3' && ' ' && 'client_add_4' LIKE '%".$query3."%')") or die(mysql_error());;
if(mysql_num_rows($raw_results) > null){ // if one or more rows are returned do following
while($results = mysql_fetch_array($raw_results)){
?>
<table width="100%">
<tr>
<th>ID</th>
<th>Name</th>
<th>IC</th>
<th>Mobile</th>
<th>Address</th>
<th>Marital Status</th>
<th>Race</th>
<th>Asset Type</th>
<th>Bank</th>
<th>Amount</th>
<th>Nationality</th>
<th>Limit</th>
</tr>
<tr>
<td><?php echo $results["client_id"]; ?></td>
<td><?php echo $results["client_name"]; ?></td>
<td><?php echo $results["client_ic"]; ?></td>
<td><br><?php echo $results["client_mobile_1"]."<br>".$results["client_mobile_2"]."<br>".$results["client_mobile_3"]; ?></td>
<td><?php echo $results["client_add_1"]."<br>".$results["client_add_2"]."<br>".$results["client_add_3"]."<br>".$results["client_city"]."<br>".$results["client_postcode"]; ?></td>
<td><?php echo $results["client_marital_status_id"]; ?></td>
<td><?php echo $results["client_race_id"]; ?></td>
<td><?php echo $results["client_asset_type_id"]; ?></td>
<td><?php echo $results["client_bank_id"]; ?></td>
<td><?php echo $results["amount"]; ?></td>
<td><?php echo $results["client_nationality_id"]; ?></td>
<td><?php echo $results["client_limit"]; ?></td>
</tr>
</table>
<?php
}
}
else{ // if there is no matching rows do following
echo "No results";
}
}
?>
</body>
So I try enter value for client ic, for example 1234, there is no data in the database that match the value that i entered just now but the result still show have, can i know why because i already don't have way to solve this

Thatś because when you use wildcards LIKE '%".$query."%' if your variable $query is empty you are just getting all because you compare with everything LIKE '%%'.
You need to change this sentence:
$raw_results = mysql_query("SELECT * FROM client WHERE ('client_name' LIKE '%".$query."%') OR ('client_ic' LIKE '%".$query2."%') OR ('client_add_1' && ' ' && 'client_add_2' && ' ' && 'client_add_3' && ' ' && 'client_add_4' LIKE '%".$query3."%')") or die(mysql_error());;
whith something like this
$sql_query="SELECT * FROM client WHERE ";
$other=false;
if ($query != null and $query!="") {
$sql_query=$sql_query."('client_name' LIKE '%".$query."%')";
$other=true;
}
if ($query2 != null and $query2!="") {
if ($other) {
$sql_query=$sql_query." OR ";
}
$sql_query=$sql_query."('client_ic' LIKE '%".$query2."%')";
$other=true;
}
if ($query3 != null and $query3!="") {
if ($other) {
$sql_query=$sql_query." OR ";
}
$sql_query=$sql_query."('client_add_1' && ' ' && 'client_add_2' && ' ' && 'client_add_3' && ' ' && 'client_add_4' LIKE '%".$query3."%')";
$other=true;
}
if ($other) {
$raw_results = mysql_query($sql_query) or die(mysql_error());
}

Related

How do i put a link in a table

I have a table on my website, which gets data from a database, in the table I have delete buttons on a row, I have just made the table searchable with jQuery, but now I can't figure out how to keep the delete buttons.
index.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta charset="utf-8">
<meta name="description" content="Inventar">
<meta name="author" content="Martin Eide Bjørndal">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link rel="stylesheet" href="/src/css/style.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"></script>
</head>
<body>
<button class="back" onclick="window.location='../'">
<img src="/src/icons/back.png">
</button> <!-- Tilbake knapp -->
<button class="ny_inventar" onclick="window.location='/admin/brukere/ny'">
<img src="/src/icons/add.png">
</button> <!-- Ny Bruker knapp -->
<div class="container-fluid" id="utskjekkcontainer">
<div class="row justify-content-center">
<div class="col-mv-10 bg-light mt-5 rounded p-3">
<h1 class="text-primary p-2">Brukere</h1>
<hr>
<div class="form-inline">
<label for="search" class="font-weight-bold lead text-dark">Søk</label>
<input type="text" name="search" id="search_text" class="form-control form-control-lg rounded-0 border-primary" placeholder="Søk...">
</div>
<hr>
<?php
include "../../src/fn/init.php";
$stmt=$conn->prepare("SELECT * FROM brukere");
$stmt->execute();
$result=$stmt->get_result();
?>
<table class="table table-hover table-light table-striped" id="table_data">
<thead>
<tr>
<th>#</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Utskjekket</th>
<th>Admin</th>
<th>Slett</th>
</tr>
</thead>
<tbody>
<?php while($row=$result->fetch_assoc()){ ?>
<tr>
<td><?php echo $row["id"]; ?></td>
<td><?php echo $row["fornavn"]; ?></td>
<td><?php echo $row["etternavn"]; ?></td>
<td><?php echo $row["utskjekket"]; ?></td>
<td><?php echo $row["is_admin"]; ?></td>
<td>Slett</td>
</tr>
<?php }
$conn->close();
?>
</tbody>
</table>
</div>
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#search_text').keyup(function(){
var search = $(this).val();
$.ajax({
url:'action.php',
method:'post',
data:{query:search},
success:function(response){
$('#table_data').html(response);
}
});
});
});
</script>
</body>
</html>
action.php:
<?php
include "../../src/fn/init.php";
$output = "";
if(isset($_POST["query"])){
$search = $_POST["query"];
$stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
$stmt->bind_param("sss",$search, $search, $search);
} else {
$stmt=$conn->prepare("SELECT * FROM brukere");
};
$stmt->execute();
$result=$stmt->get_result();
if($result->num_rows>0){
$output = "<thead>
<tr>
<th>#</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Utskjekket</th>
<th>Admin</th>
<th>Slett</th>
</tr>
</thead>
<tbody>";
while($row=$result->fetch_assoc()){
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td>".Slett."</td>
</tr>";
};
$output .= "</tbody>";
echo $output;
} else {
echo "<h3>No match found!</h3>";
};
?>
This is the search script, the problem is in the while loop where the link is added, I can't figure out how to make it work.
The a tag is not added as a plain-text to the output string, you need to rewrite that line, concatenate strings parts to variables parts correctly.
Try replacing:
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td>".Slett."</td>
</tr>";
with:
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td><a href='delete.php?id=".urlencode($row['id'])."' onclick='return confirm('Er du sikker?');'>Slett</a></td>
</tr>";
To allow PHP to echo the id from the table result you need to just simply do a php echo
Slett
You don't have to url encode at this stage as you are just simply building the href of an a:link
You can use it
<?php
include "../../src/fn/init.php";
$output = "";
if(isset($_POST["query"])){
$search = $_POST["query"];
$stmt = $conn->prepare("SELECT * FROM brukere WHERE fornavn LIKE CONCAT('%',?,'%') OR etternavn LIKE CONCAT('%',?,'%') OR id LIKE CONCAT('%',?,'%')");
$stmt->bind_param("sss",$search, $search, $search);
} else {
$stmt=$conn->prepare("SELECT * FROM brukere");
};
$stmt->execute();
$result=$stmt->get_result();
if($result->num_rows>0){
$output = "<thead>
<tr>
<th>#</th>
<th>Fornavn</th>
<th>Etternavn</th>
<th>Utskjekket</th>
<th>Admin</th>
<th>Slett</th>
</tr>
</thead>
<tbody>";
while($row=$result->fetch_assoc()){
$output .= "
<tr>
<td>".$row["id"]."</td>
<td>".$row["fornavn"]."</td>
<td>".$row["etternavn"]."</td>
<td>".$row["utskjekket"]."</td>
<td>".$row["is_admin"]."</td>
<td>Slett </td>
</tr>";
};
$output .= "</tbody>";
echo $output;
} else {
echo "<h3>No match found!</h3>";
};

Edit/Update data in php through AJAX

In my index.php I am fetching data from the database. I put an edit button on that and I have used a datatable to view data information in this form. I have four field: Name, Age, Email, Update through mysqli_fetch_array I have fetched the data.
This is the index.php file:
<?php
//including the database connection file
include_once("config.php");
//fetching data in descending order (lastest entry first)
//$result = mysql_query("SELECT * FROM users ORDER BY id DESC"); // mysql_query is deprecated
// using mysqli_query instead
?>
<html>
<head>
<title>Homepage</title>
<link rel="stylesheet" href="DataTables/datatables.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/dataTables.bootstrap.css" type="text/css">
<link rel="stylesheet" href="DataTables/DataTables/css/jquery.dataTables.css" type="text/css">
<script src="DataTables/datatables.js"></script>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/datatable.js"></script>
<script src="DataTables/DataTables/js/dataTables.bootstrap.js"></script>
<script src="DataTables/DataTables/js/jquery.dataTables.js"></script>
</head>
<body>
Add New Data<br/><br/>
<table id="datatable" class="display" width='100%' border=0>
<thead>
<tr bgcolor='#CCCCCC'>
<td>Name</td>
<td>Age</td>
<td>Email</td>
<td>Update</td>
</tr>
</thead>
<?php
//while($res = mysql_fetch_array($result)) { // mysql_fetch_array is deprecated, we need to use mysqli_fetch_array
//$action=$_POST["action"];
//if($action=='showroom')
{
$result = mysqli_query($mysqli, "SELECT * FROM users ORDER BY id DESC");
while ($res = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $res['name'] . "</td>";
echo "<td>" . $res['age'] . "</td>";
echo "<td>" . $res['email'] . "</td>";
echo "<td>Edit | Delete</td>";
}
}
?>
</table>
</body>
</html>
This is my edit.php file. First I check empty fields, after that I run updating the table query redirecting to the display page. In our case, it is index.php then getting id from url, selecting data associated with this particular id, fetching data through mysqli_fetch_array .
<?php
// including the database connection file
include_once("config.php");
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if (empty($name) || empty($age) || empty($email)) {
if (empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if (empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if (empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while ($res = mysqli_fetch_array($result)) {
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name; ?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age; ?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email; ?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id']; ?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>
Finally, this is my edit.js file. In this file I try to do edit the form through AJAX, but I can't find where I doing mistakes.
<script>
$(document).ready(function (e) {
$('#update').click(function (event)
{
event.preventDefault();
$.ajax({
data: $('form').serialize(),
url: "edit.php", //php page URL where we post this data to save in database
type: 'POST',
success: function (strMessage) {
$('#message').text("strMessage");
}
})
});
});
</script>
You are doing edit and update on same file so you have to add condition on file. change your code as below:
edit.php
<?php
// including the database connection file
include_once("config.php");
if($_SERVER['REQUEST_METHOD'] == "POST")
{
$id = $_POST['id'];
$name = $_POST['name'];
$age = $_POST['age'];
$email = $_POST['email'];
// checking empty fields
if(empty($name) || empty($age) || empty($email)) {
if(empty($name)) {
echo "<font color='red'>Name field is empty.</font><br/>";
}
if(empty($age)) {
echo "<font color='red'>Age field is empty.</font><br/>";
}
if(empty($email)) {
echo "<font color='red'>Email field is empty.</font><br/>";
}
} else {
//updating the table
$result = mysqli_query($mysqli, "UPDATE users SET name='$name',age='$age',email='$email' WHERE id=$id");
//redirectig to the display page. In our case, it is index.php
header("Location: index.php");
}
}
//getting id from url
$id = $_GET['id'];
//selecting data associated with this particular id
$result = mysqli_query($mysqli, "SELECT * FROM users WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$name = $res['name'];
$age = $res['age'];
$email = $res['email'];
}
?>
<html>
<head>
<title>Edit Data</title>
<script src="style/jquery-3.2.1.js"></script>
<script src="style/insert.js"></script>
<script src="style/view.js"></script>
<script src="style/edit.js"></script>
</head>
<body>
Home
<br/><br/>
<p id="message"></p>
<form name="form1" method="POST" action="edit.php">
<table border="0">
<tr>
<td>Name</td>
<td><input type="text" name="name" value="<?php echo $name;?>"></td>
</tr>
<tr>
<td>Age</td>
<td><input type="text" name="age" value="<?php echo $age;?>"></td>
</tr>
<tr>
<td>Email</td>
<td><input type="text" name="email" value="<?php echo $email;?>"></td>
</tr>
<tr>
<td><input type="hidden" name="id" value=<?php echo $_GET['id'];?>></td>
<td><input type="submit" name="update" id="update" value="Update"></td>
</tr>
</table>
</form>
</body>
</html>

show mysql results in php just if a row=with

I have this code and i want to show the results just if the row "SOLVED" = 1 . If i put the statement where solved='1' my filters doesn't work anymore are show all the results .
I am new in php and a little help will pe appreciated .
<?php
###########################################################
/*
GuestBook Script
Copyright (C) 2012 StivaSoft ltd. All rights Reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/gpl-3.0.html.
For further information visit:
http://www.phpjabbers.com/
info#phpjabbers.com
Version: 1.0
Released: 2012-03-18
*/
###########################################################
error_reporting(1);
include("config.php");
$SETTINGS["data_table"]='problems'; // this is the default database name that we used
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.0/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"></script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<style type="text/css">
<!--
#import url("style.css");
-->
</style>
<form id="form1" name="form1" method="post" action="list-problems-active.php">
<label for="from">From</label>
<input name="from" type="text" id="from" size="10" value="<?php echo $_REQUEST["date"]; ?>" />
<label for="to">to</label>
<input name="to" type="text" id="to" size="10" value="<?php echo $_REQUEST["to"]; ?>"/>
<label>Name or Email:</label>
<input type="text" name="string" id="string" value="<?php echo stripcslashes($_REQUEST["string"]); ?>" />
<label>Location</label>
<select name="location">
<option value="">--</option>
<?php
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." GROUP BY location ORDER BY location ";
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
while ($row = mysql_fetch_assoc($sql_result)) {
echo "<option value='".$row["location"]."'".($row["location"]==$_REQUEST["location"] ? " selected" : "").">".$row["location"]."</option>";
}
?>
</select>
<input type="submit" name="button" id="button" value="Filter" />
</label>
<a href="list-problems-active.php">
reset</a>
</form>
<br /><br />
<table id="newspaper-b" summary="2007 Major IT Companies' Profit">
<thead>
<tr>
<th scope="col">Id</th>
<th scope="col">Location</th>
<th scope="col">Manager</th>
<th scope="col">Problem Info</th>
<th scope="col">Date</th>
<th scope="col">Author</th>
<th scope="col">Solved</th>
</tr>
</thead>
<?php
if ($_REQUEST["string"]<>'') {
$search_string = " AND (location LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%' OR problem LIKE '%".mysql_real_escape_string($_REQUEST["string"])."%')";
}
if ($_REQUEST["location"]<>'') {
$search_city = " AND location='".mysql_real_escape_string($_REQUEST["location"])."'";
}
if ($_REQUEST["from"]<>'' and $_REQUEST["to"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE from_date >= '".mysql_real_escape_string($_REQUEST["from"])."' AND to_date <= '".mysql_real_escape_string($_REQUEST["to"])."'".$search_string.$search_city;
} else if ($_REQUEST["from"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE from_date >= '".mysql_real_escape_string($_REQUEST["from"])."'".$search_string.$search_city;
} else if ($_REQUEST["to"]<>'') {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE to_date <= '".mysql_real_escape_string($_REQUEST["to"])."'".$search_string.$search_city;
} else {
$sql = "SELECT * FROM ".$SETTINGS["data_table"]." WHERE id>0".$search_string.$search_city;
}
//$sql_result = mysql_query ("select Id, location, manager, problem, date, author from problems where solved=0 ORDER BY date desc") or die ('request "Could not execute SQL query" '.$sql);
$sql_result = mysql_query ($sql, $connection ) or die ('request "Could not execute SQL query" '.$sql);
//$sql_result = mysql_query("SELECT * FROM problems WHERE solved='0'");
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
?>
<tr>
<td><?php echo $row["Id"]; ?></td>
<td><?php echo $row["location"]; ?></td>
<td><?php echo $row["manager"]; ?></td>
<td><?php echo $row["problem"]; ?></td>
<td><?php echo $row["date"]; ?></td>
<td><?php echo $row["author"]; ?></td>
<td><?php echo "<a href='set-as-solved.php?Id=" . $row['Id'] . "'> <img src='check.png" . $last_file[0] . "' alt='error'> " ?></td>
</tr>
<?php
}
} else {
?>
<tr><td colspan="5">No results found.</td>
<?php
}
?>
</table>
<script>
$(function() {
var dates = $( "#from, #to" ).datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 2,
dateFormat: 'yy-mm-dd',
onSelect: function( selectedDate ) {
var option = this.id == "from" ? "minDate" : "maxDate",
instance = $( this ).data( "datepicker" ),
date = $.datepicker.parseDate(
instance.settings.dateFormat ||
$.datepicker._defaults.dateFormat,
selectedDate, instance.settings );
dates.not( this ).datepicker( "option", option, date );
}
});
});
</script>
</body>
</html>

Having trouble with code - Deleting records from database - JS / PHP

I'm having some trouble with this code pinpointing exactly where the problems coming from, I'm not sure if theres a problem with the javascript but when I go to select a record from select.php it just ends up stalling.. (nothing happens ;/)
confirmDelete.js
function fnConfirm(delUrl) {
if (confirm("Are you sure you want to delete this record?")) {
window.location = delUrl;
}
var linkDel = document.getElementById("linkDelete");
linkDel.onclick= fnConfirm;
select.php
<?php header("Cache-Control:no-cache"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Delete Cabin -AdminPanel</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css" />
</head>
<body>
<script src="confirmDelete.js"></script>
<h2>Select from the cabins listed below to delete:</h2>
<?php
//connect to server and database
include 'sqldb_connect.inc.php';
//set up query
$query = "SELECT * FROM tblCabins";
//execute query
$result = mysql_query($query);
if(!$result)
{
mysql_close();
exit("Error retrieving cabins from database");
}
//get the number of rows in the cabins table and store in a variable
if(mysql_num_rows($result) <1)
{
mysql_close();
exit("No cabin entries found");
}
//start table
?>
<!--.......................................................................-->
<table>
<tr>
<th>cabinID</th>
<th>Cabin Type</th>
<th>Cabin Description</th>
<th>Price per night</th>
<th>Price per week</th>
<th>Photo</th>
<th> </th>
</tr>
<!--.......................................................................-->
<?php
//fetch the next row (or record) of the result set until there are no more left
while($row = mysql_fetch_array($result))
{
//store the results in variables
$cabinID = $row['cabinID'];
$cabintype = $row['cabinType'];
$cabindesc = $row['cabinDescription'];
$pricepern = $row['pricePerNight'];
$priceperw = $row['pricePerWeek'];
$photo = $row['PHOTO'];
?>
<!--.......................................................................-->
<tr>
<td><?= $cabinID; ?></td>
<td><?= $cabintype; ?></td>
<td><?= $cabindesc; ?></td>
<td><?= $pricepern; ?></td>
<td><?= $priceperw; ?></td>
<td><?= $photo; ?></td>
<td><a id="linkDelete" href="javascript:fnConfirm('cabinDelete_process.php?cabinID=<?= "$cabinID"; ?>')">Delete</a></td>
</tr>
<!--.................................................................................-->
<?php
}
mysql_close();
?>
<!--.................................................................................-->
</table>
</body>
</html>
process.php
<?php header("Cache-Control:no-cache"); ?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>deleteCabinProcess - adminPanel</title>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<?php
//this page will delete the cabin
//selected from the previous page
//read cabinID passed to this page
$cabinID = $_GET['cabinID'];
//connect to server and database
include 'sqldb_connect.inc.php';
//set up query
$query = "DELETE FROM tblCabins WHERE cabinID = '$cabinID'";
//execute query
$result = mysql_query($query);
if(!$result)
{
mysql_close();
exit("Error deleting Cabin from the database");
}
mysql_close();
exit ("Successfully deleted the record from the database ");
?>
</body>
</html>
If anyone can see any problems it'd be greatly appreciated.. Brb need to go outside and adjust my eyes!

PHP - Submit form using Get method.

I'm using Get method to add data that has been entered by user to the event table in database
as you can see I'm using the get method to see if the user has posted and then run the code
but the if statement does not run and I can't find out where is the problem.
Any help would be useful
Thank you very much
if(isset($_GET['add']))
{
$title=$_POST['txttitle'];
$detail=$_POST['txtdetail'];
$eventdate=$month."/".$day."/".$year;
$sqlinsert="INSERT INTO book (title, detail, eventdat, dateadded) VALUES ('{$title}', '{$detail}', '{$eventdate}',now())";
$result = mysql_query($sqlinsert, $connect);
if($result)
{
echo"date has been added";
}
else
{
echo "ops there was problem ";
}
}
this is the full Code
event.php
<?php
include_once('db_connection.php');
$sqlinsert="";
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function goLastMonth(month, year)
{
if(month==1)
{
--year
month= 13;
}
--month
var monthstring=""+month+"";
var monthlength= monthstring.length;
if(monthlength<= 1)
{
monthstring="0"+monthstring;
}
document.location.href="<?php $_SERVER['PHP_SELF'];?> ?month="+monthstring+"&year="+year;
}
function goNextMonth(month , year)
{
if(month==12)
{
++year
month= 0;
}
++month
var monthstring=""+month+"";
var monthlength= monthstring.length;
if(monthlength<= 1)
{
monthstring="0"+monthstring;
}
document.location.href="<?php $_SERVER['PHP_SELF'];?> ?month="+monthstring+"&year="+year;
}
</script>
</head>
<body>
<?php
if(isset($_GET['day']))
{
$day=$_GET['day'];
}
else
{
$day=date('j');
}
if(isset($_GET['month']))
{
$month=$_GET['month'];
}
else
{
$month=date("n");
}
if(isset($_GET['year']))
{
$year=$_GET['year'];
}
else
{
$year=date("Y");
}
$t=date('H:i');
//$day=date('j');
//$month=date("n");
//$year=date("Y");
$time=$day.",".$month.",".$year;
$currenttimestamp= strtotime("$year-$month-$day");
$monthname=date("F",$currenttimestamp );
$numdays= date("t",$currenttimestamp);
if(isset($_GET['add']))
{
$title=$_POST['txttitle'];
$detail=$_POST['txtdetail'];
$eventdate=$month."/".$day."/".$year;
$sqlinsert="INSERT INTO book (title, detail, eventdat, dateadded) VALUES ('{$title}', '{$detail}', '{$eventdate}',now())";
$result = mysql_query($sqlinsert, $connect);
if($result)
{
echo"date has been added";
}
else
{
echo "ops there was problem ";
}
}
?>
<?php echo $sqlinsert;?>
<table border="2">
<tr>
<td colspan="5">Month And Year <?php echo $monthname;?></td>
<td ><input style="width:55px" type="button" value="<<" name="previousbutton" onclick="goLastMonth(<?php echo $month. ",".$year;?>)"> </td>
<td> <input style="width:55px" type="button" value=">>" name="nextbutton" onclick="goNextMonth(<?php echo $month. ",".$year;?>)"> </td>
</tr>
<tr>
<td width="50">Sun</td>
<td width="50">Mon</td>
<td width="50">Tue</td>
<td width="50">Wed</td>
<td width="50">Thu</td>
<td width="50">Fri</td>
<td width="50">Sat</td>
</tr>
<?php
$counter="";
echo "<tr >";
for ($i=1;$i< $numdays+1; $i++, $counter++)
{
$timeStamp=strtotime("$year-$month-$i");
if($i==1)
{
$firstDay=date("w", $timeStamp);
for($j=0;$j<$firstDay; $j++, $counter++)
//blank space
{
echo "<td> </td>";
}
}
if($counter %7==0)
{
echo "</tr><tr>";
}
$monthstring=$month;
$monthlength= strlen ($monthstring);
//
$daystring=$i;
$daylength= strlen($daystring);
if($monthlength<=1)
{
$monthstring="0".$monthstring;
}
if($daylength<=1)
{
$daystring="0".$daystring;
}
echo "<td align='center'><a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$daystring."&year=".$year."&v=true'>".$i."</a></td>";
}
echo"</tr>";
?>
</table>
<?php
if(isset($_GET['v']))
{
echo"<a href='".$_SERVER['PHP_SELF']."?month=".$monthstring."&day=".$daystring."&year=".$year."&v=true&f=true'>ADD EVENT</a>";
if(isset($_GET['f']))
{
include("eventform.php");
}
}
?>
</body>
</html>
and this is Event Form
<form name="eventform" name="POST" action="<?php $_SERVER['PHP_SELF'];?>?month=<?php echo $month;?>&day=<?php echo $day;?>&year=<?php echo $year;?>&v=true&&add=true">
<table width="400px">
<tr>
<td width="150">Title</td>
<td width="250"><input type="text" name="txttitle"></td>
</tr>
<tr>
<td width="150">Detail</td>
<td width="250"><textarea name="txtdetail"></textarea></td>
</tr>
<tr>
<td colspan='2' align="center"><input type="submit" name"btnadd" value="Add Event"></td>
</tr>
</table>
</form>
PHP:
if(isset($_GET['btnadd']))
{
$title=$_GET['txttitle'];
$detail=$_GET['txtdetail'];
$eventdate=$month."/".$day."/".$year;
$sqlinsert="INSERT INTO book (title, detail, eventdat, dateadded) VALUES ('{$title}', '{$detail}', '{$eventdate}',now())";
$result = mysql_query($sqlinsert, $connect);
if($result)
{
echo"date has been added";
}
else
{
echo "ops there was problem ";
}
}
And HTML:
<form name="eventform" method="GET" action="<?php $_SERVER['PHP_SELF']; ?>">
<table width="400px">
<tr>
<td width="150">Title</td>
<td width="250"><input type="text" name="txttitle"></td>
</tr>
<tr>
<td width="150">Detail</td>
<td width="250"><textarea name="txtdetail"></textarea></td>
</tr>
<tr>
<td colspan='2' align="center"><input type="submit" name"btnadd" value="Add Event"></td>
</tr>
</table>
</form>
method="GET" automatically adds the vars to the URL, you do not need to add them in the action.
There are various errors in your code, but the main is that you are setting <form name="POST">. I believe that you want to set <form method="POST">.
first of all, if you go for method GET.. any user by just refreshing the page after sending, it would bucle your action, cause PHP will check for the url form if it has a GET method form.
also, your PHP code seems to be a bit wrong..
if(isset($_GET['add']))
{
$title=$_POST['txttitle'];
$detail=$_POST['txtdetail'];
$eventdate=$month."/".$day."/".$year;
$sqlinsert="INSERT INTO book (title, detail, eventdat, dateadded) VALUES ('{$title}', '{$detail}', '{$eventdate}',now())";
$result = mysql_query($sqlinsert, $connect);
if($result)
{
echo"date has been added";
}
else
{
echo "ops there was problem ";
}
}
your PHP is checking if theres a var, (array="add"), so its checking if there's an input with the name "add" in your form, i think you are trying check for "btnadd" because your submit button has that name.
and you have an error in your input:
<input type="submit" name"btnadd" value="Add Event">
you didnt enter "=", so should be:
<input type="submit" name="btnadd" value="Add Event">
where "btnadd" is has to be in your PHP like this
if(isset($_GET['btnadd']));//Exact var name

Categories