I am new to coding and have no clue. I managed to grap this script from this site http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/
I amended the titles and field inputs to match my project requirements instead of the ones used in the demo. I managed to get this working on my project with reference to the drop down lists.
The problem i am having now is how do you make the script accept the values and input it into the database after the customer selects the drop down lists and clicks the submit button.
If there is a better way to rewrite these codes?
Please i am in need of help. Thank you!
here is the code i got on the "get_child_categories.php" file:
<?php
include('cn.php');
if($_REQUEST)
{
$id = $_REQUEST['parent_id'];
$query = "select * from tour where pid = ".$id;
$results = #mysql_query( $query);
$num_rows = #mysql_num_rows($results);
if($num_rows > 0)
{?>
<select name="sub_category" class="parent">
<option value="" selected="selected">-- Sub Category --</option>
<?php
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['tour_id'];?>"><?php echo $rows
['category'];?></option>
<?php
}?>
</select>
<?php
}
else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found
!</label>';}
}
?>
Also note that the "No Record Found" is always displayed after selecting all drop down lists at the end. How do i fix this to show every criteria is met before submission?
This is the "booking.php" form:
<!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" xml:lang="en" lang="en">
<head>
<link href="style.css" rel="stylesheet" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Jurassic Tours/booking form</title>
<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript" src="jquery.livequery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//$('#loader').hide();
$('.parent').livequery('change', function() {
$(this).nextAll('.parent').remove();
$(this).nextAll('label').remove();
$('#show_sub_categories').append('<img src="loader.gif" style="float:left;
margin-top:7px;" id="loader" alt="" />');
$.post("get_chid_categories.php", {
parent_id: $(this).val(),
}, function(response){
setTimeout("finishAjax('show_sub_categories', '"+escape(response
)+"')", 400);
});
return false;
});
});
function finishAjax(id, response){
$('#loader').remove();
$('#'+id).append(unescape(response));
}
</script>
<style>
.both h4{ font-family:Arial, Helvetica, sans-serif; margin:0px; font-size:14px;}
#search_category_id{ padding:3px; width:200px;}
.parent{ padding:3px; width:150px; float:left; margin-right:12px;}
.both{ float:left; margin:0 0px 0 0; padding:0px;}
</style>
</head>
<?php
include('cn.php');?>
<body>
<div id="main">
<div id="header">
<img src="images/banner.jpg" alt="Banner" style="padding:10px"/>
</div>
<div id="mylinks">
<div id="navcontainer">
<ul>
<li>Home</li>
<li>Login</li>
<li>Register</li>
<li>Booking</li>
<li>About Us</li>
<li>Services</li>
<li>Feedback</li>
<li>Agency Login</li>
<li>Logout</li>
</div>
</div>
<div id="content">
<h2><center>PLEASE PLACE YOUR BOOKING</center></h2>
<div style="padding-left:30px; height:710px;">
<br clear="all" /><br clear="all" />
<form action="booking.php" method="post">
<div id="show_sub_categories">
<select name="search_category" class="parent">
<option value="" selected="selected">-- Categories --</option>
<?php
$query = "select * from tour where pid = 0";
$results = mysql_query($query);
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['tour_id'];?>"><?php echo $rows
['category'];?></option>
<?php
}?>
</select>
</div>
<br clear="all" /><br clear="all" />
<input type="submit" name="submit" value="submit">
</form>
<br clear="all" /><br clear="all" />
</div>
</body>
</html>
The booking form is getting data from the tour table in the database where there is tour,destination,and duration all dependant on drop down lists selected.
This is the processing part where i do not know how to do after the submit button is pressed so i left it blank! The only data i can recover is the Primary key from the customer table as shown below.
<?php
//When submit button is pressed.
if (isset($_POST['submit'])) {
//Include the server and database connection.
include('cn.php');
session_start();
$userUsername = $_SESSION['loggedInUser'];
// Build the SQL query to retreive the variables ($) and input the data into the database.
$sql = "INSERT INTO booking
(user_id)
VALUES ((SELECT user_id FROM user WHERE user_username =
'" . $userUsername . "'))";
// test the sql statement.
if(!mysql_query($sql,$cn)) {
die(mysql_error($cn));
}
// direct to this page when booking is successful.
header('Location: booking_success.php');
}
?>
I forgot to include the update.php file
<?php
if (!empty($_GET['tour_id']) && !empty($_GET['value'])) {
$id = $_GET['tour_id'];
$value = $_GET['value'];
try {
$objDb = new PDO('mysql:host=localhost;dbname=jurassicbase', 'root', '');
$objDb->exec('SET CHARACTER SET utf8');
$sql = "SELECT *
FROM `categories`
WHERE `master` = ?";
$statement = $objDb->prepare($sql);
$statement->execute(array($value));
$list = $statement->fetchAll(PDO::FETCH_ASSOC);
if (!empty($list)) {
$out = array('<option value="">Select one</option>');
foreach($list as $row) {
$out[] = '<option value="'.$row['tour_id'].'">'.$row
['name'].'</option>';
}
echo json_encode(array('error' => false, 'list' => implode('', $out)));
} else {
echo json_encode(array('error' => true));
}
} catch(PDOException $e) {
echo json_encode(array('error' => true));
}
} else {
echo json_encode(array('error' => true));
}
I'm guessing you are never reaching the form processor as you don't have any <form> tag in your form page.
You would need:
<form action="your_form_processor.php" method="post">
// your form fields
</form>
to get that to work.
Apart from that you need to switch to PDO (or mysqli) and prepared statements as your code is vulnerable to sql injection.
While you are developing your code, you should also remove all # error suppressing operators.
Related
MY INDEX PAGE
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Some name</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" />
</head>
<body>
<div class="container">
<br />
<h2 align="center">Search by name</h2><br />
<div class="form-group">
<div class="input-group">
<span class="input-group-addon">Search</span>
<input type="text" name="search_text" id="search_text" placeholder="Enter model / search here" class="form-control" />
</div>
</div>
<br />
<div id="result"></div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
load_data();
function load_data(query)
{
$.ajax({
url:"fetch.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(){
var search = $(this).val();
if(search != '')
{
load_data(search);
}
else
{
load_data();
}
});
});
</script>
AND MY fetch.php PAGE
which is used to get data from the database tables and output results.
I also added if the result is > 50 it will ask to enter few more characters because if I don't add if result > 50 then my page took 20sec to display all data because my database table has 25000 entries.
<?php
$connect = mysqli_connect("localhost", "root", "PASSWORD", "DATABASE");
if(isset($_POST["query"]))
{
$search = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM files
WHERE Name LIKE '%".$search."%'
";
}
else
{
$query = "
SELECT * FROM files ORDER BY ID
";
}
$result = mysqli_query($connect, $query);
if(mysqli_num_rows($result) < 500)
{
$output1 .= '
<div class="table-responsive">
<table class="table table bordered">
<div>
<th>Name</th>
<th>URL</th>
<th>Extension</th>
<th>Download</th>
</div>
';
while($row = mysqli_fetch_array($result))
{
$output2 .= '
<tr>
<td>'.$row["Name"].'</td>
<td>'.$row["URL"].'</td>
<td>'.$row["Extension"].'</td>
</tr>
';
}
if(mysqli_num_rows($result) > 0)
{
echo "$output1";
echo "$output2";
}
else
{
echo 'no results found';
}
}
else
{
echo 'Please enter few more charecters';
}
?>
I want href link for each of my results and on the click, it should download a file from ./"URL" column from a database table.
My database looks like this:
AND MY CURRENT PAGE IS http://mss1996.ddns.net:8008/files
I tried adding < a href=".$row["URL"]."> in outpur'array' but it destroys my page.
You should be able to easily add the URL field to form a valid URL if the contents of that field is indeed a valid URL. What I see missing form your code is http or https if it's an external link. If it's a relative link within the page then you're ok. Then add the </a> to close the link. So you'd form your table column like this:
echo '<td>' . $row["URL"] . '</td>';
i'm trying to create an autocomplete box for a form.
Basically what I want to achieve is a textarea field that allows me to search the database for names belonging to a table and add them to a table through a form.
I managed to create this, but it allows me to search only one name at a time, while I would need to look for more names to add to the same textarea.
Basically I have a textarea and this must give me the possibility to insert more names:
name1
name2
...
Where each name is chosen from the drop-down menu that is created. In this way I could go to insert more "names" in the database.
auto_complete.php
<!DOCTYPE html>
<html>
<head>
<title>Autocomplete TextBox</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>
ul{
background-color:#eee;
cursor:pointer;
}
li{
padding:12px;
}
</style>
</head>
<body>
<br /><br />
<div class="container" style="width:500px;">
<form method="post" action="insert_db.php">
<h3 align="center">Box Text</h3><br />
<label>Enter Name</label>
<br> <textarea name="nominativo" rows="5" cols="30" placeholder="Name Surname" id="nominativo" class="form-control"" ></textarea><br>
<input type="submit" value="Invia">
<div id="nominativoList"></div>
</form>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#nominativo').keyup(function(){
var query = $(this).val();
if(query != '')
{
$.ajax({
url:"search.php",
method:"POST",
data:{query:query},
success:function(data)
{
$('#nominativoList').fadeIn();
$('#nominativoList').html(data);
}
});
}
});
$(document).on('click', 'li', function(){
$('#nominativo').val($(this).text());
$('#nominativoList').fadeOut();
});
});
</script>
search.php
<?php
$conn = mysqli_connect("localhost", "root", "123456789", "Personale");
if(isset($_POST["query"]))
{
$output = '';
$query = "SELECT * FROM Squadra WHERE Nominativo LIKE '%".$_POST["query"]."%'";
$result = mysqli_query($conn, $query);
$output = '<ul class="list-unstyled">';
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{
$output .= '<li>'.$row["Nominativo"].'</li>';
}
}
else
{
$output .= '<li>Country Not Found</li>';
}
$output .= '</ul>';
echo $output;
}
?>
insert_db.php
<?php
$conn = mysqli_connect("localhost", "root", "123456789", "Personale");
$nominativo = $_POST['nominativo'];
$sql = "INSERT INTO Prenotazione (Nominativo) VALUES ('$nominativo')";
$result = mysqli_query($conn,$sql);
?>
In your opinion how can i do??
Thank you for your attention and for your time.
I couldn't find an answer to this question elsewhere, I was hoping someone here might know. I've spent 9 hours straight trying to get this to work, I've been searching non-stop.
I have three PHP files. The third file contains my PHP functions to check for existing users and add users to the database
user.inc.php
<?php
//checks if given username exists in database
function user_exists($user){
$user = mysqli_real_escape_string($user);
$sql= "SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}'";
$result = mysqli_query($con,$sql);
if ($result == 1){
return true;
}
else {
return false;
}
}
function email_exists($email){
$user = mysqli_real_escape_string($email);
$sql="SELECT COUNT(`user_id`) FROM `users` WHERE `user_email` = '{$email}'";
$result = mysqli_query($con,$sql);
// $row = mysqli_fetch_assoc($total);
if ($result == 1){
return true;
}
else {
return false;
}
}
//checks if given username/password is valid
function valid_credentials($user,$pass){
$user = mysqli_real_escape_string(htmlentities($user));
$pass = sha1($pass);
$sql= "SELECT COUNT(`user_id`) FROM `users` WHERE `user_name` = '{$user}'AND `user_password` ='{$pass}'";
$result = mysqli_query($con,$sql);
if ($result == 1){
return true;
}
else {
return false;
}
}
//adds a user to the database
function add_user($user,$pass,$email){
mysqli_query($con,"INSERT INTO`users` (`user_name`,`user_password`,`user_email`) VALUES ('a','b','c')");
$user = mysqli_real_escape_string(htmlentities($user));
$pass = sha1($_REQUEST[$pass]);
mysqli_query($con,"INSERT INTO`users` (`user_name`,`user_password`,`user_email`) VALUES ('{$user}','{$pass}','{email}')");
}
?>
The second PHP file starts the connection to the database and includes the previous file at the bottom.
init.inc.php
<?php
session_start();
$exceptions = array('registerPage','login');
$page = substr(end(explode('/',$_SERVER['SCRIPT_NAME'])), 0, -4);
if (in_array($page, $exceptions)=== false){
if (isset($_SESSION['username'])=== false ){
header('Location: login.php');
die();
}
}
$con = mysqli_connect('127.0.0.1','root','','yingyujiaocheng');
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_query($con,"INSERT INTO `users` (`user_name`,`user_password`) VALUES ('user','pass')");
$path = dirname(__FILE__);
include("{$path}/inc/user.inc.php");
?>
The third PHP file includes the second file at the top and also has HTML and forms. When the form on the 3rd page is filled out and submitted, it sends the information to the top of the 3rd page to the PHP script. This is processed for errors which calls functions from the first files. The database works, I have done MYSQLI commands from every place, the only thing not working is the call from the 3rd PHP file to the first PHP file. The functions user_exists, email_exists and add_user to not call correctly.
Here is the third file:
registerPage.php
<?php error_reporting(E_ALL);
include('core/init.inc.php');
$errors = array();
if(isset($_POST['username'],$_POST['password'],$_POST['email'])){
$username = $_POST['username'];
$password = $_POST['password'];
$email = $_POST['email'];
if (empty($username)){
$errors[] = 'The username cannot be empty.';
}
if (empty($password)){
$errors[] = 'The password cannot be empty.';
}
if (empty($email)){
$errors[] = 'The email field cannot be empty.';
}
if (user_exists($username)){
$errors[] = 'The username is already taken';
}
if (email_exists($email)){
$errors[] = 'The email already taken';
}
if (empty($errors)){
add_user($username,$password,$email);
//$_SESSION['username'] = htmlentities($username);
//header('Location: protected.php');
// die();
}
}
?>
<!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>
<link href="ext/Styles/styleSheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div class="header" align="centre">
<img src="ext/Images/Logo.png" width="150" height="80" style="float:left;" />
<h2 class="headerFontClickedSmall" style="float: right; margin-top:36px; margin-right: 60px"> </h2>
<h2 class="headerFontUnclickedSmall" style="float: right; margin-top:36px; margin-right: 10px"> / </h2>
<h2 class="headerFontUnclickedSmall" style="float: right; margin-top:36px; margin-right: 10px"> </h2>
<h2 class="cornerBox1" style="float: right; margin-top:20px; margin-right: 50px"> </h2>
</div>
<div class="content">
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<?php echo "Username is :" . $username . "<br>";
echo "Password is :" . $password;
?>
<br />
<h1 class="contentHeader" style=""> </h1>
<div>
<?php
if (empty($errors) === false){
?>
<ul>
<?php
foreach ($errors as $error){
echo "<li>{$error}</li>";
}
?>
</ul>
<?php
}
?>
</div>
<form action="registerPage.php" method="POST">
<h1 class="contentRegisterText" style=""> : <input class="inputbox" style="margin-left:30px" type="text"
name = "username" id="username"/> </h1>
<br />
<h1 class="contentRegisterText" style=""> : <input class="inputbox" style="margin-left:30px" type="text"
name = "email" id="email"/> </h1>
<br />
<h1 class="contentRegisterText" style="">: <input class="inputbox" style="margin-left:30px" type="password"
name = "password" id="password"/> </h1>
<br /><br /><br /><br /><br /><br />
<input style="margin-left:30px" type="submit" value = "" id="Register"/> </form>
</div>
<div class="footer" align="center" >
<div class="floating-box" style="margin-top:40px" >
<dl>
<dt><h1 class="footerTitle">社交媒体</h1></dt>
<br />
<dd><a href="http://www.huya.com/lucio">
<img src="ext/Images/HuyaLogo.png" alt=" " width="42" height="42" outline="none">
</a>
<img src="ext/Images/weixinLogo.png" width="40" height="40" style="margin-left:3;"/><img src="ext/Images/logo-qq.png" width="40" height="40" /></dd>
</dl>
</div>
<div class="floatingboxFooter1" style="margin-top:40px">
<dl>
<dt><h1 class="footerTitle"></h1> </dt>
<br />
<dd><h1 class="footerSmall">:</h1></dd>
<dd><h1 class="footerSmall">Weixin: </h1></dd>
<dd><h1 class="footerSmall">QQ: </h1></dd>
</dl>
</div>
<div class="floating-box" style="margin-top:64px">
<dl>
<br />
<dd><h1 class="footerSmall">bangzhu#yingyujiaocheng.com</h1></dd>
<dd><h1 class="footerSmall">yingyujiaocheng</h1></dd>
<dd><h1 class="footerSmall">yingyujiaocheng</h1></dd>
</dl>
</div>
<div class="floatingboxFooter1" style="margin-top:40px">
<dl>
<dt><h1 class="footerTitle"></h1> </dt>
<br />
<dd><h1 class="footerSmall"></h1></dd>
<dd><h1 class="footerSmall"></h1></dd>
<dd><h1 class="footerSmall"></h1></dd>
</dl>
</div>
</body>
</html>
Thank you for looking, any help is appreciated,
Cheers
Lucio
Try to debug the $path variable, I think the problem is in the path you included in this line.
include("{$path}/inc/user.inc.php");
Or try to insert global $con on top of every function inside user.inc.php like so:
function user_exists($user) {
global $con;
// rest of the code...
}
I came up with a problem which made me crazy as I am new to PHP. The problem is: the below timetable submission form works good on Chrome (every time I left the email unfilled, the submission cannot be processed). However, when using on safari, you can always submit blank form into the database.
Here is the html form.
<script type="text/javascript" src="/membership/my-form/js/jquery-2.1.1.js"></script>
<script type="text/javascript" src="/membership/my-form/js/main.js"></script>
<form class="mf-form floating-labels" method="post" action="timetablesubmit.php">
<div>
<h1 style="text-align:center">Availability form</h1>
</div>
<div>
<p class="mf-select icon">
<select name="timetable-staff" class="user" required>
<option value="">Select Person</option>
<option value="AMY">Amy</option>
<option value="TOM">Tom</option>
</select>
</p>
<div>
<input name="location1" value="A" type="hidden">
<input name="location2" value="B" type="hidden">
</div>
<div class="AMY box">You work in A.</div>
<div class="TOM box">You work in B.</div>
</div>
<div class="icon">
<label class="mf-label" for="mf-email">Email Address</label>
<input class="email" type="email" name="timetable-email" id="mf-email" required>
</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("select").change(function(){
$( "select option:selected").each(function(){
if($(this).attr("value")=="Amy"){
$(".box").hide();
$(".AMY").show();
}
if($(this).attr("value")=="Tom"){
$(".box").hide();
$(".TOM").show();
}
});
}).change();
});
</script>
<style type="text/css">
.box{
padding: 10px;
display: none;
margin-top: 20px;
border: 1px solid #000;
font-size:1.6em;
text-align:center;
background-color: #f1f1f1;
}
</style>
Here is the timetablesubmit.php:
<?php
header("content-type:text/html;charset=utf-8");
session_start();
$timesubmit=date('Y-m-d H:i:s');
$staff=$_POST['timetable-staff'];
$email=$_POST['timetable-email'];
$con=mysql_connect("localhost","database","password");
if (!$con) {
die ('Could not connect:' . mysql_error());
}
mysql_select_db("database", $con);
mysql_query("set names utf8");
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
mysql_close($con);
sleep(2);
?>
<html>
<? require 'header.php'; ?>
<div class="tk-reg">
<p>Thak you <?php echo $_POST['timetable-staff']; ?><p>
<p> Time availability submitted successfully.<p>
Your email address is: <?php echo $_POST["timetable-email"]; ?>
</div>
<div class="tk-regfollow">
<ul style="text-align:center">
Back to home page.
</ul>
</div>
</html>
Then I searched the Internet and changed to below, still not working on Safari (the alert appears, however data still been insert into database.
<?php
require 'header.php';
$nameErr = $emailErr = "";
$name = $email = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["timetable-staff"])) {
$nameErr = "Please select a staff.";
} else {
$staff = test_input($_POST["timetable-staff"]);
}
if (empty($_POST["timetable-email"])) {
$emailErr = "Email address is required";
} else {
$email = test_input($_POST["timetable-email"]);
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
$con=mysql_connect("localhost","database_name","database_password");
if (!$con) {
die ('Could not connect:' . mysql_error());
}
mysql_select_db("database_name", $con);
mysql_query("set names utf8");
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
mysql_close($con);
sleep(2);
?>
<html>
<style>
.error {color: #FF0000;}
</style>
<h1 style="text-align:center">Availability form for
<?php
$d=strtotime("+1 Months");
echo date("M", $d) . " 2015 <br>";
?>
</h1>
<form class="mf-form floating-labels" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<div>
<p class="mf-select icon">
<select name="timetable-staff" class="user" required>
<option value="">Select Person</option>
<option value="AMY">Amy</option>
<option value="TOM">Tom</option>
</select>
<span class="error">* <?php echo $nameErr;?></span>
</p>
</div>
<div class="icon">
<label class="mf-label" for="mf-email">Email Address</label>
<input class="email" type="email" name="timetable-email" id="mf-email" required>
<span class="error">* <?php echo $emailErr;?></span>
</div>
<br><br>
<input type="submit" name="submit" value="Submit">
</form>
</html>
I hope someone could help me pointing out my mistakes. Thank you.
======================================================================
I tried a lot of ways to figure this out, however still have either 'this' or 'that' problems. I finally use a method that actually work, but I do not know whether it is not recommended.
Here is the code I modified in timetablesubmit.php
(my flow is: timetable.php ==>timetablesubmit.php==>welcome.php)
$email = trim($_POST['timetable-email']);
if($email !='' and $email !=null) {
$sql1;
}
else {
echo '<html><head>
<link rel="stylesheet" type="text/css" href="/membership/style.css"/>
<head>
<div class="check-error-message">
<p>Error: Email address is required.</p><br>
Return
</div>';
exit;
};
You can check with condition before insert operation
if($nameErr =="" && $emailErr == "")
{
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
}
you can have one condition here to avoid empty fill
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
here keep this condition like this
if($staff!='' && $email!='')
{
mysql_query("INSERT INTO timetable(staff,email)
VALUES('$staff','$email')");
}
Html 5 "required" will not work in safari.
This line is the problem <input class="email" type="email" name="timetable-email" id="mf-email" required>
Write jquery/javascript validation to check the required field.
Hope its help you.
As they said, not all browsers accept the attribute required because it's new.
On PHP, server side, you can validate too if there's something filled with:
$var = trim($_POST['var']);
if(!is_empty($var)) {
//do mysqli function
}
else {
//show error
}
trim will remove blank spaces at start and end of the value given.
is_empty will be almost like $var == ""
I recently found this tutorial http://www.infotuts.com/create-ajax-based-search-system-php-jquery/ and have noticed that all the results are displayed in search.php while search.php is called through ajax and displayed in index.php. Whenever I tried to integrate it into my website, my index.php contains a variable of $id which is shown in this url: (index.php?id=1) My problem is, I can't seem to get it to know what my $id is. I am unable to change the query in search.php to what I like as a result of this.
$query = mysql_query("select * from userdetail where name like '{$term}%'", $connection);
Here is the original query above me, however I want to have it dependent on the id of the page, so... :
$query = mysql_query("select * from userdetail where id = '$id' AND name like '{$term}%'", $connection);
The only problem is, that search.php has no idea what my $id variable is, even when I load it from index.php it does not work. Can anyone help?
The full code can be seen in the tutorial, but I can show you guys here.
Search.php
<?php
$connection = mysql_connect('localhost', 'root', '12345');
$db = mysql_select_db('userdata', $connection);
$term = strip_tags(substr($_POST['searchit'],0, 100));
$term = mysql_escape_string($term); // Attack Prevention
if($term=="")
echo "Enter Something to search";
else{
$query = mysql_query("select * from userdetail where id = '$id' AND name like '{$term}%'", $connection);
$string = '';
if (mysql_num_rows($query)){
while($row = mysql_fetch_assoc($query)){
$string .= "<b>".$row['name']."</b> - ";
$string .= $row['email']."</a>";
$string .= "<br/>\n";
}
}else{
$string = "No matches found!";
}
echo $string;
}
?>
Here is index.php
<html>
<head>
<title>Ajax Based Search- InfoTuts</title>
<?php
$id = ((int)$_GET["id"]);
?>
<style type="text/css" >
#main {
padding: 10px;
margin: 100px;
margin-left: 300px;
color: Green;
border: 1px dotted;
width: 520px;
}
#display_results {
color: red;
background: #CCCCFF;
}
</style>
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#button_find").click(function(event){
event.preventDefault();
search_ajax_way();
});
$("#search_query").keyup(function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
$("#search_results").show();
var search_this=$("#search_query").val();
$.post("search.php", {searchit : search_this}, function(data){
$("#display_results").html(data);
})
}
</script>
</head>
<body>
<div id="main">
<h1>Ajax Based Search System- InfoTuts</h1>
<form id="searchform" method="post">
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="submit" value="Search" id="button_find" />
</form>
<div id="display_results"></div>
</div>
</body>
</html>
Try this
In search.php file add the following code to accept the id from index.php file
<code>
$term = mysql_escape_string($term); // Attack Prevention
$id = $_POST['id'];
if(!empty($id)) {
$query = mysql_query("select * from userdetail where id = '$id' AND name like '{$term}%'", $connection);
} else {
$query = mysql_query("select * from userdetail where name like '{$term}%'", $connection);
}
if($term=="")
echo "Enter Something to search";
</code>
In the index.php file send the $id variable value along with the ajax request.
<code>
function search_ajax_way(){
$("#search_results").show();
var search_this=$("#search_query").val();
var id_val=$("#id").val();
$.post("search.php", {searchit : search_this, id : id_val}, function(data){ $("#display_results").html(data);}
</code>
In the html add a input hidden field for id
<code>
<form id="searchform" method="post">
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type='hidden' value='<?php echo $id; ?>' id='id'/>
<input type="submit" value="Search" id="button_find" />
</form>
</code>
in
Please mention action='search.php' in form then it will redirect to search.php...and there you will get $id...