My website search query is not working - php

On my website I have a file articles.php and on it I have a search field. When I enter the information it redirects me to my search.php which is correct and in the URL I can see it is outputting my result but it's not showing me my results on the search.php body.
The Localhost URL is outputting after I searched "Can you game on Windows visa"
http://localhost/qaa/search.php?search=Can+you+game+on+widows+vista&submit-search=
There is nothing on this page, just an empty box search.php
Connection
<?php
$server = "localhost";
$username = "root";
$password = "";
$db = "Qaa";
$conn = mysqli_connect($server, $username, $password, $db);
?>
articles.php "Where my search bar is located"
<?php
include 'connect.php';
?>
<h1>Front Page</h1>
<h2>All articles:</h2>
<link rel="stylesheet" type="text/css" href="css/article.css">
<div class="article-container">
<form action="search.php">
<input type="text" name="search" placeholder="Search">
<button type="submit" name="submit-search">Get answers</button>
</form>
<?php
$sql = "SELECT * FROM article";
$result = mysqli_query($conn, $sql);
$queryResults = mysqli_num_rows($result);
if ($queryResults > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='article-box'>
<h3>".$row['a_title']."</h3>
<p>".$row['a_text']."</p>
<hp>".$row['a_date']."</p>
<p>".$row['a_author']."</p>
</div>";
}
}
?>
Search.php "Where the search information should appear after click on 'Get answers button'"
<?php
include 'connect.php';
?>
<link rel="stylesheet" type="text/css" href="css/article.css">
<h1>Search Page</h1>
<div class="article-container">
<?php
if (isset($_POST['submit-search'])){
$search = mysqli_real_escape_string($conn, $_POST['search']);
$sql = "SELECT * FROM article WHERE a_title LIKE '%$search%' OR a_text
LIKE '%$search%' OR a_author LIKE '%$search%' OR a_date LIKE '%$search%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
echo "There are ".$queryResult." results!";
if($queryResult > 0){
while ($row = mysqli_fetch_assoc($result)){
echo "<div class='article-box'>
<h3>".$row['a_title']."</h3>
<p>".$row['a_text']."</p>
<hp>".$row['a_date']."</p>
<p>".$row['a_author']."</p>
</div>";
}
}else{
echo "There are no results matching your search! Contact our support so
we can add this or if you have a result, add it, as a result, using the
GIVE ANSWER button!";
}
}
?>
</div>

You are using $_POST['search'] Which is wrong. Because your search string is submitted in get method. So you must use:-
$_GET['search']
Please try this.

Related

Why will my input form not find a matching user to my search inside of my table?

I am trying to create a PHP search that looks through my table (users) and finds the user that matches the name they searched for and displays it on the screen. But the program won't display the user I searched up, and I don't know why. The variables all check out, and I didn't misspell anything in the code or table. My ifelse statement tells me that there is no query result, even though the user in the table and the user I searched are identical. I am using PHPMyAdmin to manage the tables and see changes (if there are any) to the table. The result I wanted was for the program to display the user and email on the page. I can't find a solution, so if you can please tell me!
addnone.php
<?php
include_once 'includes/db_connect.php';
?>
<!DOCTYPE html>
<html>
<head>
<title>SCIENCE FAIR</title>
<link rel="stylesheet" href="style.css">
<section class="container grey-text">
<form class="white" action="addnone.php" method="POST">
<tr>
<label>First Name:</label>
<td><input type="text" name="firstname" placeholder="First Name"></td></br>
</tr>
<div class="center">
<td colspan="2"><input type="submit" name="submit" value="Search"></td>
</div>
</form>
<div class="box">
<?php
if (isset($_POST['submit'])) {
$firstname = $_POST['firstname'];
$sql = "SELECT * FROM users WHERE name = '%$firstname%'";
$result = mysqli_query($conn, $sql);
$queryResult = mysqli_num_rows($result);
if ($queryResult > 0) {
while ($row = mysqli_fetch_assoc($result)) {
echo "<div>
<p>".$row['name']."<p>
<p>".$row['email']."<p>
</div>";
}
} else {
echo "No users with name $firstname!";
}
}
?>
</div>
</section>
</html>
db_connect.php
<?php
$dbServername = "localhost";
$dbUsername = "scifair";
$dbPassword = "password";
$dbName = "scifair";
// connect to database
$conn = mysqli_connect($dbServername, $dbUsername, $dbPassword, $dbName);
// check connection
if(!$conn){
echo 'Connection error: ' . mysqli_connect_error();
}
?>
Use "LIKE" Operator
$sql = "SELECT * FROM users WHERE name LIKE '%$firstname%'";

PhpStorm isset function not working?

<?php
$con=mysqli_connect("localhost","root","","ok_db")or die(mysqli_connect_error());
$output = 'arslan';
// collect
if (isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$query = mysqli_query($con,"SELECT * FROM user_data WHERE fname LIKE '%$searchq%'") or die("Could not search.");
$count = mysqli_num_rows($query);
if($count == 0) {
$output = 'No results found.';
} else {
while($row = mysqli_fetch_array($query)) {
$itemname = $row['fname'];
$description = $row['lname'];
$image = $row['id'];
$output .= '<div>'.$itemname.' '.$description.'</div>';
}
}
}
else{
echo "no" ;
}
?>
<html>
<head>
<title>searching</title>
</head>
<body>
<form action="search.php" method="POST">
<input type="text" name="search" placeholder="Search">
<input type="submit" value=">>" />
</form>
</body>
<?php
print $output;
?>
</html>
This code works fine on my local host (XAMPP) but does not echo anything out in PhpStorm, the isset function not working there and always shows the output "no".
Is something wrong with my PhpStorm settings because it runs fine on localhost?
PHP STORM is an IDE for writing your code and has no effect on this.
I would suggest doing
print_r($_POST['search']);
and making sure it is actually filled in, possibly a typo.

how to search sql database using php

For the past couple days, I have been trying to learn how to search an mysql database. So far I have the code below. for some reason it isn't searching and giving me results back. my database is named score and the table is all scores. Someone please help me with this.
It should be searching my database but it's coming up with no results. I have made sure everything is correct.
This file is searching.php
<?php
if (isset($_POST['search'])) {
$id = $_POST['id'];
$connect = mysqli_connect("localhost", "root", "root", "score");
$query = "SELECT `name` FROM `all_scores` WHERE `id` = $id LIMIT 1";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$name = $row['name'];
}
} else {
echo "Undifined ID";
$gameid = "";
}
mysqli_free_result($result);
mysqli_close($connect);
} else {
$gameid = "";
}
this is search.php
<!DOCTYPE html>
<html>
<head>
<title> PHP FIND DATA </title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
</body>
</html>
To get the form values inside the php file you need to use $_POST. Here's an example using PDO. You're only retrieving one row so you don't need the while loop.
searching.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$q = $conn->prepare("SELECT `name` FROM `all_scores` WHERE `id` = :id LIMIT 1");
$q->bindValue(':id', $_POST['id'], PDO::PARAM_STR, 50);
$q->execute();
if ($q->rowCount() > 0) {
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
Html:
<form action="searching.php" method="post">
Id:<input type="text" name="id"><br><br>
<input type="submit" name="search" value="Find">
</form>
Take some time look at several other examples

MYSQL and PHP database update wont update database

I am having an issue trying update the database with a form.
So, my issue is when I click on update nothing happens. The database doesn't update.
Another issue is when i use POST in my form and SQL query. It doesn't pull the information through to the edit page, it is blank.
I'm sorry if this hard to read etc. but this is my first time posting. Also, I know there is security flaws in my GET/POST queries I'm just trying to get the thing to work before I start using the prepared statements or whatever they are called.
FYI, if I echo the query and define a if/else statement, I can see it doesn't work but I just don't know why. I have spent 3 days on this and change the code so many times using examples I have found on the internet.
Index.php
<?php
$servername = "localhost";
$username = "***";
$password = "****";
$dbname = "****";
$link = new mysqli("$servername", "$username", "$password", "$dbname");
if ($link->connect_error) {
die("Connection failed: " . $link->connect_error);
}
echo "Connected successfully";
mysqli_select_db($link,"jamesrph_myphp");
$sql = "SELECT * FROM article";
$result = mysqli_query($link,$sql);
$id = 'id';
$title = 'title';
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
<title>PHP </title>
</head>
<body>
<h1> My title </h1>
<table>
<tr>
<?php
while($row=mysqli_fetch_array($result)){
?>
<td><?php echo $row["title"]; ?> </td>
<td>Read More</td>
<td>Edit</td>
</tr>
<?php
}
?>
</table>
</body>
</html>
edit.php
<?php
$link = mysqli_connect("localhost","******","******", "*****");
$query = "SELECT * FROM article WHERE id=".mysqli_real_escape_string($link, $_GET['id'])." LIMIT 1";
$result = mysqli_query($link,$query);
$row = mysqli_fetch_array($result);
$title = $row['title'];
$content = $row['content'];
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<p> Edit Article </p>
<form method="get" action="processarticle.php">
<input type="hidden" name="id" value="<?php echo $row["id"]; ?>" />
<input id="titlearea" type="text" name="title" value="<?php echo $row["title"]; ?>"/>
<textarea id="contentarea" name="content" rows="10" cols="40"><?php echo $row["content"];?></textarea>
<input type="submit" name="submit" id="update_article"/>
</form>
</body>
</html>
processarticle.php
<<?php
//Database Connection
include 'connection.php';
//Get ID from Database
if(isset($_GET['edit_id'])){
$sql = "SELECT * FROM article WHERE id =" .$_GET['edit_id'];
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_array($result);
}
//Update Information
if(isset($_POST['btn-update'])){
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
$update = "UPDATE article SET title=?, content=? WHERE id=?";
$up = mysqli_query($link, $update);
if($stmt = $mysqli->prepare($update)){
$stmt->bind_param("ssi" ,$title ,$content ,$id);
$stmt->excute();
}
header("location: disp.php");
}
?>
Ok your edit.php form has a GET method, yet you are using POST variables in you processarticle.php and you have a GET variable in there.
Lets just say a form can only do one thing either GET or POST
The URL you specified in your form then will access either GET or POST variables based on form method
So if you want to update your article based off your form first lets look at the id = this should be $POST['id'] the hidden field in your form, not that hidden though
$update = "UPDATE article SET title='$title', content='$content' WHERE id=". $_POST['id'];
The more I look at this the more this is going to turn in to a 3 part mini series
Ok on your processarticle.php for starters I would use a prepared statement for the update http://php.net/manual/en/mysqli.prepare.php
process.php
//Update Information
if(isset($_POST['Update_Article'])){
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
$SQL = "UPDATE
article
SET title=?, content=?
WHERE id=?";
if ($stmt = $mysqli->prepare($SQL)) {
$stmt->bind_param("sss", $title ,$content ,$id );
$stmt->execute();
}
}
Start here http://www.w3schools.com/php/default.asp and go from crawling to walking
Honest to god work through that from top to bottom then go here
https://symfony.com/ and hope in a F1 Car
Then try http://www.w3schools.com/bootstrap/default.asp because you are going to want your page to look cool
Use form method post or change all $_POST in $_GET in processarticle.php.
And try changing $_GET['edit_id'] into $_GET['id'] in processarticle.php.

Multiple Search Form in one Submit button PHP/HTML

I'm trying to create a search query where in the user could either search the database using the firstname or lastname or both. I am able to do this using 1 type of search only, but if I do both I'm not sure how I could do this.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Search Contacts</title>
<link href="site.css" rel="stylesheet">
</head>
<body>
<nav id="nav01"></nav>
<div id="main">
<h3>Search Contact Details</h3>
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$myquery = mysqli_real_escape_string($connection,$_POST["fname"]);
$myquery2 = mysqli_real_escape_string($connection,$_POST['lname']);
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// SQL query
if (!empty($myquery)) {
$sql = "select distinct ID, FirstName, LastName, Email, PhoneNumber
from Userlist where FirstName LIKE '%". $myquery ."%' OR LastName LIKE '%".$myquery2."%'";
//Get query on the database
$result = mysqli_query($conn, $sql);
//Check results
if (mysqli_num_rows($result) > 0)
{
//Headers
echo "<table>";
echo "<tr>";
echo "<th>Image ID</th>";
echo "<th>Lastname</th>";
echo "<th>Firstname</th>";
echo "<th>Email</th>";
echo "<th>PhoneNumber</th>";
echo "</tr>";
//output data of each row
while($row = mysqli_fetch_assoc($result))
{
echo "<tr>";
echo "<td>".$row['ID']."</td>";
echo "<td>".$row['LastName']."</td>";
echo "<td>".$row['FirstName']."</td>";
echo "<td>".$row['Email']."</td>";
echo "<td>".$row['PhoneNumber']."</td>";
echo "</tr>";
}
echo "</table>";
} else {
echo "0 results";
}
}
mysqli_close($conn);
?>
<footer id="foot01"></footer>
</div>
<script src="script.js"></script>
</body>
</html>
You can do like this:
<?php
if(strlen($_POST["fname"])>0 AND strlen($_POST["lname"])>0){
$sql = "SELECT ID, FirstName, LastName, Email, PhoneNumber FROM Userlist WHERE FirstName LIKE '%". $_POST["fname"])>."%' AND LastName LIKE '%". $_POST["lname"])>."%'";
}
elseif(strlen($_POST["fname"])>0 AND strlen($_POST["lname"])==0){
$sql = "SELECT ID, FirstName, LastName, Email, PhoneNumber FROM Userlist WHERE FirstName LIKE '%". $_POST["fname"])>."%'";
}
elseif(strlen($_POST["lname"])>0 AND strlen($_POST["fname"])==0){
$sql = "SELECT ID, FirstName, LastName, Email, PhoneNumber FROM Userlist WHERE LastName LIKE '%". $_POST["lname"])>."%'";
}
else{
//No keywords specified
}
?>
You can simply use OR and distinct on ID, so that you only get 1 entry if the user searchs for both, FirstName and LastName
$myquery = mysqli_real_escape_string($connection,$_POST["fname"]); //<<< change $connection to your connection variable
$myquery2 = mysqli_real_escape_string($connection,$_POST['lname']);
$sql = "select distinct ID, FirstName, LastName, Email, PhoneNumber
from Userlist where FirstName LIKE '%". $myquery ."%' OR LastName LIKE '%".$myquery2."%'";
You should escape everything you search for in your query, either with
mysqli_real_escape_string
as written above, or you better use a prepared statement
EDIT:
This :
$myquery = mysqli_real_escape_string($connection,$_POST["fname"]);
$myquery2 = mysqli_real_escape_string($connection,$_POST['lname']);
needs to be after you established your connection. And as you are using $conn for your connection, you need to change it to
$myquery = mysqli_real_escape_string($conn,$_POST["fname"]);
$myquery2 = mysqli_real_escape_string($conn,$_POST['lname']);
Like this:
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
$myquery = mysqli_real_escape_string($conn,$_POST["fname"]);
$myquery2 = mysqli_real_escape_string($conn,$_POST['lname']);
Your code is subject to be sql injection attack and so i have tried to make it better with corrections.
<h3>Search Contact Details</h3>
<form method="post" action="#" id="searchform">
First Name:<br>
<input type="text" name="fname">
<br>Last Name:<br>
<input type="text" name="lname">
<br>
<input type="submit" name="submit" value="Search">
</form>
<?php
/*USE PDO prepared statement to prevent mysql injection attacks*/
//PDo constructor instantiating instance of database object.
$pdo = PDO('mysql:host=localhost;dbname=YourDatabaseName;charset=utf8', 'YourUserName', 'YourPassword');
//check if something is submitted
if(isset($_POST['submit']) ){
//remove tags from the user input
$fname = strip_tags('%'.$_POST['fname'].'%');
$lname = strip_tags('%'.$_POST['lname'] .'%');
//you need to use the if- conditional to
//check if one or both fields are set
if ( (isset($fname) && !empty($fname)) || (isset($lname) && !empty($lname)) ) {
try{
$sql = "SELECT distinct ID, FirstName, LastName, Email, PhoneNumber
FROM Userlist
WHERE `FirstName` LIKE :FirstName OR `LastName` LIKE :LastName";
//Prepare the statment
$query = $pdo->prepare($sql);
$query->bindParam(':FirstName', $fname, PDO::PARAM_STR);
$query->bindParam(':LastName', $lname, PDO::PARAM_STR);
$query->execute();
$result = $query->fetchAll();
} catch (Exception $e) {
print "Database Problem: " . $e->getMessage();
}
}
//you can use foreach to display the result.
foreach ($result as $res):
echo $rs['FirstName']; //and so on
endforeach;
}
else{
echo 'search for some thing';
}
?>

Categories