Search and display the result in the same page - php

I have small doubt in PHP coding, please help me. Actually I am displaying jobs currently, after searching,the result will displayed in the same page. It is done, but the result is displaying below the content. What I have to do to display only results in that page? I want to make unavailable the previous contents.This is the code:
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
</body>
</html>
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST,USER,PASS,DB) or die("Unable to connect to db");
$selQ = "Select * from jobpostings";
$res1 = mysqli_query($con, $selQ);
while($row = mysqli_fetch_array($res1))
echo $row[3]."<br> Job Id:<b>".$row[2]."</b><br><b>".$row[1]."</b>"."
<br>"."Exp:".$row[5]."<br>"."Location:".$row[6]."<br>".$row[8]."<br><br>";
if(isset($_POST["btn"])){
$query=$_POST['txt'];
$query=htmlspecialchars($query);
$query=mysqli_real_escape_string($con,$query);
$raw_results="select * from jobpostings where (C_name like '%" .$query."%')
or (Job_title like '%".$query."%')";
$final_results=mysqli_query($con,$raw_results);
if(mysqli_num_rows($final_results)>0){
while($results=mysqli_fetch_array($final_results)){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]
<br>".$results[3]."</p>";
}
}
else{
echo '<b style="color:red;">No results found</b>';
}
}
?>
Thanks in advance

Take the whole php code inside <body> and put if conditions to show either of sections. Like this:
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<?php if(!isset($_POST["btn"]))
{ ?>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
<?php }
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST,USER,PASS,DB) or die("Unable to connect to db");
$selQ = "Select * from jobpostings";
$res1 = mysqli_query($con, $selQ);
while($row = mysqli_fetch_array($res1))
echo $row[3]."<br> Job Id:<b>".$row[2]."</b><br><b>".$row[1]."</b>"."
<br>"."Exp:".$row[5]."<br>"."Location:".$row[6]."<br>".$row[8]."<br><br>";
if(isset($_POST["btn"])){
$query=$_POST['txt'];
$query=htmlspecialchars($query);
$query=mysqli_real_escape_string($con,$query);
$raw_results="select * from jobpostings where (C_name like '%" .$query."%')
or (Job_title like '%".$query."%')";
$final_results=mysqli_query($con,$raw_results);
if(mysqli_num_rows($final_results)>0){
while($results=mysqli_fetch_array($final_results)){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]
<br>".$results[3]."</p>";
}
}
else{
echo '<b style="color:red;">No results found</b>';
}
}
?>
</body>
</html>

Here is the modified code:
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST,USER,PASS,DB) or die("Unable to connect to db");
$final_results = null;
if(isset($_POST["btn"])){
$query=$_POST['txt'];
$query=htmlspecialchars($query);
$query=mysqli_real_escape_string($con,$query);
$raw_results="select * from jobpostings where (C_name like '%" .$query."%') or (Job_title like '%".$query."%')";
$final_results=mysqli_query($con,$raw_results);
}
?>
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
<?php
if(!is_null($final_results) && mysqli_num_rows($final_results)>0){
while($results=mysqli_fetch_array($final_results)){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]."<br>".$results[3]."</p>";
}
}else{
echo '<b style="color:red;">No results found</b>';
}
$selQ = "Select * from jobpostings";
$res1 = mysqli_query($con, $selQ);
while($row = mysqli_fetch_array($res1))
echo $row[3]."<br> Job Id:<b>".$row[2]."</b><br><b>".$row[1]."</b>"."
<br>"."Exp:".$row[5]."<br>"."Location:".$row[6]."<br>".$row[8]."<br><br>";
?>
</body>
</html>
I didn't test this code, please confirm it works fine.
Also ALWAYS start php code before <html> tag and everything you have to be print must be within <body> tag

1) I would suggest you not to create 2 SQL query (one without search and one with search). You can make one query and append where clause according to the search.
2) "..but the result is displaying below the content." => Wrap all the contents inside <body> tag.
Updated Code
<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST, USER, PASS, DB) or die("Unable to connect to db");
$where = "";
$searched = false;
if (isset($_POST["btn"]) && isset($_POST['txt'])) {
$searched = true;
$txt = htmlspecialchars($_POST['txt']);
$txt = mysqli_real_escape_string($con, $txt);
$where = "WHERE (C_name like '%" .$txt. "%') or (Job_title like '%" .$txt. "%')";
}
$raw_results = "SELECT * FROM `jobpostings` ".$where;
$final_results = mysqli_query($con, $raw_results);
if (mysqli_num_rows($final_results) > 0) {
while ($results = mysqli_fetch_array($final_results)) {
if(!$searched){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]."<br>".$results[3]."</p>";
} else {
echo $results[3] . "<br> Job Id:<b>" . $results[2] . "</b><br><b>" . $results[1] . "</b>" . "<br>" . "Exp:" . $results[5] . "<br>" . "Location:" . $results[6] . "<br>" . $results[8] . "<br><br>";
}
}
} else {
echo '<b style="color:red;">No results found</b>';
}?>
</body>
</html>
Note: Use Prepared Statements to avoid SQL Injections

<html>
<head>
<title>Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<h2>Job Openings</h2>
<form method="POST" action="jobopenings.php">
<input type="text" name="txt" required />
<input type="submit" name="btn" value="search" /><br/>
</form>
<?php
define('HOST', 'localhost');
define('USER', 'root');
define('PASS', '');
define('DB', '*****');
$con = mysqli_connect(HOST,USER,PASS,DB) or die("Unable to connect to db");
if(isset($_POST["btn"])){
$query=$_POST['txt'];
$query=htmlspecialchars($query);
$query=mysqli_real_escape_string($con,$query);
$raw_results="select * from jobpostings where (C_name like '%" .$query."%')
or (Job_title like '%".$query."%')";
$final_results=mysqli_query($con,$raw_results);
if(mysqli_num_rows($final_results)>0){
while($results=mysqli_fetch_array($final_results)){
echo "<p><b>".$results[1]."</b><br> Job Id:".$results[2]
<br>".$results[3]."</p>";
}
}
else{
echo '<b style="color:red;">No results found</b>';
}
}
else{
$selQ = "Select * from jobpostings";
$res1 = mysqli_query($con, $selQ);
while($row = mysqli_fetch_array($res1))
echo $row[3]."<br> Job Id:<b>".$row[2]."</b><br><b>".$row[1]."</b>"."
<br>"."Exp:".$row[5]."<br>"."Location:".$row[6]."<br>".$row[8]."<br><br>";}
?>
</body>
</html>

Related

PHP: Simple PostgreSQL Query

I am trying to realize a most simple way to query a postgreSQL db via a web site form. My current approach is the following, which results in a broken looking page (even the print command is ignored) and not reacting to submitting the values, i.e., not producing any output.
Could you give me a clue what is wrong with the code?
<!DOCTYPE html>
<head>
<title>Insert data to PostgreSQL with php - creating a simple web application</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
li {listt-style: none;}
</style>
</head>
<body>
<h2>Enter Query</h2>
<ul>
<form name="insert" action="pg.html" method="POST" >
<li>RA:</li><li><input type="text" name="ra" /></li>
<li>Dec:</li><li><input type="text" name="dec" /></li>
<li>Radius:</li><li><input type="text" name="radius" /></li>
<li><input type="submit" /></li>
</form>
</ul>
<?php
$servername = "localhost";
$username = "foo";
$password = "bar";
$dbname = "foobar";
print "bla $dbname";
// Create connection
$conn = pg_connect("host=$servername user=$username, password=$password dbname=$dbname");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM foobar WHERE q3c_radial_query(RAJ2000, DECJ2000, ra, dec, radius)";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "RA: " . $row["RAJ2000"]. ", DEC: " . $row["DECJ2000"]. ", r" . $row["rmag"]. "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
</body>
</html>

mysqli_row_nums didn't work when query was given

I am creating a login page using PHP and Mysqli database, I wrote the query, however mysqli_num_rows() give me an error when value is given. PS: I did this in Object Oriented Format
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db = "customerdb";
$connection = #new mysqli($host, $user, $pass, $db);
if ($connection->connect_errno) {
die("Connection failed!");
exit();
}
if (isset($_POST['submit'])) {
$username = $connection->real_escape_string($_POST['username']);
$password = $connection->real_escape_string($_POST['password']);
$script = "SELECT * FROM customer_management WHERE
customer_management.Username='".$username."'AND WHERE customer_management_Password='".$password."'";
$result = $connection->query($script, MYSQLI_USE_RESULT);
$check = $result->num_rows;
if ($check >= 1){
echo "Welcome to this website";
}
else{
echo"Sorry but your input is incorrect!";
}
}
?>
<!DCOTYPE html>
<html lang='en'>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Login Page</title>
</head>
<body>
<h1>Login Page</h1>
<form method="post" action="login.php">
<input type="text" placeholder = 'username' name="username" /><br /><br />
<input type="password" placeholder="password" name="password" /><br /><br />
<input type="submit" name="submit" value="Log In" />
</form>
</body>
</html>
Change customer_management_Password to customer_management.Password in your query.

How to retrieve and show BLOB Image from database?

I am trying to insert and retrieve image from database. All is going well and image is being inserted in database in BLOB format, but when I am trying to retrieve those images it does not appear and only broken icon comes to webpage. The code is given below. Please help.
ImageUpload.php
<?php
if(count($_FILES) > 0) {
if(is_uploaded_file($_FILES['userImage']['tmp_name'])) {
mysql_connect("localhost", "root", "");
mysql_select_db ("connection");
$imgData =addslashes(file_get_contents($_FILES['userImage']['tmp_name']));
$imageProperties = getimageSize($_FILES['userImage']['tmp_name']);
$sql = "INSERT INTO output_images(imageType ,imageData)
VALUES('{$imageProperties['mime']}', '{$imgData}')";
$current_id = mysql_query($sql) or die("<b>Error:</b> Problem on Image Insert<br/>" . mysql_error());
if(isset($current_id)) {
header("Location: listImages.php");
}
}
}
?>
<HTML>
<HEAD>
<TITLE>Upload Image to MySQL BLOB</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<form name="frmImage" enctype="multipart/form-data" action="" method="post" class="frmImageUpload">
<label>Upload Image File:</label><br/>
<input name="userImage" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" />
</form>
</div>
</BODY>
</HTML>
ListImages.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("connection");
$sql = "SELECT imageId FROM output_images ORDER BY imageId DESC";
$result = mysql_query($sql);
?>
<HTML>
<HEAD>
<TITLE>List BLOB Images</TITLE>
<link href="imageStyles.css" rel="stylesheet" type="text/css" />
</HEAD>
<BODY>
<?php
while($row = mysql_fetch_array($result)) {
?>
<img src="imageView.php?image_id=<?php echo $row["imageId"]; ?>" /><br/>
<?php
}
mysql_close($conn);
?>
</BODY>
</HTML>
imageView.php
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("connection") or die(mysql_error());
if(isset($_GET['image_id'])) {
$sql = "SELECT imageType,imageData FROM output_images WHERE imageId=" . $_GET['image_id'];
$result = mysql_query("$sql") or die("<b>Error:</b> Problem on Retrieving Image BLOB<br/>" . mysql_error());
$row = mysql_fetch_array($result);
header("Content-type: " . $row["imageType"]);
echo $row["imageData"];
}
mysql_close($conn);
?>

Cannot get session value with php

i'm sending session values from my first.php and trying to get from my second.php. I have done some reading about this, and works fine on my localhost, but on my server doesn't work at all.
Here is the code from my first.php file:
<?php
session_start();
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="http://localhost/Shopping_biblioteka/css/style.css">
<title></title>
</head>
<body align="center">
<div id="login">
<?php
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
mysql_connect("localhost", "shopping_katalog", "logik#112233") or die(mysql_error());
mysql_select_db("shopping_katalog") or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES utf8");
$result = mysql_query("SELECT password,id FROM x9qg6_users
where username='" . $username . "'");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$row = mysql_fetch_row($result);
$userhash = md5($password . $test[1]);
if ($test[0] === $userhash) {
$_SESSION['login_user'] = $user_id;
$_SESSION['username'] = $username;
$url = "biblioteka.php";
header("Location: $url");
}
} else {
echo 'Внесете ги вашите податоци во полињата!';
}
?>
<form action="" method="POST" accept-charset="UTF-8">
Корисничко име:<br/>
<input name="username" id="username" type="text"/><br/>
Лозинка:<br/>
<input type="password" id="password" name="password"/><br/>
<input type="submit" value="Логирај се!"/>
</form>
</div>
</body>
</html>
And here is my second.php file:
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="http://localhost/Shopping_biblioteka/css/style.css">
<title>Библиотека на</title>
</head>
<body>
<div id="wrapper">
<?php
$user_ID = $_SESSION['login_user'];
$logged_user = $_SESSION['username'];
?>
<h1 align="center" id="b_welcome">Добредојде <?php echo $logged_user; ?> во твојата библиотека! </h1>
<h4 align="center" id="b_info">Во твојата библиотека ги имаш следниве книги</h4>
<div id="knigi">
<?php
/* OVA E QUERITO
*
SELECT *
FROM Knigi k, poracki p
WHERE k.knigaid = p.kniga
AND p.korisnikInt = $user_ID
*
*/
//-----------------------------------
if(isset($_SESSION['login_user'])){
mysql_connect("localhost", "user", "pass) or die(mysql_error());
mysql_select_db("shopping_katalog") or die(mysql_error());
mysql_query("SET CHARACTER SET utf8");
mysql_query("SET NAMES utf8");
$result = mysql_query("SELECT * FROM Knigi k, poracki p
WHERE k.knigaid = p.kniga AND p.korisnikInt ='" . $user_ID . "'");
while ($row = mysql_fetch_array($result)) {
//knigaid,naslov,avtor,link_do_pdf,thumb_link,kategorija,cena,br_strani
echo '<div id="item">';
echo '<h5 align="center" id="b_item_title">' . $row['naslov'] . '</h5>';
//echo '' . $row['avtor'] . '';
echo '<img src="http://' . $row['thumb_link'] . '" id="b_item_slika" />';
echo '</div>';
}
if (!$result) {
echo 'Проблем со добивање на податоците: ' . mysql_error();
exit;
}
}else{
$url = "/index.php";
header("Location: $url");
}
?>
</div><!--kraj na knigite-->
</div>
</body>
</html>
Here is the concept:
in you first_page.php the user should enter his username and password and if you find them both are correct and match those exist in the database, then you will set a session and store whatever data you want in it, then you will redirect the user to the second_page.php which will use those session stored values to do whatever you want with them. And if the user didn't enter his username and password he will stay in the first_page.php
And here is a simple example from which you can take the main concept and apply it on your case:
in first_page.php
<?php
session_start();
ob_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body align="center">
<div>
<?php
if (!empty($_POST["username"]) && !empty($_POST["password"])) {
$_SESSION['username'] = $_POST["username"];
header("Location: second_page.php");
}
?>
<form action="first_page.php" method="post" accept-charset="UTF-8">
Username: <input type="text" name="username" /><br/>
Password: <input type="password" name="password"/><br/>
<input type="submit" value="Login"/>
</form>
</div>
</body>
</html>
And in second_page.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title></title>
</head>
<body>
<h3>Welcome <?php echo $_SESSION["username"] ?></h3>
</body>
</html>
To check if cookies are enabled or not, use the code...
<?php
setcookie('test', 1, time()+3600);
if(!isset($_GET['cookies'])){
header('Location:/info.php?cookies=true');
}
if(count($_COOKIE) > 0){
echo "Cookies are Enabled!";
} else {
echo "Disabled";
}
?>

I have a php form dropdown menu that needs to send information

I have a dropdown menu that is filled by a mysql database. I need to select one and have it send the information for use on the next page after clicking submit. It does populate the drop down menu like it is supposed to it just does not seem to catch the data on the next page. Here is what I have:
removeMain.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<form action="remove.php" method="post">
<?php
$link = mysql_connect('********', '********', '*********');
if (!$link){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("********", $link);
$res = mysql_query("SELECT * FROM cardLists order by cardID") or die(mysql_error());
echo "<select name = CardID>";
while($row=mysql_fetch_assoc($res)) {
echo "<option value=$row[ID]>$row[cardID]</a></option>";
}
echo "</select>";
?>
Amount to Remove: <input type="text" name="Remove" />
<input type="submit" />
</form>
<body>
</body>
</html>
remove.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>
<body>
<?php
$link = mysql_connect('*********', '*********', '*********');
if (!$link){
die('Could not connect: ' . mysql_error());
}
mysql_select_db("***********y", $link);
$query = sprintf("UPDATE cardLists SET AmountLeft = AmountLeft - %s WHERE cardID = '%s'", mysql_real_escape_string($_POST["Remove"]), mysql_real_escape_string($_POST["CardID"]));
mysql_query($query);
mysql_close($link);
?>
<br />
<input type="submit" name="return" id="return" value="Update More" />
<input type="submit" name="main" id="main" value="Return To Main" />
</body>
</html>
while($row=mysql_fetch_assoc($res)) {
echo "<option value=$row[ID]>$row[cardID]</a></option>";
}
echo "<option value=$row[ID]>$row[cardID]</a></option>"; should be
echo "<option value=$row[ID]>$row[cardID]</option>";
dont know if that solves your problem, but it was the first thing i noticed
echo "<select name = CardID>";
should be:
echo "<select name = \"CardID\">";

Categories