Upload User ID to Database using Ajax and PHP - javascript

The thing is i a have a page where my user post shows and on the post there is a connect button in form of form input. Each of the post has the posters id. I want it such that when a user clicks on the connect button the poster's id is INSERTED into the database.
The PHP
<?php
$sql = <<<EOF
SELECT COUNT(*) as count FROM programs;
EOF;
$ret = $db->querySingle($sql);
if ($ret == 0)
{
echo "<div class='no_prog'>No programs currently advertised</div>";
}
else
{
$rsql = <<<EOF
SELECT * FROM programs ORDER BY id DESC;
EOF;
$rret = $db->query($rsql);
while ($rrow = $rret->fetchArray(SQLITE3_ASSOC))
{
$banner = $rrow['banner'];
$banner_2 = $rrow['banner_2'];
$title = $rrow['sem_title'];
$spons = $rrow['sem_spons'];
$link = $rrow['sem_link'];
$company = $rrow['sem_comp'];
$brief = $rrow['sem_brief'];
$ad_id = $rrow['userid'];
$usql = <<<EOF
SELECT * FROM User WHERE ID = '$ad_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC))
{
$ad_img = $urow['image'];
$ad_name = $urow['fname'];
echo "<div class=\"preview_prog\">
<div class='posted_by'>
<p><img src='$ad_img'></p>
</div>
<div class='ad_user_info'>
<div class='ad_info'>
<div class='ad_info_img'>
<img src='$ad_img'>
</div>
<div class='ad_info_name'>
<p>$ad_name</p>
</div>
<div class='ad_info_conn'>
<div class='ad_info_conn_btn'>
<div class='conn_img'>
<img src='images/connect.png'>
</div>
//TOP INSERT $ad_id TO DATABASE
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
<!--<a href='user_connect.php?userid=$ad_id' class='conn_text' name='user_connect'>Connect +</a>-->
</form>
</div>
I have tried putting the form="action" in an external php file but its not getting the$ad_id. Most likely because it not a link
Action PHP
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['connect']))
{
$my_id = $_SESSION['log_id'];
$ad_id = (int)$_GET['userid'];
$rand_num = rand();
$hsql =<<<EOF
SELECT COUNT(hash) as count FROM connect WHERE (user_one = '$my_id' AND user_two = '$ad_id') OR (user_one = '$ad_id' AND user_two = '$my_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1)
{
$response = "Your are already connected to '$ad_id'";
}
else
{
$csql =<<<EOF
INSERT INTO connect (user_one, user_two, hash) VALUES ('$my_id', '$ad_id', '$rand_num');
EOF;
$cret = $db->exec($csql);
if (!$cret)
{
$message = "Error connecting to '$ad_id'";
}
else
{
$message = "Successfully Connected to '$ad_id'";
}
}
}
?>
Please any advice on how i can upload the $ad_id to the database.
Note that am new to PHP and know little Ajax

try to add an hidden field within the form that you are creating in string with name "userid" which will have the id in its value that you want to receive in your action.php with $_GET['userid'] in replace this $_GET['userid'] with $_POST['userid']. You will get the userid
<?php
$sql = <<<EOF
SELECT COUNT(*) as count FROM programs;
EOF;
$ret = $db->querySingle($sql);
if ($ret == 0)
{
echo "<div class='no_prog'>No programs currently advertised</div>";
}
else
{
$rsql = <<<EOF
SELECT * FROM programs ORDER BY id DESC;
EOF;
$rret = $db->query($rsql);
while ($rrow = $rret->fetchArray(SQLITE3_ASSOC))
{
$banner = $rrow['banner'];
$banner_2 = $rrow['banner_2'];
$title = $rrow['sem_title'];
$spons = $rrow['sem_spons'];
$link = $rrow['sem_link'];
$company = $rrow['sem_comp'];
$brief = $rrow['sem_brief'];
$ad_id = $rrow['userid'];
$usql = <<<EOF
SELECT * FROM User WHERE ID = '$ad_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC))
{
$ad_img = $urow['image'];
$ad_name = $urow['fname'];
echo "<div class=\"preview_prog\">
<div class='posted_by'>
<p><img src='$ad_img'></p>
</div>
<div class='ad_user_info'>
<div class='ad_info'>
<div class='ad_info_img'>
<img src='$ad_img'>
</div>
<div class='ad_info_name'>
<p>$ad_name</p>
</div>
<div class='ad_info_conn'>
<div class='ad_info_conn_btn'>
<div class='conn_img'>
<img src='images/connect.png'>
</div>
//TOP INSERT $ad_id TO DATABASE
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='hidden' name='userid' value='$ad_id'/>
<input type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
<!--<a href='user_connect.php?userid=$ad_id' class='conn_text' name='user_connect'>Connect +</a>-->
</form>
</div>
Action.php
<?php
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['connect']))
{
$my_id = $_SESSION['log_id'];
$ad_id = (int)$_POST['userid'];
$rand_num = rand();
$hsql =<<<EOF
SELECT COUNT(hash) as count FROM connect WHERE (user_one = '$my_id' AND user_two = '$ad_id') OR (user_one = '$ad_id' AND user_two = '$my_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1)
{
$response = "Your are already connected to '$ad_id'";
}
else
{
$csql =<<<EOF
INSERT INTO connect (user_one, user_two, hash) VALUES ('$my_id', '$ad_id', '$rand_num');
EOF;
$cret = $db->exec($csql);
if (!$cret)
{
$message = "Error connecting to '$ad_id'";
}
else
{
$message = "Successfully Connected to '$ad_id'";
}
}
}
?>

Related

Filtering result based on multisearchbar using jQuery

I want a user to be able to search for a job based on typing in multiple searchbar components,but in my code it can search based on one searchbar. For this I am using two variables search and search2, it can work only on search variable.
html:
<form action="search.php" method="GET">
<input type="text" id="" class="form-control searchBar" placeholder="Designation">
<input type="text" id="" class="form-control searchBar" placeholder="City" />
<button id="searchBtn" type="button" class="btn btn-info btn-flat">Go!</button>
</form>
javascript:
<script type="text/javascript">
$("#searchBtn").on("click", function(e) {
e.preventDefault();
var searchResult = $(".searchBar ").val();
var filter = "searchBar";
if(searchResult != "" ) {
$("#pagination").twbsPagination('destroy');
Search(searchResult, filter);
} else {
$("#pagination").twbsPagination('destroy');
Pagination();
}
});
</script>
<script type="text/javascript">
function Search(val, filter) {
$("#pagination").twbsPagination({
totalPages: <?php echo $total_pages; ?>,
visible: 5,
onPageClick: function (e, page) {
e.preventDefault();
val = encodeURIComponent(val);
$("#target-content").html("loading....");
//$("#target-content").load("search.php?page="+page+"&search="+val+"&filter="+filter);
$("#target-content").load("search.php?page="+page+"&search="+val+"&search2="+val+"&filter="+filter);
}
});
}
</script>
my search.php page:
<?php
session_start();
require_once("db.php");
$limit = 4;
if(isset($_GET["page"]))
{
$page = $_GET['page'];
}
else
{
$page = 1;
}
$start_from = ($page-1) * $limit;
if(isset($_GET['filter']) && $_GET['filter']=='searchBar')
{
$search = $_GET['search'];
$search2 = $_GET['search2'];
$sql = "SELECT * FROM job_post INNER JOIN company ON job_post.id_company=company.id_company WHERE jobtitle LIKE '%$search%' OR city LIKE '%$search2%' LIMIT $start_from, $limit";
}
?>
i have two input field one for jobtitle and one for city,and based on this i want related output, eg: jobtile='software devloper' and city= 'delhi',my database show only result of software devloper on city delhi.
search.php:
if(isset($_GET['filter']) && $_GET['filter']=='searchBar')
{
$search = $_GET['search'];
$search2 = $_GET['search2'];
$sql = "SELECT * FROM job_post INNER JOIN company ON job_post.id_company=company.id_company WHERE jobtitle LIKE '%$search%' OR city LIKE '%$search2%' LIMIT $start_from, $limit";
}
else if(isset($_GET['filter']) && $_GET['filter']=='experience')
{
$sql = "SELECT * FROM job_post WHERE experience >='$_GET[search]' LIMIT $start_from, $limit";
}
$result = $conn->query($sql);
if($result->num_rows > 0)
{
while($row = $result->fetch_assoc())
{
$sql1 = "SELECT * FROM company WHERE id_company='$row[id_company]'";
$result1 = $conn->query($sql1);
if($result1->num_rows > 0)
{
while($row1 = $result1->fetch_assoc())
{
?>
<div class="attachment-block clearfix">
<img class="attachment-img" src="uploads/logo/<?php echo $row1['logo']; ?>" alt="Attachment Image">
<div class="attachment-pushed">
<h4 class="attachment-heading"><?php echo $row['jobtitle']; ?> <span class="attachment-heading pull-right">$<?php echo $row['maximumsalary']; ?>/Month</span></h4>
<div class="attachment-text">
<div><strong><?php echo $row1['companyname']; ?> |\ <?php echo $row1['city']; ?> | Experience <?php echo $row['experience']; ?> Years</strong></div>
</div>
</div>
</div>
<?php
}
}
}
}
}
$conn->close();
?>

My SQL PHP Generated edit button is only working once

I'm developing a web application which is like a notepad or a to-do list with php sql html css jquery
The query gets the list at index page and displays it and on displaying it adds a button with an "edit" class.
When they press on the edit the edit works but only once after submitting.
On submitting the button launches an ajax call with jQuery to another PHP file which edits the data and and displays all the items from the database again.
There's also an "add item" button which adds a new item. Which on submit adds a new item and also gets everything again from the database and displays it (also ajax).
The bug is either after submitting a new item or after editing, the edit button stops working
Please check the snippet below -- snippet 1 is the jquery, snippet 2 is the file to be run on ajax call, and snippet 3 is the index php file:
$("#submit").click(function(){
textarea = $("#textarea").val();
date = $("#date").val();
if(textarea == "" || date == ""){
$("#message").html("<span class='error'>Make sure you didn't leave anything empty");
}
else{
$("#message").html("");
submitItem();
$("#contentCont").fadeOut(200);
}
});
$(".edit").click(function(){
i = "edit";
itemID = $(this).attr("name");
var dateValue = $("#date"+itemID).text();
var statusValue = $("#status"+itemID).attr("name");
var textboxValue = $("#textbox"+itemID).text();
var categoryValue = $("#category"+itemID).text().toLowerCase();
$("#contentCont").fadeIn(200);
$("#textarea").val(textboxValue);
$("#date").val(dateValue);
$("#categories").val(categoryValue).prop("selected",true);
$("#status").val(statusValue).prop("selected",true);
});
function submitItem(){
textarea = $("#textarea").val();
status = $("#status").val();
category = $("#categories").val();
date = $("#date").val();
var ajaxReq = new XMLHttpRequest();
ajaxReq.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("todoCont").innerHTML = this.responseText;
}
}
ajaxReq.open("POST","../php/addItem.php",true);
ajaxReq.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxReq.send("textarea="+textarea+"&category="+category+"&status="+status+"&date="+date+"&itemID="+itemID+"&i="+i);
}
<?php
session_start();
require("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);
$category = validate($_POST["category"]);
$item = $_POST["textarea"];
$date = $_POST["date"];
$status = validate($_POST["status"]);
$userID = $_SESSION["userID"];
$itemID = $_POST["itemID"];
$i = $_POST["i"];
$searchForCategoryID = "SELECT * FROM categories where userID='$userID' AND categoryname = '$category'";
$result = $cnx->query($searchForCategoryID);
$row = $result->fetch_assoc();
$categoryID = $row["CategoryID"];
if ($i === "new"){
$addItem = "INSERT INTO Items(userID,ItemValue,DueDate,CategoryID,Status) VALUES ($userID, '$item' , '$date' , $categoryID,'$status')";
$cnx->query($addItem);
}
else if ($i === "edit"){
$editItem = "UPDATE Items SET ItemValue='$item' , DueDate='$date' , CategoryID = $categoryID,Status='$status' WHERE itemID = $itemID " ;
$cnx->query($editItem);
}
$getTableRows = "SELECT * FROM Items WHERE userID = $userID ORDER BY DueDate";
$result = $cnx->query($getTableRows);
if($cnx->error){
echo "Could not get your stuff";
}
if($result->num_rows > 0){
while ($rows = $result->fetch_assoc()){
$getCategory = "SELECT CategoryName FROM Categories WHERE CategoryID = " . $rows["CategoryID"] . ";";
$result2 = $cnx->query($getCategory);
$rows2 = $result2->fetch_assoc();
if ($rows["Status"] == "ongoing"){
$status = "ongoing";
}else
if ($rows["Status"] == "overdue"){
$status = "overdue";
}else
if ($rows["Status"] == "done"){
$status = "done";
}
echo ' <div class="box-container">
<div class="right">
<div class="textbox">
<span id="textbox'.$rows["itemID"].'">'. $rows["ItemValue"] .'</span>
</div>
<div class="footer">
<div class="status '. $status .'" id="status'.$rows["itemID"].'" name="'.$status.'"></div>
<span class="date" id="date'.$rows["itemID"].'">'.$rows["DueDate"].'</span>
<span class="category" id="category'.$rows["itemID"].'">'.ucfirst($rows2["CategoryName"]).'</span>
<button type="button" name="'. $rows["itemID"] .'" class="btn btn-info edit">Edit</button>
</div>
</div>
</div>';
}
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php session_start();?>
<?php
include("server.php");
$cnx = new mysqli($server_name,$server_username,$server_password,$db);
$userID = $_SESSION["userID"];
<!--This is how the info is shown and the EDIT button is made-->
echo ' <div class="box-container">
<div class="right">
<div class="textbox">
<span id="textbox'.$rows["itemID"].'">'. $rows["ItemValue"] .'</span>
</div>
<div class="footer">
<div class="status '. $status .'" id="status'.$rows["itemID"].'" name="'.$status.'"></div>
<span class="date" id="date'.$rows["itemID"].'">'.$rows["DueDate"].'</span>
<span class="category" id="category'.$rows["itemID"].'">'.ucfirst($rows2["CategoryName"]).'</span>
<button type="button" name="'. $rows["itemID"] .'" class="btn btn-info edit">Edit</button>
</div>
</div>
</div>';
}
?>
you need to register your events more globally:
$("body").on("click", "#submit", function(){
});
and
$("body").on("click", ".edit", function(){
});
You need to delegate as the element is getting created dynamically.
Change the below line:
$(".edit").click(function(){
to:
$(".edit").on('click', function(){
And the same applies for
$("#submit").click(function(){
to
$("#submit").on('click', function(){

Error occur when login with switching database when company name is selected which related with $_SESSION

Im facing a problem Notice: Undefined index: company in C:\xampp\htdocs\new_exp\login.php on line 4
Errors
At here i have 3 database. exp, new_1 and new_2. In exp database have company table which contain id, company_name, and database_name attributes.
There are two database connection that i use which are dbconnection_main.php and dbconnection.php. dbconnection_main.php i used to call ada database which storing company_name and database_name table. Once user selected option of company_name when login in same time it will call the database_name.
The error occur when i login.
This is my index.php
<?php
session_start();
error_reporting(-1);
// Cek Active Link
function ActiveClass($requestUri)
{
$current_file_name = basename($_SERVER['REQUEST_URI'], ".php");
if ($current_file_name == $requestUri)
echo 'class="active"';
}
//check already login
if (!isset($_SESSION['UserId'])) {
header ('Location: login');
exit;
}
if ($_SESSION['level'] == 'APPROVAL'){
header ('Location: login');
exit;
}
//Link to page
if (isset($_GET['page']) && $_GET['page'] == 'ManageCategory') {
$page = "ManageExpenseCategory";
} else {
$page = 'dashboard';
}
//get global notification
include('includes/global.php');
//Get Header
include('includes/header.php');
//set global message notification
$msgBox ="";
if (file_exists('pages/'.$page.'.php')) {
// Load the Page
include('pages/'.$page.'.php');
} else {
// Else Display an Error
echo '
<div class="wrapper">
<h3>Err</h3>
<div class="alertMsg default">
<i class="icon-warning-sign"></i> The page "'.$page.'" could not be found.
</div>
</div>
';
}
include('includes/footer.php');
?>
So here is my login.php
<?php
session_start();
error_reporting(-1);
$_SESSION['db_company_name'] = $_POST['company'];
$msgBox = '';
//include notification page
include ('includes/notification.php');
//Include db Page
require_once ('includes/dbconnection.php');
//Include Function page
include ('includes/Functions.php');
//User Login
if(isset($_POST['login']))
{
$username = $mysqli->real_escape_string($_POST['email']);
$Password = encryptIt($_POST['password']);
if ($stmt = $mysqli->prepare("SELECT UserId, company_id, FirstName, LastName, Email, Password, level, admin_access, Currency from user WHERE Email = ? AND Password = ? "))
{
$stmt->bind_param("ss", $username, $Password);
$stmt->execute();
$stmt->bind_result($UserId_, $CompanyId_, $FirstName_, $LastName_, $Email_, $Password_, $Level_, $Admin_access_, $Currency_);
$stmt->store_result();
$stmt->fetch();
if ($num_of_rows = $stmt->num_rows >= 1)
{
session_start();
$_SESSION['UserId'] = $UserId_;
$_SESSION['FirstName'] = $FirstName_;
$_SESSION['LastName'] = $LastName_;
$_SESSION['level'] = $Level_;
$_SESSION['admin_access'] = $Admin_access_;
$_SESSION['Currency'] = $Currency_;
$_SESSION['company_id'] = $CompanyId_;
$compId = $_SESSION['company_id'];
$UserIds = $_SESSION['UserId'];
$company_q = mysqli_query($mysqli, "SELECT * FROM company_setting where company_id = '".$compId."'");
$company = mysqli_fetch_assoc($company_q);
$_SESSION['company_name'] = $company['company_name'];
if ($_SESSION['level'] === 'STAFF'){
echo '<META HTTP-EQUIV="Refresh" Content="0; URL=index">';
}
else
{
$msgBox = alertBox($LoginError);
}
}
}
}
?>
<!DOCTYPE html>
<html>
<div class="panel-body">
<?php if ($msgBox) {
echo $msgBox;
} ?>
<form class="form-horizontal m-t-20" method="post" action="" role="form">
<div class="form-group ">
<div class="col-xs-12">
<input class="form-control" onBlur="checkcompany(this.value)" type="email" required placeholder="<?php echo $Emails; ?>" name="email" id="email" autofocus>
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<input class="form-control" type="password" name="password" value="" required placeholder="<?php echo $Passwords; ?>">
</div>
</div>
<div class="form-group">
<div class="col-xs-12">
<span id="result"><select name="company" id="company" class="form-control" required><option>company</option></select></span>
</div>
</div>
<div class="form-group text-center m-t-40">
<div class="col-xs-12">
<button type="submit" name="login" class="btn btn-primary btn-block text-uppercase waves-effect waves-light"><?php echo $SignIn; ?></button>
</div>
</div>
</form>
</div>
<script>
function checkcompany(v)
{
//alert(v);
var dataString = 'email='+v;
//document.getElementById('loginbtn').style.display = "none";
$.ajax({
type: "POST",
url: "checkaccount.php",
data: dataString,
cache: true,
success: function (result){
$("#result").html(result);
//document.getElementById('loginbtn').style.display = "block";
}
})
}
</script>
This is my checkaccount.php
<?php
error_reporting(-1);
session_start();
include("includes/dbconnection_main.php");
$email = $_POST['email'];
?>
<select name="company" id="company" class="form-control" required>
<option value="">----------------</option>
<?php
$company_q = mysqli_query($mysqli, "SELECT * FROM company");
while($company = mysqli_fetch_assoc($company_q))
{
//connect to sub database
$conn_hostname = "localhost";
$conn_database = $company['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqlii = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
$check_q = mysqli_query($mysqlii, "SELECT * FROM user WHERE Email = '".$email."' AND status = 'ACTIVE' AND password != ''");
$check = mysqli_num_rows($check_q);
if (!$check) {
printf("Error: %s\n", mysqli_error($mysqlii));
exit();
}
if($check >= 1)
{
?>
<option value="<?php echo $company['company_name']; ?>"><?php echo strtoupper($company['company_name']); ?></option>
<?php
}
mysqli_close($mysqlii);
}
?>
</select>
SO this is my dbconnection_main.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
$mysqli = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
?>
And This is my dbconnection.php
<?php
error_reporting(-1);
ini_set('display_errors', '0');
if(!isset($_SESSION))
{
session_start();
}
$dbuser="root";
$dbpassword="";
$dbname="exp";
$dbhost="localhost";
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}
$mysqlie = new mysqli($dbhost, $dbuser, $dbpassword, $dbname);
$get_database_q = mysqli_query($mysqlie, "SELECT * FROM company WHERE company_name = '".$company_name."'") or trigger_error(mysqli_error($mysqlie),E_USER_ERROR);
$get_database = mysqli_fetch_assoc($get_database_q);
if (!$get_database) {
printf("Errors: %s\n", mysqli_error($mysqlie));
exit();
}
$conn_hostname = "localhost";
$conn_database = $get_database['database_name'];
$conn_username = "root";
$conn_password = "";
$mysqli = new mysqli($conn_hostname, $conn_username, $conn_password, $conn_database);
?>
I cannot detect the error since it only give me such general error prompt out. I think it might be related with dbconnection.php at this part which related with $_session..
if($_SESSION['db_company_name'] != '')
{
$company_name = $_SESSION['db_company_name'];
}else
{
$company_name = $_POST['company_name'];
$_SESSION['db_company_name'] = $company_name;
}

Php validation form without char

I have a problem.I need that the user can not send the form without having to write something
I have this form :
<div id="content" class="inner-wrapper reg">
<div id="mside">
<div class="section goback">
<div class="btn-back"><a class="back" onClick="history.go(-1)"><?= $lang['profile']['back'] ?></a></div>
</div>
<div class="section register">
<form id="mail-cons" method="post" action="" enctype="multipart/form-data" >
<div class="step2">
<ul class="step-ul">
<h2>Asesoría vía correo electrónico</h2>
<?//Primul pas pt user, descrierea problemei
if(loggedtype()=='user' AND $data['user_description']==''){?>
<div class="step-message sys-info"><img class='small icon' src='<?=$url_base?>css/images/icons/information.png' alt=''/> <?=$lang['mc']['user_step1']?></div>
<div class="row mail-cnsl">
</div>
<div class="row">
<textarea id="descriere2 " name="descriere" class="tinymce" rows="20" cols="50" style="width: 554px; height: 517px;"><?php echo $_REQUEST["descriere"];?></textarea>
</div>
<div class="row submit mail-cnsl">
<input type="submit" name="submitdesc" value="Enviar solicitud!" />
</div>
<? } ?>
And this function for validation:
<script type="text/javascript">
function validate_required(field,alerttxt)
{
with (field)
{
if (value==null||value=="")
{
alert(alerttxt);return false;
}
else
{
return true;
}
}
}
function validate_form(thisform)
{
with (thisform)
{
if(window.clicked) return true;
if (validate_required(user_description_extra,"Por favor, introduzca el motivo del rechazo!")==false)
{user_description_extra.focus();return false;}
}
}
</script>
<script type="text/javascript">
function validate_length(f,a,l){
z=f.value;
x=z.length;
if (x<l){alert (a); f.focus(); return false;}
return true;
}
</script>
And this function for submit :
if(isset($_POST['submitdesc'])){
$upd = mysql_query("UPDATE discussion SET active='0' WHERE id='".$_GET['iddisc']."'") or die(mysql_error());
$sel = mysql_query("SELECT * FROM discussion WHERE id='".$_GET['iddisc']."'") or die(mysql_error());
$data = mysql_fetch_array($sel);
$upd_mc = mysql_query("UPDATE mail_counseling SET new_user=0, new_cons=1, user_description='".mysql_real_escape_string($_POST['descriere'])."' WHERE id_disc='".$_GET['iddisc']."'") or die(mysql_error());
//Notificari
if($_SESSION['loggedin']['type']=='user'){
$insid = $user['id_user'];
$type1 = 'user';
$type2 = 'client';
}else{
$insid = $cons['id_counselor'];
$type1 = 'consilier';
$type2 = 'counselor';
}
$insnotifs = mysql_query("INSERT INTO mc_notifs (type,id_user,message) VALUES ('".$_SESSION['loggedin']['type']."','".$insid."','".mysql_real_escape_string($message)."')") or die(mysql_error());
//End Notificari
//Send notification mail
$query_tpl_mail = "SELECT * FROM mails WHERE id_mails='6'";
$tpl_mail = mysql_query($query_tpl_mail, $conn) or die(mysql_error());
$row_tpl_mail = mysql_fetch_assoc($tpl_mail);
$subject = $row_tpl_mail['title_mail'.$lng_s_tb];
$message = $row_tpl_mail['description'.$lng_s_tb];
avertizare_mail($cons["email"],$subject,$lang['mc']['notif1']);
avertizare_mail($user["email"],$subject,$lang['mc']['notif11']);
header("Location: ".$url_base."$tip_user-account/mail-counseling/ok/");
exit;
}
But don't work .Can I help my?
Do not rely on the client side validation. Turning off javascript may leave your form vulnerable. You must do this work in php more securely and easily.
if(isset($_POST['submitdesc'])){
$desc = htmlspecialchars(trim($_POST['descriere'])));
if(isset($desc)){
$upd = mysql_query("UPDATE discussion SET active='0' WHERE id='".$_GET['iddisc']."'") or die(mysql_error());
$sel = mysql_query("SELECT * FROM discussion WHERE id='".$_GET['iddisc']."'") or die(mysql_error());
$data = mysql_fetch_array($sel);
$upd_mc = mysql_query("UPDATE mail_counseling SET new_user=0, new_cons=1, user_description='".mysql_real_escape_string($_POST['descriere'])."' WHERE id_disc='".$_GET['iddisc']."'") or die(mysql_error());
//Notificari
if($_SESSION['loggedin']['type']=='user'){
$insid = $user['id_user'];
$type1 = 'user';
$type2 = 'client';
}else{
$insid = $cons['id_counselor'];
$type1 = 'consilier';
$type2 = 'counselor';
}
$insnotifs = mysql_query("INSERT INTO mc_notifs (type,id_user,message) VALUES ('".$_SESSION['loggedin']['type']."','".$insid."','".mysql_real_escape_string($message)."')") or die(mysql_error());
//End Notificari
//Send notification mail
$query_tpl_mail = "SELECT * FROM mails WHERE id_mails='6'";
$tpl_mail = mysql_query($query_tpl_mail, $conn) or die(mysql_error());
$row_tpl_mail = mysql_fetch_assoc($tpl_mail);
$subject = $row_tpl_mail['title_mail'.$lng_s_tb];
$message = $row_tpl_mail['description'.$lng_s_tb];
avertizare_mail($cons["email"],$subject,$lang['mc']['notif1']);
avertizare_mail($user["email"],$subject,$lang['mc']['notif11']);
header("Location: ".$url_base."$tip_user-account/mail-counseling/ok/");
exit;
}else{
?><script>alert('Empty text field is not allowed.')</script><?php
}
}

Autocomplete dynamic search SQL database from PHP

I have a search box where search is done through database. In the code I have, the search is done in one input box and the dynamic search output is shown in a text area below it.
What I want is a search like Google, where when the user stars typing, it should show similar items from the db table.
For example, if I have two organizations named "Dummy 1" and "Dummy 2" and the user types in "du", the search bar should show the 2 results and user should be able to select one.
The code I have is:
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
The js is like this:
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
This is the search.php file:
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%$searchq%'")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
//$output = echo "<option value='".$orgname."'>" . $orgname . "</option>";
$output = $orgname;
$output2 = $orgid;
$output3 = $subs;
//$output = '<div>'.$orgname.'</div>';
}
}
}
echo ($output);
?>
How can I achieve that?
In the JS code...
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#output").html(output);
}
}
</script>
you have given the id(#output) of a input type element to display(or to return) the HTML statements and the js script also not closed properly (syntax error).So the valid statement will be...
<form action="newbrand.php" method="post">
<br>
Brand Name: <input type="text" name="bname" /><br><br>
Search for an Organization: <input type="text" name="search" onkeyup="searchq()" id="output"><
Selected Organization:<textarea id="output"></textarea>
</form>
<br>
<div id="mydiv"></div>
<script type="text/javascript">
function searchq(){
var searchTxt = $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt},function(output){
$("#mydiv").html(output);
});
}
</script>
Just change your query :
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
And the query will work fine :)
Then output the response in HTML in your search.php (manage the css accordingly) :
<?php
include 'db_connect.php';
$link = mysqli_connect($host, $username, $password, $db);
if(!link){
echo "DB Connection error";
}
$output = '' ;
$output2 = '' ;
if (isset($_POST['searchVal'])){
$searchq = $_POST['searchVal'];
//$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($link, "SELECT * FROM `organisations_info` WHERE `Organisation_Name` LIKE '%".$searchq."%' ")or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output = '<div>No results!</div>';
}else{
while($row = mysqli_fetch_array($query)){
$orgname = $row['Organisation_Name'];
$orgid = $row['Organisation_Id'];
$subs = $row['Subscription_Type'];
?>
<div><?php echo $orgname; ?></div>';
<div><?php echo $orgid ; ?></div>';
<div><?php echo $subs ; ?></div>';
<?php
} // while
} // else
} // main if
?>
I hope this is what you required !!

Categories

Resources