php search works as seperate page, but not on same page - php

I'm working on a project where I can use multiple forms on an html page to search and update tables from a mysql database. I have created a basic html form that will run a search on a separate php file. When I try to integrate that same php script into that same html it finds no results. Any help would be appreciated.
basic html
<html>
<body>
<form name="search" method="post" action="searchresults.php">
<input name="search" type="text" size="40" maxlength="50" />
<input type="submit" name="Submit" value="Search" />
</form>
</body>
</html>
search php
<?php
$database = "dbname";
$username = "name";
$password = "pass";
$host = "host";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error){
die("Failed:" . $conn->connect_error);
}
echo"Successful";
$query = $_POST['search'];
$query = htmlspecialchars($query);
$raw_results = mysqli_query($conn,"SELECT * FROM beers WHERE name LIKE '%".$query."%'");
if(mysqli_num_rows($raw_results) > 0){ // if one or more rows are returned do following
while($results = mysqli_fetch_array($raw_results)){
echo "<p><h3>".$results['Name']."</h3>".$results['Brewery']."</p>";
}
}
else{ // if there is no matching rows do following
echo "No results";
}
?>
This works separated, but if I copy the same php script and insert it into the main html it connects but finds no results. Tried using _GET instead of _POST removed the action field and Ive searched all over for similar issues. If I scale everything completely down it gives me a parse error for $query = htmlspecialchars($query); , any thoughts?

Apply if (isset($query)) {...}. Only when search name is valid can you gain results.
<?php
$query = $_POST['search'];
// Apply validation.
if (isset($query)) {
$query = htmlspecialchars($query);
echo"Successful";
$conn = new mysqli($host, $username, $password, $database);
if ($conn->connect_error) {
die("Failed:" . $conn->connect_error);
}
$raw_results = mysqli_query($conn, "SELECT * FROM beers WHERE name LIKE '%" . $query . "%'");
if (mysqli_num_rows($raw_results) > 0) { // if one or more rows are returned do following
while ($results = mysqli_fetch_array($raw_results)) {
echo "<p><h3>" . $results['Name'] . "</h3>" . $results['Brewery'] . "</p>";
}
} else { // if there is no matching rows do following
echo "No results";
}
}
?>

Related

PHP not inserting data into MySQL but not showing error

I am trying to input data into a MySQL Database using PHP and a HTML Form but the data isn't saved into the database even though it shows that it has. Please show me how to ensure the form entries save to the database.
HTML
<form action="newproduct.php" method="post">
<table>
<tr>
<td>Username</td>
<td><input name="user" type="text"></td>
</tr> ...
<button type="submit">Go</button>
</form>
PHP
<?php
$servername = "localhost";
$username = $_POST["user"];
$password = $_POST["pass"];
$dbname = "bakefree_products";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "INSERT INTO ".$_POST["range"]." (productname, image, frompricesize, paypalcode, productdesc, allergystandard, allergyglutenfree, allergyvegan, allergygfvegan)
VALUES ('".$_POST["productname"]."', '".$_POST["image"]."', '".$_POST["frompricesize"]."', '".$_POST["paypalcode"]."', '".$_POST["productdesc"]."', '".$_POST["allergystandard"]."', '".$_POST["allergyglutenfree"]."', '".$_POST["allergyvegan"]."', '".$_POST["allergygfvegan"]."')";
if (mysqli_query($conn, $sql)) {
echo "New product created successfully.";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
//show new number of products
$sql = "SELECT * FROM".$_POST["range"];
$result = $conn->query($sql);
if ($result->num_rows > 0) {echo "There are ".$result->num_rows ." products.";
} else {
echo "<br><br>There are no products in ".$_POST["range"];
}
mysqli_close($conn);
?>
RESULT
New product created successfully.
There are no products in TEST
Actually insertion should be working fine but you need to check the syntax of the select query here,
//show new number of products
$sql = "SELECT * FROM ".$_POST["range"]; // Added a space after `FROM`
And it should fetch data properly and show you the string, There are X products.

display user input as comment on same page

I'm trying to create a comment system on my webpage. I want the user to be able in input a comment and have it automatically display on the same page, and reload so that if another user wants to comment the previous comment will also be there. So far, I have created a database that takes in the comments. I have tried to display the comments by querying through my database and printing it out, but it just seems to crash my site.
This is the code I have so far
index.php:
<form action="insert.php" method="GET">
Comments:
<input type="text" name="field1_name"/>
<input type="submit" name="submit" value="submit"/>
</form>
<?php
$query="SELECT COMMENTS FROM parentComment";
$results = mysqli_query($query);
while ($row = mysqli_fetch_assoc($results)) {
echo $row['COMMENTS'];
}
?>
insert.php:
$user = 'x';
$password = '';
$db = 'comment_schema';
$host = 'localhost';
$port = 3306;
$link = mysqli_connect($host, $user, $password, $db);
mysqli_query($link,"GRANT ALL ON comment_schema TO 'x'#'localhost'");
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
if(!empty($_GET["field1_name"])) {
$field1_name = mysqli_real_escape_string($link, $_GET["field1_name"]);
// Escape user inputs for security
$sql = "INSERT INTO parentComment (COMMENTS) VALUES ('$field1_name')";
$result = mysqli_query($link, $sql);
// attempt insert query execution
if ($result) {
//echo $_GET["field1_name"];
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
// close connection
mysqli_close($link);
}
else{
die('comment is not set or not containing valid value');
}
So far everything works as in the comments are being inserted into the database. My problem is with retrieving the comments and displaying it to the user on the same page. I've tried to do so, but it seems to be not working. Not sure where I'm going wrong in my implementation (I've implemented it in the index.php file)
You didn't connect to your db for the query:
$results = mysqli_query($query);
Pass the connection to the query:
$results = mysqli_query($link, $query);
It's required.
http://php.net/manual/en/mysqli.query.php
You also need to make sure that you did establish a connection in that file, otherwise it won't work.

PHP : Cannot get Exact match From MYSQL Database

This php has been really giving me issues. I want to Echo back the data from the database and i want it to show the main data from the database and i want it to show the data from the database to match the information entered from the database for instance if i enter the name "Paul Mason" and click the search button , it connects to the datbase and echos back the information on the site.
Code i have written shows below.
<html>
<title>Search Records</title>
<head>
<body>
<form name="" id="" method="post" action="search.php"/>
<p> Enter Student name : <input type="text" name="fullname" id="fullname"/>
<input type="submit" name="senda" value="Search Data" />
</form>
<?php
if(isset($_POST['senda'])){
include 'mysqlconn.php';
$con = mysqli_connect($host, $dbuser, $pass, $db) or die('Cannot Connect');
$name = $_POST['fullname'];
$sql = "SELECT * FROM scores WHERE MATCH(fullname) AGAINST('$name')";
$result = mysqli_query($con,$sql) or die("Error: ".mysqli_error($con));
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC))
{
printf("%s (%s)\n", $row['Fullname'] ." ". $row['studentNo'] ." ". $row['SubjectName'] ." ". $row['GPA'] ." ". $row['CGPA'] ." ". $row['SCORE']);
mysqli_free_result($result);
}
mysqli_close($con);
}
?>
</body>
</head>
</html>
Instead it shows something else like this : Error: Can't find FULLTEXT index matching the column list
What ould be wrong, I need someone to correct me programmatically!
There is no FULLTEXT index on the column you are referencing. For a single column search, if you dont wish to create an index, try (converted into a prepared statement for you as well):
for loose match:
$con = new mysqli($host, $dbuser, $pass, $db) or die('Cannot Connect');
$name = $_POST['fullname'];
$query = $con->prepare("SELECT * FROM scores WHERE fullname LIKE '%$name%'");
$query->execute();
For exact match:
$con = new mysqli($host, $dbuser, $pass, $db) or die('Cannot Connect');
$name = $_POST['fullname'];
$query = $con->prepare("SELECT * FROM scores WHERE fullname = '$name'");
$query->execute();
If you do have or create a FULLTEXT index, then it will work but would still recommend preparing the query to prevent injection attacks:
$con = new mysqli($host, $dbuser, $pass, $db) or die('Cannot Connect');
$name = $_POST['fullname'];
$query = $con->prepare("WHERE MATCH(fullname) AGAINST('$name')");
$query->execute();

Error message Trying to get property of non-object whentrying to display results from a query

I'm using a simple form to run a database query on a table in my database. The connection doesn't appear to be a problem. The form renders without any issue. When I go to the page though, I receive an error stating that I'm trying to get the property of a non object. Here's the particular line being called out:
if ($result->num_rows > 0){
echo "$result";
}
Any ideas why?
<?php
$servername = "localhost";
$username = "xxx";
$password = "xxx";
$dbname = "oldga740_SeniorProject";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result= '';
//collect
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM Customer WHERE Client LIKE '%$searchq%'";
$result = $conn->query($sql);
}
//Display results
if ($result->num_rows > 0) {
echo "$result";
}
else {
echo "0 results";
}
?>
<html>
<head>
</head>
<body>
<form action="Index.php" method="post">
<input type="text" name="search" placeholder="Search...." />
<input type="submit" value=">>" />
</form>
</body>
</html>
It's fairly straight forward. I have noted for clarity:
// You make it a variable here, with the assumption
// $_POST['search'] will transform it into an object later
$result= '';
// If there is a search variable try to search database
if(isset($_POST['search'])) {
$searchq = $_POST['search'];
$searchq = preg_replace("#[^0-9a-z]#i","",$searchq);
$sql = "SELECT * FROM Customer WHERE Client LIKE '%$searchq%'";
// All is good if the condition is met
$result = $conn->query($sql);
// This has to go here because you have turned $result into an object now
if ($result->num_rows > 0) {
// Likely you will draw an error here, this is probably an array
// that you will need to iterate over using while()
echo "$result";
}
}
/*
// If you leave it here, if the search is not being done, you've
// assigned $result = '' so you are doing ->num_rows on empty
if ($result->num_rows > 0) {
echo "$result";
}
*/

Getting User Data Based on Their Information

This first field is where a web visitor will enter in the 'cardname' hit submit and be directed to another page (dashboard2.php) where only his or her content will appear.
Enter your cardname to access your content<br>
<form action='dashboard2.php'>
<input type='text' name='cardname'/><input type='submit' value='retrieve card'/>
</form>
</body>
The page below is the page that is directed after the user enters in the 'cardname' from the first input field. However, I only want this second page to show the information based on the cardname that was entered. Right now, it shows every single cardname, questionone, answerone from that table.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
} else {
echo "0 results";
}
$conn->close();
?>
You have to modify the query to accept a WHERE clause. For instance, WHERE cardname = mysqli_real_escape_string($conn, $_GET['cardname']) (The default method for any form is GET unless you specify method="post".).
You should learn about prepared statements for MySQLi and perhaps consider using PDO, it's really not hard.
It seems that you want to perform a search and not a display all the records.
Usually a search returns records that match a certain field, unless a specific ID or unique value was entered in the search. I'm not sure this is the case.
I put this together a little quick but hopefully it helps...
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "flashcards";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// escape the string to avoid SQL injections
$searchEscaped = $conn->real_escape_string($_POST['cardname']);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT cardname, questionone, answerone FROM cards WHERE cardname = '$searchEscaped' ";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
if($result->num_rows == 1){
// only one result found, show just that
$row = $result->fetch_assoc()
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}else{
// multiple rows found, show them all
while($row = $result->fetch_assoc()) {
echo "<br> ". $row["cardname"]. " ". $row["questionone"]. " " . $row["answerone"] . "<br>";
}
}
} else {
echo "0 results";
}
$conn->close();
?>

Categories