Simple php/sql search engine - php

I am trying to make a simple php, sql search engine that will select everything from my database that is "LIKE" the keyword (query) and display it. However it will not work. It only displays the text "problem"(see line 32) and after hours of troubleshooting I still can not figure this out.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Search Engine Test</title>
</head>
<body>
<script language="php">
// Create a database connection
$connection = mysql_connect("*****","*****","*****");
if (!connection) {
die ("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("*****",$connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
// Search Engine
// Only execute when button is pressed
if (isset($_POST['search'])) {
// Filter
//$keyword = trim ($keyword);
echo $keyword;
// Select statement
$search = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
// Display
$result = #mysql_query($search);
if (!$result){
echo "problem";
exit();
}
while($result = mysql_fetch_array( $search ))
{
echo $result['cause_name'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($search);
if ($anymatches == 0)
{
echo "Nothing was found that matched your query.<br><br>";
}
}
</script>
<form action="<?php echo $_SERVER['PHP_SELF']?>" method="post">
<input type="text" name="keyword">
<input type="submit" name="search" value="Search">
</body>
</html>

Try and change:
if (isset($_POST['search'])) { //$_POST['search'] just tells that there are a submit-button when submitting (and the name of it)
// Filter
//$keyword = trim ($keyword);
echo $keyword; //You're echoing out value of $keyword which hasn't been set/assigned
// Select statement
//You're always searching for the word keyword with leading and/or trailing characters
//You're not searching for a dynamically assigned value which I think is what you want
$search = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
//You're executing an already defined query (assigned in $search)
$result = #mysql_query($search); //You're suppressing errors, it's bad practice.
if (!$result){
echo "problem";
exit();
}
to:
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim ($_POST['keyword']);
// Select statement
$search = "SELECT * FROM tbl_name WHERE cause_name LIKE '%$keyword%'";
// Display
$result = mysql_query($search) or die('query did not work');
IMPORTANT!
<script language="php"> isn't valid. You should type <?php at the beginning of php-code and ?> to end php-code.
UPDATE:
You will also have to change this code:
while($result = mysql_fetch_array( $search ))
{
echo $result['cause_name'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($search);
if ($anymatches == 0)
{
echo "Nothing was found that matched your query.<br><br>";
}
}
TO:
while($result_arr = mysql_fetch_array( $result ))
{
echo $result_arr['cause_name'];
echo " ";
echo "<br>";
echo "<br>";
}
$anymatches=mysql_num_rows($result);
if ($anymatches == 0)
{
echo "Nothing was found that matched your query.<br><br>";
}
}
When making new code, you really should NOT use mysql_ functions*, because they're deprecated. Look into PDO or mysqli instead.

Expanding your code, we can see that:
$result = #mysql_query($search);
turns into:
$result = #mysql_query(mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'"));
Which doesn't make much sense.
Change the first line to:
$search = "SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'"
or, instead of assigning $search a value at all, just skip to assigning $result the value that $search currently has.
EDIT: to help you explain:
Change this:
$search = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
// Display
$result = #mysql_query($search);
if (!$result){
echo "problem";
exit();
}
to this:
$result = mysql_query("SELECT * FROM tbl_name WHERE cause_name LIKE '%keyword%'");
// Display
if (!$result){
echo "problem";
exit();
}

Related

Mysql - Seeing if a value already exist

i just want to know how I can fix this. In my database : here i have a value of 123. My code is searching for it however it does not find it.
<html>
<head>
<?php
$userid = 123;
$con = mysqli_connect("","","*","");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}else{
echo "Connected";
}
echo "123";
// Perform queries
$sql_fetch_id = "SELECT * FROM AccessedIds WHERE 64id = '123";
$query_id = mysqli_query(sql2242953, $sql_fetch_id);
if(mysqli_num_rows($query_id) ==0) {
echo "empty";
}else{
echo "full";
}
mysqli_close($con);
?>
<title>PHP Test</title>
</head>
<body>
</body>
</html>
Data types
Your query is wrong, try:
$query_id = mysqli_query($con, $sql_fetch_id);
More information
Also as in the comments above, remove the single quote mark before 123.
Your Query and Query string is wrong. You are missing a Single Quote (') in your Query string. See the below statements:
$sql_fetch_id = "SELECT * FROM `AccessedIds` WHERE `64id` = '123'";
$query_id = mysqli_query($con, $sql_fetch_id);
Hope this helps.

php/mysql search function issue

I feel like I just need another set of eyes on this. There is of course something in the database to search, however nothing is displayed. Is there something wrong with the syntax or logic. This is all in one file index.php
<form action = "index.php" method = "post">
Search: <input type="text" name="value" placeholder="Is it part of the FWO?"></input>
<input type=submit name = "search" value="Search">
</form>
New Entry
<br>
<p>Search Results</p>
<hr />
<?php
error_reporting(E_ALL);
$title = $_POST['value'];
echo "You have searched: " .$title;
echo "<br>";
$con = mysql_connect("localhost", "user", "pass") or die ('Could not connect, this is the error: ' . mysql_error());
mysql_select_db("db") or die ('Sorry could not access database at this time. This is the error: ' . mysql_error());
$clean = msql_real_escape_string($_GET['value']);
echo "Another test ". $clean;
$run = mysql_query("SELECT * FROM db WHERE name = '$clean'") or die(mysql_error());
if(mysql_num_rows($run) >= 1){
echo "found entry";
while($i = mysql_fetch_array($run)){
echo $i['creator'];
}
}
else {
echo "No entries found";
}
mysql_close($con);
?>
</body>
</html>
Your form is using post method and you are trying get a value by $_GET
instead of this:
$clean = msql_real_escape_string($_GET['value']);
Use this:
$clean = msql_real_escape_string($_POST['value']);
Or
$clean = msql_real_escape_string($title);
To search inside mysql you should use LIKE. and if you want to search anywhere in the string you should encapsulate with %. for example:
$run = mysql_query("SELECT * FROM db WHERE name LIKE '%$clean%'") or die(mysql_error());
for more info: http://dev.mysql.com/doc/refman/5.7/en/string-comparison-functions.html

confuse to make error message in PHP

all this code is work, what left is I try to echo a message if query not find anything..
include("config.php");
$search = $_POST['search'];
$sql = mysql_query("SELECT * FROM barangtbl WHERE nama LIKE '%$search%' ") or die(mysql_error());
while ($res=mysql_fetch_array($sql)) {
echo $res['nama'].'<br>';
}
?>
Write this:
if(mysql_num_rows($sql)) {
while ($res=mysql_fetch_array($sql)) {
echo $res['nama'].'<br>';
}
}
else
{
echo "Not found";
}
Try this:
include("config.php");
$search = $_POST['search'];
$sql = mysql_query("SELECT * FROM barangtbl WHERE nama LIKE '%$search%' ") or die(mysql_error());
if(mysql_num_rows($sql))
{
while ($res=mysql_fetch_array($sql)) {
echo $res['nama'].'<br>';
}
}
else
{
echo "The query resulted in an Empty Set";
}
Here,
mysql_num_rows($sql) will output the total no of rows in the result. If the query's output is zero rows, the value of mysql_num_rows($sql) is zero which will lead to the if condition being false and hence executing the else part.
John V is right.
But i would suggest you to use mysqli instead of the deprecated mysql function
(deprecated since version 5.5)
http://php.net/manual/en/book.mysqli.php
try this:
if($sql)
{
echo "success";
}
else
{
echo "Error";
}

Transferring MySQL server to php page = query not working?

I was trying to make a php page that would display a MySQL search engine, and itworked on one server: however, on that server crashed and I was forced to reboot it. Even when I'm using the same code, the search engine no longer works - my code is as follows:
<html>
<head>
<meta charset="UTF-8">
<title>Search Engine Test</title>
<h1>Gromax</h1>
</head>
<body>
<form action="search1.php" method="post">
<input type="text" name="keyword">
<input type="submit" name="search" value="Search">
<br>
<br>
</form>
<script language="php">
// Create a database connection
error_reporting(0);
$connection = mysql_connect("localhost", "$ mysql -u anonymous", "");
if (!$connection) {
die("Please reload page. Database connection failed: " . mysql_error());
}
// Select a databse to use
$db_select = mysql_select_db("test", $connection);
if (!$db_select) {
die("Please reload page. Database selection failed: " . mysql_error());
}
// Search Engine
// Only execute when button is pressed
if (isset($_POST['keyword'])) {
// Filter
$keyword = trim($_POST['keyword']);
// Select statement
$search = "SELECT Price FROM table_1 WHERE Model = '$keyword'";
// Display
$result = mysql_query($search) or die('query did not work');
while ($result_array = mysql_fetch_array($result)) {
$arrlength=count($result_array);
for($x=0;$x+1<$arrlength;$x++){
echo "Price: " . $result_array[$x];
echo "<br>";
}
}
}
?>
</script>
</body>
</html>
Any help would be appreciated.
I'm pretty sure you have an error in your query or your Database connection. Try commenting the line:
// error_reporting(0);
and see what error you get...
Try to use a format like this to determine what is going wrong in your select query:
<?php
$sql = "
SELECT
Price
FROM
table_1
WHERE
Model = '".$keyword."'
";
if(!$res = mysql_query($sql))
{
trigger_error(mysql_error().'<br />In query: '.$sql);
}
elseif(mysql_num_rows($res) == 0)
{
echo 'Geen resultaten gevonden';
}
else
{
while($row = mysql_fetch_assoc($res))
{
echo $row['voornaam'].'<br />';
}
}
?>

How can I make my form input not return any results when it is inputted with an empty query?

I want my form input not to act upon an empty search.
I don't want it to even go to the results page and show an error message.
SO
how can I have it so nothing happens when clicking the submit/pressing enter OR pressing space bar then enter?
Can this be done with javascript?
HTML:
<form action="search.php" method="post">
Search: <input type="text" name="term" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
PHP:
<?php
$conn = mysql_connect("", "", "")
or die (mysql_error());
mysql_select_db("testable");
if (!$conn) {
echo "Unable to connect to DB: " . mysql_error();
exit;
}
$term = addcslashes($term,'%_');
$term = "%" . $_POST["term"] . "%";
if (!mysql_select_db("weezycouk_641290_db2")) {
echo "Unable to select mydbname: " . mysql_error();
exit;
}
**if (isset($_POST['term']) && ($_POST['term'] !== '')) {
$term = $_POST['term'];
$safe_term = mysql_real_escape_string($term);
$sql = "SELECT FName,LName,Phone
FROM testable
WHERE FName LIKE '%". mysql_real_escape_string($term) ."%'";
$result = mysql_query($sql);
}**
if (!$result) {
echo "Could not successfully run query ($sql) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while ($row = mysql_fetch_assoc($result)) {
echo '<br><br><div class="data1">';
echo htmlentities($row["FName"]);
echo '</div><br><div class="data2">';
echo htmlentities($row["LName"]);
echo '</div><br><div class="data3">';
echo htmlentities($row["Phone"]);
echo '</div>';
}
mysql_free_result($result);
?>
Preventing the form from being submitted via JS is a quick fix, but you still need to handle the possibility that someone could STILL submit a blank search:
if (isset($_POST['term']) && ($_POST['term'] !== '')) {
$term = $_POST['term'];
$safe_term = mysql_real_escape_string($term);
$sql = "...."
blah blah blah
}
note the use of mysql_real_escape_string(). It is THE safe method for strings in mysql queries. addslashes is a hideously broken piece of crap and should NEVER be used for SQL injection prevention.
You can check the length in JS and abort is it's blank
Yes, you can do that using javascript.
Add a javascript function to handle on click event of submit button.
<input type="submit" name="submit" value="Submit" onclick="submitForm(event)" />
Inside that javascript function, check whether textbox is empty or not
function submitForm(event){
var val = document.getElementsByName('term')[0].value;
if (val==null || val.trim()==""){
//document.getElementsByTagName('form')[0].submit();
event.preventDefault();
return false;
}
else {
return true;
}
}
If empty, prevent default event and return false => prevent submission
if not empty, return true => submit the form.

Categories