removing common words from php/mysql search program [duplicate] - php

This question already has answers here:
mysql keyword search
(2 answers)
MySQL Fulltext Stopwords Rationale
(1 answer)
Closed 5 years ago.
Ok so I'm pretty new to PHP and building a question/answer site. I want a page where the user can search my questions table to find a question and after some research and work I've come up with this but my problem is common words. If a user types "is" in the search every question with "is" in it turns up. My question is either 1) Is my approach to this search function completely wrong? or 2) is there a way I can inject an array of common words to be omitted from the query?
search_reslut.php:
<?php
$servername = "127.0.0.1";
$username = "dylan326";
$password = "";
$dbname = "questions87";
$port = 3306;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname, $port);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Your search results: <br>";
echo "<br />";
$query = $_POST['query'];
$query = "$query $query $query";
$pieces = explode(" ", $query);
$qindex0 = $pieces[0]; // piece1
$qindex1 = $pieces[1]; // piece2
$qindex2 = $pieces[2]; // piece3
$qindex3 = $pieces[3];
$qindex4 = $pieces[4];
$qindex5 = $pieces[5];
$qindex6 = $pieces[6];
echo $query;
$sql = "select q_id, question, username, q_date from questions where (question like '%$qindex0%' or question like '%$qindex1%' or question like '%$qindex2%' or question like '%$qindex3%'
or question like '%$qindex4%' or question like '%$qindex5%' or question like '%$qindex6%')";
$result = $conn->query($sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_array($result)){
$question = $row['question'];
echo ('<a href="totalqs.php?q_id=' . $row['q_id'] .'" >' . $question .'Asked by:'.' '.$row['username'].' '.$row['q_date'] .' </a>' . '<br>');
}}
else {echo "No resluts found";}
?>

MySQL has the ability to make keyword searches easy and much faster than what you're doing. This is done through the MATCH(column) AGAINST ('words to search') syntax. Add a FULLTEXT index to your table, for the column you want to make searchable (question). Then something like this would work to return all questions that have at least one of the search words
// Get the query. escape all single quotes.
$words = str_replace("'","\'",$_POST['query']);
$sql = <<< "SQL"
select q_id, question, username, q_date from questions
where MATCH(`question`) AGAINST('$words' IN BOOLEAN MODE)
SQL;
$result = $conn->query($sql);
The nice thing about FULLTEXT searches is that they automatically exclude common words (stop words) from the searches for you. Learn more here as well as here
If you have a custom list of stop words, you can just remove them from the $words string before you execute the query
$stopWords = [
'/is/',
'/the/'
];
// Where is the cat >> Where cat
$words = preg_replace($stopWords,'',$words);
Note from the docs:
Full-text indexes can be used only with MyISAM tables. (In MySQL 5.6 and up, they can also be used with InnoDB tables.) Full-text indexes can be created only for CHAR, VARCHAR, or TEXT columns.

Related

php mysql cant find id if there is letters inside [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
When i try to search for a available id with numbers, it echos correctly.
HOWEVER, if there is a single letter inside, like this: 5325252T, It wont find it in the database.
I have a column with type: longtext
How can I get around this? I never noticed this problem before and now I'm in a hurry to fix it...
Btw, If i echo all the tables for rusp_9_cf7dbplugin_submits, it also shows those ids with letters inside. Really weird.
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT field_value FROM rusp_9_cf7dbplugin_submits WHERE field_value = 5325252T"; // If i remove the T, It will find the id and echo it in a table, but if the T is there, it wont find the id at all...
$result = $conn->query($sql);
if ($result->num_rows > 0) {
echo "<table><tr><th>ID</th><th>Name</th></tr>";
// output data of each row
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["field_value"]."</td><td>".$row["field_value"]." ".$row["field_value"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
Just enclose the field_value value in single inverted commas ' since adding a character makes the SQL engine interpret that value as a number where as it is a string literal, whereas if its just numbers then it interprets it as an integer.
Your code becomes...
...
$sql = "SELECT field_value FROM rusp_9_cf7dbplugin_submits WHERE field_value = '5325252T'"; // If i remove the T, It will find the id and echo it in a table, but if the T is there, it wont find the id at all...
...

Creating a mysql database with "." in the name (using php) [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 6 years ago.
I've been having some trouble recently with trying to automate new database creations with a php script.
Basically, the script takes the new login username and creates a database (and then insert some tables and data later on, which is also done via a php script).
I used to have to manually create the database, but now need to make it automated.
The issue is that I used to be able to just create a new database using the phpadmin "new database" function from the web GUI and put in names like "test1.siteA", "userb.siteB".
However, now that I've tried to do the same via php script, it keeps giving me the "You have an error in your syntax..." from my last "echo".
Main parameters are:
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
I've found that the error would disappear once I remove the .site part from the code (it still exist even if I combine the $dbname into 1 line).
According to some articles that I've found online, it seems that MySQL doesn't allow special characters like "." to be included in the database name.
It just seems very weird to me that the ".site" can be added manually through phpMyadmin while the php/mysqli script doesn't allow this.
The full script is as follows (I'm sure it can be heavily improved, so any suggestions regarding that are also welcome):
<?php
define("_VALID_PHP", true);
require_once(APPPATH. "/libraries/init.php");
include (BASEPATH . "/database/DB_temp.php");
$row = $user->getUserData();
$name = $user->username;
$servernm = 'localhost';
$usnm = 'user';
$pasd = 'user';
$dbname = $name;
$dbname .= '.site';
// Create connection
$conn = mysqli_connect($servernm, $usnm, $pasd);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// Check if DB exist
$sql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
$check = mysqli_query($conn,$sql)
or die("Connection failed: " . mysqli_connect_error());
while($row = mysqli_fetch_array($check,MYSQLI_NUM))
{
$dbval = $row[0];
}
if ($dbval == "0")
{
$createsql = "CREATE DATABASE '$dbname' ";
}
if ($dbval == "1")
{
$createsql = "SELECT count(SCHEMA_NAME) FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = '$dbname'";
}
if (mysqli_query($conn, $createsql)) {
Echo "Completed. DBVAL= " .$dbval ;
}
else
{
echo "Error creating database: " . mysqli_error($conn);
}
?>
PHP version: 5.6.18
phpmyadmin: 4.5.4.1
Ubuntu 14.04
Apologies if I've made some posting errors on here. Do let me know about them and I'll try to correct it as much as I can. Any help is greatly appreciated!
. is a meta character in SQL, use to separate db/table/field names:
SELECT foo.bar.baz FROM sometable
^---------- database 'foo'
^------- table 'bar'
^--- field 'baz'
You should NOT be using metacharacters in any identifiers. It just leads to pain later on, and having to do stuff like:
SELECT `foo.bar`.baz.qux FROM ...
^^^^^^^^^--------- database 'foo.bar'
^------ table 'baz'
^-- field 'qux'
So you can use backticks if you absolutely have to, but you shouldn't be doing this in the first place.
try wrapping the database name with back ticks.
$dbname .= '`.site`';

How to insert a symbol like θ, α, Γ, Δ or anything in the MySQL database using php? [duplicate]

This question already has answers here:
UTF-8 all the way through
(13 answers)
Closed 7 years ago.
Is there any needs to change the table structure or which function, so please put the solution here. thanks in advance.
My example is as:
$find_regex = 'Δ';
$replace_regex = 'Δ';
$sql = mysql_query("INSERT INTO regex_table (find_regex, replace_regex, import_date) VALUES ('$find_regex', '$replace_regex')");
When I run the above code, it executed successfully but instead of symbol(find_regex) it insert '?'
One more thing I have already tried all the suggestion likes htmlentities, htmlspecialchar and so on provided in others questions in stackoverflow but didn't resolved.
use mysql_real_escape_string($data); //where $data is your string which contains special char
refer enter link description here
Before saving to db you can encrypt your data by using htmlentities(), and while retrieving data from database you can decrpt by html_entity_decode() , See the following example may be it will help you:
<?php error_reporting(E_ALL);
$servername = "localhost";
$username = "root";
$password = "";
$db = 'test_001';
// Create connection
$conn = new mysqli($servername, $username, $password, $db);
$find_regex = htmlentities('Δ');
$replace_regex = htmlentities('Δ');
$sql = "INSERT INTO regex_table (find_regex, replace_regex ) VALUES ("."'". mysqli_real_escape_string($conn, $find_regex)."', '". mysqli_real_escape_string($conn, $replace_regex)."')";
//exit;
$result = $conn->query($sql);
//For retrieving from database
$sql = "SELECT * FROM `regex_table`";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row['find_regex'].'<br>'.$row['replace_regex'].'<br>';
}
} else {
echo "0 results";
}
$conn->close();
?>

Exploding input from text area and looping through 2 arrays

I'm entering a list of numbers in two text areas. One area is known as SectionID and the other Length. Both are of equal length. I'm submitting these to a PHP handling page which enter details to an SQL db.
<?PHP
$exchange = $_POST['Exchange'];
$estimate = $_POST['Estimate'];
$sectionid = $_POST['SectionID'];
$length = $_POST['Length'];
$username = "USER";
$password = "PASS";
$hostname = "HOST";
$con = mysql_connect($hostname, $username, $password) or die("Unable to connect to MySQL");
$selected = mysql_select_db("DATAB", $con) or die("Could not select examples");
$sectionid = explode("\n", str_replace("\r", "", $sectionid));
$length = explode("\n", str_replace("\r", "", $length));
foreach ($sectionid as $key => $secdata) {
$lendata = $length[$key];
$query = "INSERT INTO table (Exchange, Estimate, SectionID, Length) VALUES ('$exchange','$estimate','$secdata','$lendata')";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
echo "$estimate created on $exchange Exchange!";
mysql_close($con);
?>
This for some reason isn't working and I just can't see my mistake. Never before have I had to do this. The current result makes 1 entry only to the db, leaves the SectionID blank and fills Length with multiple lines from the text area.
What I'm trying to achieve is create as many entries as there are SectionID's in the list and insert the SectionID and Length that correspond to each other. This is not my only attempt, I have used about4 different variations of exploding the $_POST.
Anyone care to help me out?
No problem with explode or anything related to textarea value. its a SQL Syntax error
try this
$query = "INSERT INTO `table` (`Exchange`, `Estimate`, `SectionID`, `Length`) VALUES('$exchange','$estimate','$secdata','$lendata')";
you may enable php error display now.
To debug your code, try
print_r($sectionid);
foreach ($sectionid as $key => $secdata) {
$lendata = $length[$key];
print '<br />row '.$key . ':{'.$secdata.'}';
$query = "INSERT INTO table (Exchange, Estimate, SectionID, Length) VALUES ('$exchange','$estimate','$secdata','$lendata')";
if (!mysql_query($query,$con))
{
die('Error: ' . mysql_error($con));
}
}
If the data is being received and parsed correctly, you should see on your screen the initial array printed to the screen along with each variable within the array printed on seperate lines surrounded by brackets.
If you see something like
row 0: {}
Then it means you arent parsing or receiving the data correctly. Check that you are posting sectionID and not sectionid (upper/lower variance with the "id" part).

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in [duplicate]

This question already has an answer here:
What to do with mysqli problems? Errors like mysqli_fetch_array(): Argument #1 must be of type mysqli_result and such
(1 answer)
Closed 9 years ago.
struggling with my web design assignment. I've been following a tutorial to add in a search feature for my website, but I've been getting the following error:
Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in /search.php on line 31
line 31 is (or was)
<pre>if(mysqli_num_rows($results) >= 1)</pre>
That was the original error. as per instructions in the comments, I've since revised the code:
<pre>
<?php
//capture search term and remove spaces at its both ends if the is any
$searchTerm = trim($_GET['keyword']);
//check whether the name parsed is empty
if($searchTerm == "")
{
echo "Enter the name/brand of what you're looking for.";
exit();
}
//database connection info
$host = "localhost";
$db_name = "sookehhh_shopsy_db";
$username = "sookehhh_shopsy";
$password = "xxxx";
//connecting to server and creating link to database
$link = mysqli_connect($host, $username, $password, $db_name) or die('Could not connect: ' . mysqli_connect_error());
//MYSQL search statement
$query = "SELECT * FROM sookehhh_shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";
// original query$query = "SELECT * FROM sookehhh_shopsy_db WHERE name LIKE '%$searchTerm%'";
$results = mysqli_query($link, $query);
//added suggestion below - not sure if correct place?
if (!$result) {
die(mysqli_error($link));
}
/* check whethere there were matching records in the table
by counting the number of results returned */
if(mysqli_num_rows($results) >= 1)
{
$output = "";
while($row = mysqli_fetch_array($results))
{
$output .= "Product Name: " . $row['name'] . "<br />";
$output .= "Price: " . $row['price'] . "<br />";
}
echo $output;
}
else
echo "There was no matching record for that item " . $searchTerm;
?>
</pre>
made necessary changes and updated yet again -
now the only error message I'm getting here is "Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist"
I'm assuming that I need to change the username, perhaps because it's too similar?
Anywho, thanks for your help so far, and I apologise for my complete ignorance.
I've been trying to teach myself, but unfortunately time is a luxury I just don't have at the moment.
The problem is your query returned false meaning there was an error in your query. After your query you could do the following:
if (!$result) {
die(mysqli_error($link));
}
Or you could combine it with your query:
$results = mysqli_query($link, $query) or die(mysqli_error($link));
That will print out your error.
Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:
$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";
In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist
Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Categories