edit search result on PHP - php

I am trying to allow admin side of my website to edit member detail.
I have created search for admin so s/he can search users via their name or surname,
and I want to have edit link for each search result that it will come back.
just to let you know I really don't know how to do it.
This is the code I have
<!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>search</title>
<script src="jquery.js"></script>
<script type="text/javascript">
function serachq ()
{
var searchTxt= $("input[name='search']").val();
$.post("search.php", {searchVal: searchTxt}, function(output){
$("#output").html(output);
});
}
</script>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="search for members..." onkeydown="serachq();"/>
<input type="submit" value=">>" />
<br/>
<br/>
<div id="output">
</div>
</body>
</html>
and this is PHP code
<?php require_once("db_connection.php"); ?>
<?php
$output="";
if (isset($_POST['searchVal']))
{
$searchq=$_POST['searchVal'];
$searchq= preg_replace("#[^0-9a-z]#i","",$searchq);
$query= mysql_query("SELECT * FROM member WHERE first_name LIKE '%$searchq%' OR last_name LIKE'%$searchq%'") or die ("could not search");
$count = mysql_num_rows($query);
if($count == 0){
$output="there was no serach results!";
}
else
{
while ($row= mysql_fetch_array($query))
{
$fname=$row ['first_name'];
$lname=$row['last_name'];
$id= $row['member_id'];
$output.='<div>'.$fname.' '.$lname.' '.$id.'Edit Subject </div>';
}
}
}
echo ($output);
?>

Really you need to write the question's better in the future. Specifically, if you are getting an error provide the error. If you expect a certian result, tell us what you get instead. That said the thing that stands out is:
<?php echo $query ['$id'];
Where I imagine you meant:
<?php echo $query[$id];
Here is that part of the code cleaned up:
while ($row = mysql_fetch_array($query))
{
$fname = $row['first_name'];
$lname = $row['last_name'];
$id = $row['member_id'];
$output .= "<div>{$fname} {$lname} {$id} Edit Subject</div>";
}

If i understand your question properly, you can do using session, put $searchq in session and when you come back you can make the query form session
if (isset($_POST['searchVal']) || isset($_SESSION['serachq'])) {
if (isset($_POST['searchVal'])) {
$searchq = $_POST['searchVal'];
$_SESSION['serachq'] = $searchq;
} else {
$searchq = $_SESSION['serachq'];
}
}
or you can modify your link add-member.php?edit=<?php echo $query ['$id']; ?>&q=<?php echo urlencode()?>
and your back url should have the &q=<?php echo urlencode()?> part too then
if (isset($_POST['searchVal']) || isset($_GET['q'])) {
if (isset($_POST['searchVal'])) {
$searchq = $_POST['searchVal'];
} else {
$searchq = urldecode($_GET['q']);
}
}
`

Related

PHP Search is not working

I don't understand what's the problem with the code. It is supposed to work. There is data in table but the search is still not producing any results. The Search bar remaining still and no changes before or, after entering any data in the search bar.
Here is the code :
<!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=iso-8859-1" />
<title>Search Example</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search" />
<input type="submit" value="submit" />
</form>
<?php
$con = mysqli_connect("localhost","root","") or die("Could not connect");
mysqli_select_db($con ,"project") or die(mysqli_error());
if(isset($_POST['search']))
{
$search =$_POST['search']; // searchq contains characters which is typed
in the search
$search = preg_replace("#[^0-9a-z]#i","",$search); //filtering the
conditions */
$query = mysqli_query($con, "SELECT * FROM admin WHERE name LIKE
'%$search%'");
//most important condition line for the search
$count = mysqli_num_rows($query); // To count the selected Rows
if($count==0)
{
echo"<h2>"."No Data Found"."</h2>";
}
else
{
while($row = mysqli_fetch_array($query))
{
echo "<tr>".
"<td>".$row['username'] ."</td>".
"<td>".$row['password'] ."</td>".
"</tr>";
}
}
}
?>
</body>
</html>
Database name is project and table name is admin with Id, username and password as columns.
Use like this
$query = mysqli_query($con, "SELECT * FROM `admin` WHERE `username` LIKE
'%{$search}%'");
Do it like this:
$query = mysqli_query($con, "SELECT * FROM admin WHERE name LIKE
'%{$search}%'");
By surrounding variable in {} you can specify that only $title is a variable and the double-quote string will ensure that this variable gets expanded to its value.

Page loading objects twice

The issue I'm experiencing is the code below seems to clone (duplicate) the form or any other HTML that loads on the page .
The first time I load the page the form appears as normal however when I type in the search text-box and delete all the characters the form displays twice (or any other HTML I place on the page)
How can it be possible to load the page without the form(s) or any other of the page contents repeated please?
<?php
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$q1 = mysqli_query($con, "SELECT * FROM tbl1 username");
$data = "";
// if the search is true
if(isset($_POST['search']))
{
//
$var = $_POST['search'];
if ($query = mysqli_query($con,"SELECT username FROMtbl1 WHERE username LIKE '%$var%'"))
{
// possible creating duplicate results
while($row = mysqli_fetch_array($query))
{
$data .= '<div>' . $row['username'] . '</div>';
}
echo $data;
}
}
else
{
}
?>
<HTML>
<head>
<script src="https://code.jquery.com/jquery-3.0.0.js" integrity="sha256-jrPLZ+8vDxt2FnE1zvZXCkCcebI/C8Dt5xyaQBjxQIo=" crossorigin="anonymous"></script>
<script>
$(function() {
$('.input').keyup(function() {
var a = $('.input').val();
$.post('livesusers.php', { "search": a }, function(data) {
$('#display').html(data);
});
});
});
</script>
</head>
<body>
// form to input text and search
<h1>Search For User</h1>
<form action= "livesusers.php" method='POST'>
<input type="text" name="search" class='input'>
</form>
<div id='display' style='margin-top: 100px'></div>
</body>
The problem is because you're making an AJAX request to the current page. The response of the request includes the PHP code as well as the HTML below it, hence the current page is cloned in its entirety. To fix this, simply place your PHP code in its own file and make the AJAX request to that location. Try this:
response.php (name this whatever you like)
<?php
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$q1 = mysqli_query($con, "SELECT * FROM tbl1 username");
$data = "";
// if the search is true
if(isset($_POST['search']))
{
//
$var = $_POST['search'];
if ($query = mysqli_query($con,"SELECT username FROMtbl1 WHERE username LIKE '%$var%'"))
{
// possible creating duplicate results
while($row = mysqli_fetch_array($query))
{
$data .= '<div>' . $row['username'] . '</div>';
}
echo $data;
}
}
else
{
}
?>
display.php
<!DOCTYPE HTML>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.0.0.js" integrity="sha256-jrPLZ+8vDxt2FnE1zvZXCkCcebI/C8Dt5xyaQBjxQIo=" crossorigin="anonymous"></script>
<script>
$(function() {
$('.input').keyup(function() {
var a = $('.input').val();
// change the page name below as required...
$.post('response.php', { "search": a }, function(data) {
$('#display').html(data);
});
});
});
</script>
</head>
<body>
<h1>Search For User</h1>
<form action= "livesusers.php" method='POST'>
<input type="text" name="search" class='input'>
</form>
<div id='display' style='margin-top: 100px'></div>
</body>
</html>
To make this even more robust you should consider changing your PHP code to return JSON instead of an unencoded string. See this question for a demonstration of how to do that.
The following code has an issue, it's adding data to itself twice!
$data .= $data . '<div>' . $row['username'] . '</div>';
Try this instead
$data .= '<div>' . $row['username'] . '</div>';

Display php result after html

I have a form where people can search the database for a certain user. When they search for the user and click submit, they're re-directed to a different page and the results are displayed.
My only issue is that the results are being displayed before the required html tags - here's an example of what the page looks like through Inspect Element:
"Bobby123
"
<!DOCTYPE html>
<html>
<body>
</body>
</html>
How do I display the results AFTER the required html tags? How do I set a "set place" for the results to be displayed?
Here's my code:
<?php
if(isset($_POST['submit'])) {
$term = $_POST['search'];
$searchuser = $stmt = $con->prepare("SELECT * FROM users WHERE username LIKE :term");
$stmt->bindValue(':term', '%'.$term.'%');
$stmt->execute();
if($searchuser->rowCount() > 0) {
while($row = $searchuser->fetch()){
$name = $row['username'];
echo $name;
}
}else{
echo 'No results';
}
}
?>
<form method="post" action="results.php">
<input name="search" type="search">
<input type="submit" name="submit">
</form>
The code on results.php simply is:
<!DOCTYPE html>
<html>
<body>
</html>
If possible, I would not like to use coding like Javascript, Jquery, or anything that is run on the client side.
Instead of
if($searchuser->rowCount() > 0) {
while($row = $searchuser->fetch()){
$name = $row['username'];
echo $name;
}}else{
echo 'No results';
}
}
use
if($searchuser->rowCount() > 0) {
$content = "";
while($row = $searchuser->fetch()){
$content .= '<p>' . $row['username'] . '</p>';
}
}else{
$content = 'No results';
}
Then, in your HTML (where you want the text to display)
<HTML>
<BODY>
<?PHP echo $content; ?>
</BODY>
</HTML>

mysql php search engine displaying nothing

im just playing around when creating a mini search engine, i have results in my sql database, i have added the corrent host user and password with the correct db selected, but when i search something on the site i just get nothing, just a white screen with the search bar at the top. I am not even getting an error saying nothing could be found in the data base?
If i enter the wrong details i get an error, so i know the details are correct.
Any ideas?
<!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>Search Engine - Search</title>
<body>
<h2>Search Engine</h2>
<form action='./search.php' method='get'>
<input type='text' name='k' size='50' value='<?php echo $_GET['k']; ?>' />
<input type='submit' value='Search'>
</form>
<hr />
<?php
$k = $_GET['k'];
$terms = explode(" ", $k);
$query = "SELECT * FROM search WHERE ";
foreach ($terms as $each){
$i++;
if ($i == 1)
$query .= "keywords LIKE '%$each%' ";
else
$query .= "OR keywords LIKE '%$each%' ";
}
//connect
mysql_connect('localhost', 'user', 'password');
mysql_select_db('search');
$query = mysql_query($query);
$numrows = mysql_num_rows($query);
if ($numrows > 0) {
while ($row = mysql_fetch_assoc($query)){
$url = $row['url'];
$title = $row['title'];
$keywords = $row['keywords'];
echo "<h1><a href='$url'>$title</a></h1>
$keywords<br /><br />";
}
}
?>
</body>
</head>

Facing an error when declaring session variables in index.php

I am having index.php page as follow which have a login form, that calls login.php page. It creates session values over there.
<?php
session_start();
$con=mysqli_connect("localhost","root","","sam");
if (mysqli_connect_errno($con))
{
echo "Could not connect " . mysqli_connect_error();
}
$id = $_SESSION["id"];
$user_login = $_SESSION["user_login"];
$password_login = $_SESSION["password_login"];
?>
<!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>Samsung Ops Guide</title>
<link href="css/index.css" rel="stylesheet" type="text/css" />
</head>
<body>
Tracker
<form action="login.php" method="post" id="login">
<input id="email" placeholder="T-ID" type="text" name="em" />
<input id="email" placeholder="Password" type="password" name="pwd"/>
<input id="loginButton" type="submit" value="Login" name="log" />
</form>
<div id="error1"></div>
</body>
</html>
<?php
if (isset($_SESSION["user_login"]) && isset($_SESSION["password_login"])) {
$query = mysqli_query($con,"select * from employees where Tid='$user_login' and password='$password_login'");
while($row = mysqli_fetch_array($query)){
$ptype = $row["designation"];
}
if($ptype=="agent")
{
header("location:/new/l1/");
}
if($ptype=="l2")
{
header("location:/new/l2/");
}
}
?>
Then having a login.php page which is called when the login form is called.
Login form calls and fetch values from the database and create session according to that.
login.php is as follows :
<?php
session_start();
include "inc_files/connection.php"; // it is only creating a connection with database nothing else
$user_login=$_POST['em'];
$password_login=$_POST['pwd'];
$password_login = md5($password_login);
if(empty($user_login) || empty($password_login))
{
die (retmsg(0,"Please fill T-ID and Password"));
}
$query = mysqli_query($con,"select * from employees where Tid='$user_login' and password='$password_login'");
$read = mysqli_num_rows($query);
if(!$read)
{
die (retmsg(0,"Incorrect T-ID or Password"));
}
else
{
while($row = mysqli_fetch_array($query)){
$id = $row["id"];
$ptype = $row["designation"];
}
$_SESSION["id"] = $id;
$_SESSION["user_login"] = $user_login;
$_SESSION["password_login"] = $password_login;
if (isset($_SESSION["user_login"]) && isset($_SESSION["password_login"]))
{
if ($ptype == "l1")
{echo retmsg(1,"l1");}
if ($ptype == "l2")
{echo retmsg(1,"l2");}
}
}
function retmsg($status,$txt)
{
return json_encode(array('status' => $status, 'txt' => $txt));
}
?>
i am getting an error that
$id = $_SESSION["id"];
$user_login = $_SESSION["user_login"];
$password_login = $_SESSION["password_login"];
are not defined. in index.php
Here, the session variables will be set only when you have logged in. At first time, they are not set and you are trying to access them in these lines (in index.php).
$id = $_SESSION["id"];
$user_login = $_SESSION["user_login"];
$password_login = $_SESSION["password_login"];
firstly you have to check whether they are set, and then access it like:
if(isset($_SESSION["id"]))
$id = $_SESSION["id"];
if(isset($_SESSION["user_login"]))
$user_login = $_SESSION["user_login"];
if(isset($_SESSION["password_login"]))
$password_login = $_SESSION["password_login"];
When you are using the same page for form submission, you can access
$user_login=$_POST['em'];
$password_login=$_POST['pwd'];
only if the form is submitted. ie, On page load the form won't be submitted, which means there won't be any POST variables in the page. So surely it will create problem (the same issue we have discussed above). So here, you have to make sure that the form variables are accessed only if the form is submitted. You can do it by the following lines,
if (!empty($_POST)) // if there are any posted variables
{
$user_login=$_POST['em'];
$password_login=$_POST['pwd'];
$password_login = md5($password_login);
..............................
}
Also make sure that you have added all the code for form submission inside this if condition.
I don't know the exact error. Let try with single quotes.
$id = $_SESSION['id'];
$user_login = $_SESSION['user_login'];
$password_login = $_SESSION['password_login'];**

Categories