display multiple results from a sql query - php

so I am trying to display multiple results from a database when a query is searched, the query is passed from a search box on another page.
I have it displaying one result, but that is all it will display.
I need it to display all the results that are relevant to the search query.
the php code is below
<meta charset="UTF-8">
<?php
$mysqli = new mysqli('localhost', 'scott', 'tiger','courses');
if ($mysqli->connect_errno)
{
die('Database connection failed');
}
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
$search_result = $result->fetch_assoc();
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<h3><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
</body>
and the code for the search bar
<!doctype html>
<html>
<Head>
<meta charset = "utf-8">
<title>Search</title>
</head>
<body>
<h2>Search</h2>
<form name="search" method="post" action="SearchResultsPage.php">
<input name="searchBar" type="text" size="40" maxlength="60" />
<input type="submit" name="Submitsearch" value="Search" />
</form>
</body>
Does anyone have any suggestions?
Thanks in advance;

You will need to place it in a while loop to show multiple results, the fetch function you're using will only retrieve one row, if you place it in a loop you can keep fetching until there is nothing to fetch:
//$m->set_charset('utf8');
$search_sql = "
SELECT title, summary, id
FROM course
WHERE title LIKE '%".$_POST['searchBar']."%'";
$result = $mysqli->query($search_sql) or die($mysqli->error);
?>
<!doctype html>
<head>
<meta charset="utf-8">
<h1>Search Results</h1>
</head>
<body>
<?PHP while($search_result = $result->fetch_assoc()) { ?>
<h1><?= $search_result['title'] ?></h1>
<p><?= $search_result['summary'] ?></p>
<?PHP } ?>
</body>
P.S. your code is vulnerable to SQL injection, you should read about prepared statements. More Info on that

You can iterate over your query results with a while loop. To complete the example I added the necessary data cleaning.
<?php
// function to clean post data
function cleanPost(&$value) {
if (is_array($value)) {
foreach ($value as $k => $v) {
$value[$k] = cleanPost($v);
}
return $value;
}
else {
$value = mysql_real_escape_string($value);
return trim(htmlentities(strip_tags($value)));
}
}
// search function
function search() {
// check if post data is set
if (isset($_POST['searchBar'])) {
// make link with db
$link = mysqli_connect('localhost', 'scott', 'tiger','courses');
if (!$link)
return false;
}
// clean your post data
$cleanPostData = cleanPost($_POST);
// query
$sql = "SELECT title, summary, id FROM course WHERE title LIKE '%".$cleanPostData['searchBar']."%'";
$result = mysqli_query($link, $sql);
// iterate over results
if (isset($result) && mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
// here is your data
echo $row['title'] . "< br/>";
echo $row['summary'] . "< br/>";
echo $row['id'] . "< br/>";
}
}
}
}
// call search function
search();
?>

Related

PHP click count with mysqli

I want to make a program what will count clicks after click button.
I have this code but it don't work. I use mysqli to connect to database and I use query to insert value to database and query to select from database.
<html>
<head>
<meta charset="UTF-8">
<title>Click</title>
</head>
<body>
<form action="#" method="post">
<input type="submit" name="click" value="Klikni mě">
<br>
<?php
if(isset($_POST["click"])){
$connection=new mysqli("hidden","hidden","hidden","hidden");
if($connection == false){
die("Sorry jako");
}
$query="INSERT INTO klik (klikcount) VALUES ('$klik')";
if($connection->query($query) == false){
die("Promiň");
}
$sql="SELECT klikcount FROM klik";
$result=$connection->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
echo $row["klikcount"];
}
}
$klik=$klik+1;
}
?>
</form>
</body>
</html>
thanks.
I try solve your code and I made some changes.
Change position of "$klik = $klik+1;"
Add another SELECT
My new code:
<html>
<head>
<meta charset="UTF-8">
<title>Click</title>
</head>
<body>
<form action="#" method="post">
<input type="submit" name="click" value="Klikni mě">
<br>
<?php
if(isset($_POST["click"])) {
$connection = new mysqli("hidden","hidden","hidden","hidden");
if($connection == false) {
die("Sorry jako");
}
$sql="SELECT klikcount FROM klik";
$result=$connection->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()){
$klik = $row["klikcount"];
}
}
$klik = $klik+1;
$query = "INSERT INTO klik (klikcount) VALUES ('$klik')";
if($connection->query($query) == false) {
die("Promiň");
}
$sql = "SELECT klikcount FROM klik";
$result = $connection->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo $row["klikcount"];
}
}
}
?>
</form>
</body>
</html>

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>

checking result from select query then compare to current value if available then should not insert

I am saving latlong with the help of geolocation api into mysql db but problem is same latlong are inserted in database.I am trying to check last row of my mysql table and then comparing with current latlong if both are same,it should not be executed.Please help me to get this..Thanks in advance.
$latitude = 19.1579;
$longitude = 72.9935;
$address = airoli;
$sql = "SELECT latitude FROM tracklatlong ORDER BY id DESC LIMIT 1";
$result = mysqli_query($sql, $conn);
$row = mysqli_fetch_array($result);
$currentlat = $_row["latitude"];
if($currentlat != $latitude){
$query = "INSERT INTO `tracklatlong` (latitude, longitude,address) VALUES ('$latitude','$longitude','$address')";
if($conn->query($query) === TRUE){
echo "success";
}
else{
echo "failed";
}
}
else{
echo"Already exists";
}
As understood you need to check weather the latitute or longitute is in database Table insert it only if found false.
I am using PHP Object oriented with mysqli prepared statements.
This code returns false only when both latitute and longitute are same.
if you want output to return false were any one matchs the output than just add OR operator in SELECT query.
Here is the table image with data
Here is html code :index.php
<?php
include('co_ordinate.php');
$newcoordinate = new co_ordinate();
?>
<!DOCTYPE html>
<html>
<head>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-md-6 col-md-offset-3" style="margin-top:100px;">
<form action="" method="post">
<div class="form-group">
<i>Add Latitute</i>
<input type="text" name="latitute" class="form-control">
</div>
<div class="form-group">
<i>Add Longitute</i>
<input type="text" name="longitute" class="form-control">
</div>
<div class="form-group">
<input type="submit" name="addcoordinate" class="btn btn-primary">
</div>
</form>
<?php
if(isset($_POST['addcoordinate'])){
$latitude = $_POST['latitute'];
$longitute = $_POST['longitute'];
$newcoordinate->getCo_ordinates($latitude,$longitute);
}
?>
</div>
</body>
</html>
Here is the class file :co_ordinate.php
<?php
class co_ordinate{
private $link;
function __construct(){
$this->link = new mysqli ('localhost','root','','example');
if(mysqli_connect_errno()){
die("connection Failed".mysqli_connect_errno());
}
}
function getCo_ordinates($latitude,$longitute){
$sql = $this->link->stmt_init();
if($sql->prepare("SELECT latitude,longitude FROM tracklatlong WHERE latitude=? AND longitude= ?")){
$sql->bind_param('dd',$latitude,$longitute);
$sql->execute();
$sql->store_result();
if($sql->num_rows > 0){
echo "The Co-Ordinates Already Exists";
}
else
{
$query = $this->link->stmt_init();
if($query->prepare("INSERT INTO tracklatlong (latitude,longitude) VALUES (?,?)")){
$query->bind_param('dd',$latitude,$longitute);
$query->execute();
echo "The Co-Ordinates Inserted Successfully";
}
}
}
else
{
echo $this->link->error;
}
}
}
?>

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>

session variable keeps disappearing following selection

I have a value that I receive from another url from $_SESSION. It arrives glued together with a second value I needs as {$is:$user} or {2:bob}. I split them with they with explode and 'attempt' to assign them as $_SESSION['id'] = $pieces[0]; and $_SESSION['cust_name'] = $pieces[1];
The first time the process works prefect. the values are segmented and they go to the proper place.
But following my selected submit, I lose the value of $_SESSION['cust_name']
How can I retain the value of $_SESSION['cust_name'] following my selection?
<?php
session_start();
if(isset($_POST['SubmitForRedirect'])){
//store as session variable
$_SESSION['printdata'] = $_POST['bolredir'];
//forward browser
die(header("Location: add-job.php"));
}
require_once("header2.php");
//var_dump($_SESSION['id']);
//var_dump($_SESSION['cust_name']);
$cust_info = $_SESSION['id'];
$pieces = explode(":", $cust_info);
//if(isset($_SESSION['cust_name']))
$_SESSION['id'] = $pieces[0];
$_SESSION['cust_name'] = $pieces[1];
//else
//echo "Something died";
echo $pieces[0];
?><br /><?php
echo $pieces[1];
?>
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- <link href="style.css" rel="stylesheet" type="text/css" /> -->
<title> Contacts Database </title>
</head>
<body>
<h2> Select and existing job for: <?php echo $_SESSION['cust_name']; ?> with the ID of: <?php echo $_SESSION['id']; ?> and select print options</h2>
<?php
// selection box submit
try{
$conn = new PDO("mysql:host=localhost;dbname=$db", $user, $pass);
$stmt = $conn->prepare("SELECT * FROM customer INNER JOIN orders ON orders.cust_id = customer.id WHERE id =".$_SESSION['id']);
$stmt->execute();
$result = $stmt->fetchAll();
?>
<form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST">
<select name="bolredir">
<option></option>
<?php
foreach ($result as $item){
echo '<option value='.$item['cust_id'].'>';
echo ($item['ship_name'] .",". $item['ship_addr'] .",". $item['total_price'].",". $item['cust_id']."<br />\n");
echo '</option>';
}
}
catch (PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
?>
</select>
<input type="submit" name="SubmitForRedirect" value="Submit" />
</form>
</body>
You must put session_start() at the top of every page before any output if you wish to use sessions:
<?php
session_start();
require_once("header2.php");
It looks like you are overwriting $_SESSION['id'] on every request.
You would normally set this only once, upon signon.

Categories