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>';
Related
I'm just learning PHP and I'd like to do a basic login. Once logged in, I'd like to show basic information from the user (in this example, just the name), but for some reason I'm not getting the name printed. Could you help me please?
<?php
include "config.php";
// Session
if(!isset($_SESSION['uname'])){
header('Location: login.php');
}
// Logout
if(isset($_POST['but_logout'])){
session_destroy();
header('Location: login.php');
}
// CHECK THIS
$sql_query = "select * from users where username='".$uname."'";
$result = mysqli_query($con,$sql_query);
$row = mysqli_fetch_array($result);
?>
<!doctype html>
<html>
<head></head>
<body>
<form method='post' action="">
<h1>Dashboard</h1>
<div>
<!-- CHECK THIS -->
<h2>Hello <?php echo $row['name']; ?></h2>
</div>
<div>
<input type="submit" value="Logout" name="but_logout">
</div>
</form>
</body>
</html>
The login, logout and session are already working.
The table structure contains a table named users with the columns: id, username, password, name, email.
Thanks
$uname is undefinded
Try: $_SESSION['uname'] on line 14;
Alway u can debug this e.g. var_dump($sql_query) and execute it in phpmyadmin
And if you want use $row['name'], you must have assoc array: $row = mysqli_fetch_assoc($result);
this is a very basic example:
first of all you must to open a conection to your server and database, create a php file, lets call "CONEXION_DB.php" and add the next code:
<?php
function ConexionDBServer($DB_Con)
{
$servername = "your_server";
$username = "your_user";
$password = "your_password";
$conDB = mysqli_connect($servername, $username, $password);
if (!$conDB)
{
die('Could not connect: ' . mysqli_error());
return -1;
}
$DB = mysqli_select_db($conDB, $DB_Con);
if (!$DB)
{
echo "<SCRIPT LANGUAGE='javascript'>
alert('CONEXION WITH DB FAIL');
</SCRIPT>";
return -1;
}
return $conDB;
}
?>
now create your "main" page, lets call "main_page.php", and add:
<?php
echo "example mysql </br>";
?>
<!doctype html>
<html>
<head></head>
<body>
<form action="<?php echo $PHP_SELF?>" method="POST">
<input size=10 maxlength="150" type="text" name="txtUsuario">
<input type="submit" value="Login" name="cmdLogin">
</form>
<?php
if($_POST[txtUsuario])
{
$sql_query = "select * from users where username='" . $_POST[txtUsuario] . "'";
require_once('CONEXION_DB.php');
$con=ConexionDBServer("name_of_your_db");
$result = mysqli_query($con,$sql_query);
while($row = mysqli_fetch_array($result))
{
echo $row['username'] . "</br>";
}
mysqli_close($con);
}
?>
</body>
</html>
as you can see, in order to capture the input entry from your form, you must to use the $_POST method.
Please see my code below.
How can I return the control to the index.php to an executable statement after the closing form tag to display query results on index.php page rather than code shown toward the end of processData.php?
I have searched through Google, this forum and have not seen a solution? Those familiar with Fortran, Visual Basic would appreciate the return statement that can be used to go back to the calling routine. Is there a statement similar to return to hand over the control to the calling web page in PHP?
Code for index.php:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Report Summary</title>
</head>
<body>
<h1>Online Sales Report Demo
<br>
<br>
<form method="post" action="processData.php">
Enter Your Full Name:<input type="text" name= "author_name" />
<br>
Enter Your eMail Address:<input type="text" name= "author_email" />
<br>
<input type="submit" value="Submit">
</form>
**//Question - How to return the control to a statement after </form> tag to print values instead of processData.php**
</body>
</html>
Code for processData.php:
<?php
// define variables and set to empty values
$author = $email = "";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
//Next extract the data for further processing
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$author = test_input($_POST['author_name']);
$email = test_input($_POST['author_email']);
//Next echo the Values Stored
echo "<br>";
echo "<br>Your Name:".$author;
echo "<br>Your Email Address:".$email;
}
?>
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('mydatabase');
$sql = "SELECT Sales_Author, Sales_Date, Sales_Channel, Sales_Title, Sales_Unit, Sales_Royalty, Sales_Currency
FROM Sales_tbl
WHERE Sales_Email= '" . $email . "' ORDER BY Sales_Date ASC";
$result = mysql_query( $sql, $conn );
if(!$result )
{
die('Could not fetch: ' . mysql_error());
}
?>
<table border="2" style="background-color: #84ed86; color: #761a9b; margin: 0 auto;">
<thead> <tr> <th>Date</th><th>Channel</th><th>Title</th><th>Units</th><th>Royalty</th><th>Currency</th></tr></thead><tbody>
<?php
while($row = mysql_fetch_assoc($result)){
echo "<tr>
<td>{$row['Sales_Date']}</td>
<td>{$row['Sales_Channel']}</td>
<td>{$row['Sales_Title']}</td>
<td>{$row['Sales_Unit']}</td>
<td>{$row['Sales_Royalty']}</td>
<td>{$row['Sales_Currency']}</td>
</tr>\n"; }
?>
</tbody></table>
<?php
mysql_close($conn);
echo "Fetched data successfully\n";
?>
</body>
</html>
If I take your question literaly this is one possibility:
In processData.php put that link where ever you want it to be:
back to index.php
then you can react on that parameter in index.php:
....
<input type="submit" value="Submit">
</form>
//Question - How to return the control to a statement after </form> tag to print values instead of processData.php**
<?php
if(isset($_GET['state'])) {
switch($_GET['state']) {
case "fromProcess":
echo "I come from process!";
// do whatever you want to do
break;
default:
echo "ERROR: undefined state submitted";
}
}
?>
</body>
</html>
There's of course also the possibility to redirect without clicking a link via
header("location: index.php?state=fromProcess");
// NOTE: This has to be before ANY output, and no output after that will be seen.
But I have the feeling, that you actually want to display data generated from processData in index.html.
Then you got at least two possibilities:
Include processData.php in index.php and wrap it in a
<?php
if(isset($_POST['author_name'])) {
include('processData.php');
// process the data and make output
}
?>
Same is possible the other way round (but that's kinda tricky for what you want to do).
One general thing you have to keep in mind:
php scripts are scripts, basicly all on their own.
They are out of memory once they finished executing, so you cannot call a function of another script unless you include it into the current script (without autoload - but that not what you want).
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>
I want to display all my textarea inputs in my browser (because if I refresh my page all data is gone from what i have sent through my html form using jquery/ajax ). So currently using jquery/ajax information from homepage.php is being sent to data.php through my #textarea input and returned on success to be displayed is my #status div. Every time i hit the POST button the data is added to the browser but when I refresh the page data is all lost ( even though the information is stored in my sql table). I understand i need to use a while() loop and I have tried but none of my code works in respect to what I am trying to achieve.
Homepage.php
<?php
include("connection.php");
session_start();
if(isset($_SESSION['user_id']) && $_SESSION['user_id'] != "") {
$sid = $_SESSION['user_id'];
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
$sql = "SELECT * FROM `users` WHERE id='{$sid}'";
$query = $conn->query($sql);
$result = $query->fetch_assoc();
$fname = $result['fname'];
$lname = $result['lname'];
$time = time();
}
else {
header("location:login.php");
}
?>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
//daddy code
$ (document).ready(function() {
//mama code
$("button#postbutton").click(function() {
var data = $("#formpost").serialize();
var posterid = <?php echo $sid; ?>;
$.ajax({
type: "POST",
url: "data.php",
data: data,
success: function(data) {
$("#statustext").append(data);
$("textarea#text1").val('');
}
});
});
});
</script>
</head>
<body>
<div id="global">
<form id="formpost" action="" method="post" onsubmit="return false">
<textarea id="text1" name="status" value="" ></textarea>
<button id="postbutton">POST</button>
LOGOUT
</form>
<br/>
<br/>
<div id="allstatus">
<!-- SKELETON -->
<div id="wholestatus">
<div id="statuspic">
</div>
<div id="statusinfo">
<div id="statusname"><?php echo " Welcome to VLE, {$fname} {$lname} ";?></div>
<div id="statustext"> </div>
</div>
</div>
<!-- SKELETON -->
</div>
</div>
</body>
</html>
data.php
<?php
const DB_HOST = 'localhost';
const DB_USER = 'root';
const DB_PASS = '';
const DB_NAME = 'forum';
//connecting
$conn = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if($conn->connect_error) {
die("Connection Failed: " . $conn->connect_error);
} else {
}
if(isset($_POST['status']))
{
$var = $_POST['status'];
$sql = "INSERT INTO `question`(id, question) VALUES ('', '{$var}')";
$result = $conn->query($sql);
if($result) { }
else {
echo "failed: " . $conn->error;
}
echo "<br>{$var}";
}
?>
Your select is calling for a specific Session id but your insert is not storing anything inside id column.
I'm not sure why you keep talking about page refreshes if you're using ajax, because ajax allows you to send/retrieve data without a page refresh.
In your success function, anything that is returned is in your variable called data, but I bet if you looked at the contents of this variable you will see that it doesn't have anything because your data.php is not setup to give a proper response.
You need this in your data.php file...
header('Content-Type: application/json');
And then when you echo the response, you need to do it like this...
echo json_encode($var);
Now within the success function your data will hold the contents of $var which is actually holding the contents of $_POST['status'].
So then within the success function you can display the results like this...
$('#statustext').html(data)
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']);
}
}
`