//conn to DB
echo $_POST['text'];
$filter = $_POST['text'];
$sql = "SELECT DISTINCT * FROM contents
WHERE
MATCH(content,title) AGAINST ('$filter')
";
$mksql=mysql_query($sql);
while($row = mysql_fetch_assoc($mksql)) {
echo $row['title']."<br />";
}
I send POST request to another page with the above code.
It echoes me what I wrote in the input field but it doesn't output any result.
When I run the query in phpmyadmin in works and outputs me 1 result.
Where's the problem?
Try this :
$sql = "SELECT DISTINCT * FROM contents
WHERE MATCH(content,title) AGAINST ('$filter' IN BOOLEAN MODE ) ";
Before query any fulltext search you must create mysql fulltext indexing.
Execute this query in phpmyadmin.
ALTER TABLE contents ADD FULLTEXT(content, title);
may be there is problem in the post data which is not matching with full text search. you can use mysql_escape_string(), htmlspecialchars() functions for the post data you are using for query. These functions will help avoiding html tags,quotes,etc. you can print the generated sql and run that query in phpmyadmin. and of course create mysql fulltext indexing for the field you are searching.
Related
I am trying to display field data in the WP front end using shortcodes from a new table.
See Table
After coming across many sources and research, I do not seem to find a simple way to display data in text (not table), contained within a specific field selected in the SQL query by means of SELECT FROM WHERE.
So far I called wpdb, selected the field, created a loop and echoed. But no results are displayed.
I also tried using print_r and implode but both failed too.
<?php
function Initial_Brief(){ global $wpdb;
$results = $wpdb->prepare( "SELECT 'Initial_Brief'* FROM `Portal_100` WHERE Project_Title = 'Project 1'");
foreach ($results as $result)
echo $result['results'];
}
add_shortcode('Initial_Brief','Initial_Brief')
?>
Many thanks in advance,
To share the logic of this, which I find quite powerful, is to use shortcodes for displaying all text on the website, enabling text edit from the front-end by creating an HTML form which updates the specific field. I will create an edit icon displayed on hover to an editor's role, clicked to trigger a popup with an html form which calls a function to update the specific field in the database.
You are missing to call the get_results method like this:
<?php
global $wpdb;
$id = 23;
$sql = $wpdb->prepare( "SELECT * FROM tablename WHERE id= %d",$id);
$results = $wpdb->get_results( $sql , ARRAY_A );
?>
The use of the prepare method is a good practice for preparing a SQL query for safe execution (eg. preempt SQL injection), but it is no yet the execution, it returns a sanitized query string, if there is a query to prepare.
It is also good companion for the query method.
After some iterations I finally got it to work!
I understand mySQL does not accept input with a spacing?
How can I insert a WHERE condition for multiple words or a paragraph?
It worked for me using the following script but I had to change the WHERE value into an integer.
<?php
add_shortcode('Initial_Brief', function(){
global $wpdb;
$sql = $wpdb->prepare("Select Value from `P100` WHERE `P100`.`id` = 1 ");
$results = $wpdb->get_results( $sql , ARRAY_A );
foreach ($results as $result) {
$display = implode(", ", $result);
echo $display;
});?>
I need to be able to check and see in a certain string is anywhere within my SQL table. The table I am using only has one column of char's. Right now it is saying that everything entered is already within the table, even when it actually is not.
Within SQL I am getting the rows that have the word using this:
SELECT * FROM ADDRESSES WHERE STREET LIKE '%streeetName%';
However, in PHP the word is being entered by the user, and then I am storing it as a variable, and then trying to figure out a way to see if that variable is somewhere within the table.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one of each address allowed.<br /><hr>";
}
You need to do a little bit more than building the query, as mysql_query only returns the resource, which doesn't give you any information about the actual result. Using something like mysql_num_rows should work.
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(mysql_num_rows($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
Note: the mysql_* functions are deprecated and even removed in PHP 7. You should use PDO instead.
In the SQL you used
%streeetName%
But in the query string below, you used
%$streeetName%
Change the correct one
$duplicate = mysql_query("SELECT * FROM ADDRESSES WHERE STREET_NAME LIKE '%$streetName%'", $connect);
if(!empty($duplicate))
{
echo "Sorry, only one comment per person.<br /><hr>";
}
if($results->num_rows) is what you need to check if you have results back from your query. An example of connection and query, check, then print or error handle, the code is loose and not checked for errors. Best of luck...
//Typically your db connect will come from an includes and/or class User...
$db = new mysqli('localhost','user','pass','database');
$sql = "SELECT * FROM `addresses` WHERE `street_name` LIKE '%$streetName%'",$connect;
//test your queries in PHPMyAdmin SQL to make sure they are properly configured.
//store the results of your query in a variable
$results = $db->query($sql);
$stmt = '';//empty variable to hold the values of the query as it runs through the while loop
###########################################################
#check to see if you received results back from your query#
###########################################################
if($results->num_rows){
//loop through your results and echo or assign the values as needed
while($row = $results->fetch_assoc()){
echo "Street Name: ".$row['STREET_NAME'];
//define more variables from your DB query using the $row[] array.
//concatenate values to a variable for printing in your choice further down the document.
$address .= $row['STREET_NAME'].' '.$row['CITY'].' '$row['STATE'].' '$row['ZIP'];
}
}else{ ERROR HANDLING }
So, Im having a lot of trouble with executing a query in PHP. It executes well in phpmyadmin and gives me a neat list of results.
Here is the query I inserted into phpmyadmin:
SELECT RIGHT(`Pair`, LOCATE('_', REVERSE(`Pair`))-1)
FROM `poloniex`
WHERE LEFT(`Pair`, 3) = 'BTC';
For example an entry in the Column Pair: BTC_NXT
The query should return NXT (everything right of the "_").
Now, when switching over to php while I haven't edited the query at all, I don't get any result.
The dbconnection is already established; no problems on that front.
$query_get_pairs = "SELECT RIGHT(`Pair`,LOCATE('_',REVERSE(`Pair`))-1) FROM `poloniex` WHERE LEFT(`Pair`, 3) = 'BTC'";
$result_get_pairs = mysqli_query($dbc,$query_get_pairs);
var_dump($result_get_pairs) returns an empty array.
Summary:
poloniex is the table name.
Pair is the column name which
contains values like "BTC_NXT". The query should give me NXT.
You are not fetching anything, your code should be like:
$query_get_pairs = "SELECT RIGHT(Pair,LOCATE('_',REVERSE(Pair))-1) FROM poloniex WHERE LEFT(Pair, 3) = 'BTC'";
$result_get_pairs = mysqli_query($query_get_pairs);
$myResult = mysqli_fetch_assoc($result_get_pairs);
var_dump($myResult);
I have a postgresql database and I am connecting to and reading from it via php. Ive put in php codes that give me back the result to the query i pass from my code.
Ex- My code :(Note - My HTML page uses a form which asks for input and searches for the given input in the database)
<?php
$result = pg_prepare($dbh, "Query1", 'SELECT * FROM test.bact WHERE disease = $1');
$result = pg_execute($dbh, "Query1", array($disease));
if (!$result) {
die("Error in SQL query: " . pg_last_error());
}
//$rows = pg_fetch_all($result)
/*// iterate over result set
// print each row*/
while ($row = pg_fetch_array($result)) {
echo $row[0]." ".$row[1]. "<br />";
}
From the above piece of code I get my information as strings separated by a space ( echo $row[0]." ".$row[1])
example: Information at row[0]<space>Information at row[1]
What I want - I want the retrieved data in a more organised form i.e. with the column name.
How it should look like -
Name of Column : Data
Name of column : Data ...and so on.
I know there is way in mysql using the mysql_fetch_field, but I wanted something for postgresql. Since I am new to php n databases I am not really sure as to how will I use this.
Any help would be appreciated.
You can use pg_field_name or pg_fetch_assoc
I have made the following search script but can only search one table column when querying the database:
$query = "select * from explore where site_name like '%".$searchterm."%'";
I would like to know how I can search the entire table(explore). Also, I would need to fix this line of code:
echo "$num_found. ".($row['site_name'])." <br />";
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Thanks for any help, here is the entire script if needed:
<?php
// Set variables from form.
$searchterm = $_POST['searchterm'];
trim ($searchterm);
// Check if search term was entered.
if (!$serachterm)
{
echo "Please enter a search term.";
}
// Add slashes to search term.
if (!get_magic_quotes_gpc())
{
$searchterm = addcslashes($searchterm);
}
// Connects to database.
# $dbconn = new mysqli('localhost', 'root', 'root', 'ajax_demo');
if (mysqli_connect_errno())
{
echo "Could not connect to database. Please try again later.";
exit;
}
// Query the database.
$query = "select * from explore where site_name like '%".$searchterm."%'";
$result = $dbconn->query($query);
// Number of rows found.
$num_results = $result->num_rows;
echo "Found: ".$num_results."</p>";
// Loops through results.
for ($i=0; $i <$num_results; $i++)
{
$num_found = $i + 1;
$row = $result->fetch_assoc();
echo "$num_found. ".($row['site_name'])." <br />";
}
// Escape database.
$result->free();
$dbconn->close();
?>
Contrary to other answers, I think you want to use "OR" in your query, not "AND":
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
Replace other_column with the name of a second column. You can keep repeating the part I added for each of your columns.
Note: this is assuming that your variable $searchterm has already been escaped for the database, for example with $mysqli->real_escape_string($searchterm);. Always ensure that is the case, or better yet use parameterised queries.
Similarly when outputting your variables like $row['site_name'] always make sure you escape them for HTML, for example using htmlspecialchars($row['site_name']).
One last thing that is bugging me is when I push the submit button on a different page I always displays the message "Please enter a search term." even when I enter in something?
Make sure that both forms use the same method (post in your example). The <form> tag should have the attribute method="post".
Also, what is wrong with the line of code you mentioned? Is there an error? It should work as far as I can tell.
A UNION query will provide results in a more optimized fashion than simply using OR. Please note that utilizing LIKE in such a manner will not allow you to utilize any indexes you may have on your table. You can use the following to provide a more optimized query at the expense of losing a few possible results:
$query = "SELECT * FROM explore WHERE site_name LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE other_field LIKE '".$searchterm."%'
UNION
SELECT * FROM explore WHERE third_field LIKE '".$searchterm."%'";
This query is probably as fast as you're going to get without using FULLTEXT searching. The downside, however, is that you can only match strings beginning with the searchterm.
To search other columns of table you need to add conditions to your sql
$query = "select * from explore where site_name like '%".$searchterm."%' or other_column like '%".$searchterm."%'";
But if you don't know that I would strongly advise going through some sql tutorial...
Also I didn't see anything wrong with this line
echo "$num_found. ".($row['site_name'])." <br />";
What error message are you getting?
Just add 'AND column = "condition"' to the WHERE clause of your query.
Be careful with adding lots of LIKE % conditions as these can be very slow especially if using a front wild card. This causes the RDBMS to search every row. You can optimize if you use an index on the column and only a trailing wildcard.
You are searching the whole table, just limiting the results to those where the site_name like '%".$searchterm."%'. If you want to search everything from that table, you need to remove the WHERE clause
Here's the corrected line. You had a few too many quotes in it.
echo $num_found.".".($row['site_name'])." <br />";
Regarding displaying the message, you have a typo in your code:
// Check if search term was entered.
if (!$serachterm)
should be:
// Check if search term was entered.
if (!$searchterm)
In the code you have written, !$serachterm always evaluates to true because you never declared a variable $seracherm (note the typo).
your code is very bugy for sql injection first do
do this
$searchterm = htmlspecialchars($searchterm);
trim($searchterm);
next
$query = mysql_real_escape_string($query);
finaly your search looks like this
$query = "select * from explore where site_name like '%$searchterm%';