I am trying to get the result from the database with the mysql LIKE but in wordpress its not working here is the code of what i am trying
//this is what i am putting in where clause.
$state = $_POST['state'];
//table name.
$table_name = $wpdb->prefix . 'userprofile';
//trying but this is returning empty
$q = 'SELECT * FROM ' . $table_name . 'WHERE state LIKE \'%' . esc_sql( like_escape( $state ) ) . '%\'';
echo $q;
$result = $wpdb->get_results($q);
if (empty($result)) {
echo "the result is empty";
}
//returns empty array.
print_r($result);
You are missing a space:
$q = 'SELECT * FROM ' . $table_name . 'WHERE[..snip..]
^---here
which means you're producing
SELECT * FROM whateveruserprofileWHERE
which is invalid SQL.
Like Marc B. said, there are some missing quotes and unnecessary quotations.. change your query line, to this:
$q = "SELECT * FROM $table_name
WHERE state LIKE '%". esc_sql( like_escape( $state ) ) . "%'
AND WHERE city LIKE '%". esc_sql( like_escape( $city ) ) . "%'
AND WHERE session LIKE '%". esc_sql( like_escape( $session ) ) . "%'
OR WHERE another LIKE '%". esc_sql( like_escape( $another ) ) . "%' ";
and your POST line to this:
$state = $_POST['state'];
do this way
$state = esc_sql( $state );
$state = like_escape( $state );
$state = '%' . $state . '%';
$q = 'SELECT * FROM ' . $table_name . 'WHERE state LIKE '$state';
Related
Why Error - Unknown system variable 'post_content'
foreach( $posts as $post ) {
$post_content = $this->add_image_dimensions( $post->post_content );
if( $post_content != $post->post_content ) {
$query = "UPDATE " . $wpdb->prefix . "posts";
$query = " SET post_content = '" . $post_content . "' WHERE ID = " . $post->ID;
$wpdb->query( $query );
}
Sorry for my English
#Strawberry is right. You may want to do something like this:
$query = "UPDATE " . $wpdb->prefix . "posts";
$query = $query + " SET post_content = '" . $post_content . "' WHERE ID = " . $post->ID;
I have just change my hosting, before all my PHP scripts worked fine
but now i get many mysql error like this:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near column = \'value\'
it seems that there is a double quote in some script
there is a way to resolve without update all my PHP scripts?
EDIT: example of PHP code
function test( $table,$column, $where ){
if( get_magic_quotes_gpc() ) { $where = strip_tags( trim( $where ) ); }
else{ $where = strip_tags( mysql_real_escape_string( trim( $where ) ) ); }
$where = "AND id = '" . $where . "' ";
$query = "SELECT " . $column . " FROM " . $table . " WHERE 1 " . $where . " LIMIT 1";
//...
You have to either pass the $table variable or declare it as global, if defined outside.
function test( $column, $where ){
global $table;
if( get_magic_quotes_gpc() ) { $where = strip_tags( trim( $where ) ); }
else{ $where = strip_tags( mysql_real_escape_string( trim( $where ) ) ); }
$where = "AND id = '" . $where . "' ";
$query = "SELECT " . $column . " FROM " . $table . " WHERE 1 " . $where . " LIMIT 1";
What happens if your function looks like this?
function test( $table,$column, $where ){
$where=stripslashes($where);
$where = strip_tags(mysql_real_escape_string(trim( $where )));
$where = "AND id = '" . $where . "' ";
$query = "SELECT " . $column . " FROM " . $table . " WHERE 1 " . $where . " LIMIT 1";
}
I am having a problem getting a query to work (and also am questioning the security of the query).
if(isset($_POST)){
$sql = "SELECT * FROM members WHERE";
if($_POST['FirstName_S'] !== ''){
$sql .= " FirstName LIKE '%" . $_POST['FirstName_S'] . "%'";
}
if($_POST['LastName_S'] !== ''){
$sql .= " OR LastName LIKE '%" . $_POST['LastName_S'] . "%'";
}
if($_POST['Firm_S'] !== ''){
$sql .= " OR Firm LIKE '%" . $_POST['Firm_S'] . "%'";
}
if($_POST['Country_S'] !== ''){
$sql .= " OR Country LIKE '%" . $_POST['Country_S'] . "%'";
}
if($_POST['City_S'] !== ''){
$sql .= " OR City LIKE '%" . $_POST['City_S'] . "%'";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql .= " OR State LIKE '%" . $_POST['State_S'] . "%'";
}
}
Obviously, if FirstName_S is undefined, the query breaks saying "WHERE OR". It seems like it would have a logical fix, but I've been staring at it for a little too long.
Also, sql injection was brought up as a concern, and as a side-question, would sanitizing the input be enough? Or is this altogether bad practice?
if(isset($_POST)){
$sql = "SELECT * FROM members WHERE";
if($_POST['FirstName_S'] !== ''){
$sql .= "OR FirstName LIKE '%" . $_POST['FirstName_S'] . "%'";
}
if($_POST['LastName_S'] !== ''){
$sql .= " OR LastName LIKE '%" . $_POST['LastName_S'] . "%'";
}
if($_POST['Firm_S'] !== ''){
$sql .= " OR Firm LIKE '%" . $_POST['Firm_S'] . "%'";
}
if($_POST['Country_S'] !== ''){
$sql .= " OR Country LIKE '%" . $_POST['Country_S'] . "%'";
}
if($_POST['City_S'] !== ''){
$sql .= " OR City LIKE '%" . $_POST['City_S'] . "%'";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql .= " OR State LIKE '%" . $_POST['State_S'] . "%'";
}
$sql=str_replace("WHERE OR","WHERE",$sql); // quick dirty fix
}
Ofcourse you'd need to sanitize the input, but since you didn't mention which MySQL API you use, I did not add any sanitization functions yet. You can look at http://php.net/mysqli_real_escape_string
do it other way as follow
if(isset($_POST)){
$sql = "SELECT * FROM members WHERE";
if($_POST['FirstName_S'] !== ''){
$sql_arr[]=" FirstName LIKE '%" . $_POST['FirstName_S'] . "%'";
}
if($_POST['LastName_S'] !== ''){
$sql_arr[]= " LastName LIKE '%" . $_POST['LastName_S'] . "%'";
}
if($_POST['Firm_S'] !== ''){
$sql_arr[]= " Firm LIKE '%" . $_POST['Firm_S'] . "%'";
}
if($_POST['Country_S'] !== ''){
$sql_arr[]= " Country LIKE '%" . $_POST['Country_S'] . "%'";
}
if($_POST['City_S'] !== ''){
$sql_arr[]= " City LIKE '%" . $_POST['City_S'] . "%'";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql_arr[]= " State LIKE '%" . $_POST['State_S'] . "%'";
}
if(!empty($sql_arr)){
$sql.=implode(' OR ',$sql_arr);
}
}
The quick fix is to add 1=1 to your query, so your query ends with WHERE 1=1. That allows you to be free to append any number of OR something to your query, without being concerned with omitting the OR on the first one.
(That 1=1 predicate doesn't cause any problem; that will be evaluated at parse time, and doesn't appear in the execution plan.)
As to SQL Injection, yes, this code is susceptible. If you are using mysql interface, then sanitize the post variables with mysql_real_escape_string function. If you are using mysqli or PDO (and you should be), then use parameterized queries.
$stmt = $dbConnection->prepare('SELECT * FROM members WHERE FirstName LIKE ? OR LastName LIKE ? OR FIRM LIKE ? OR Country LIKE ? OR CITY LIKE ? OR STATE LIKE ?');
if($_POST['FirstName_S'] !== ''){
$stmt->bind_param('FirstName', '%'.$_POST['FirstName_S'].'%');
} else {
$stmt->bind_param('FirstName', '%');
}
… // do this for all your parameters
$stmt->execute();
I think this could help you:
if(isset($_POST)){
$sql = "SELECT * FROM members";
if($_POST['FirstName_S'] !== ''){
$sql .= " WHERE FirstName LIKE '%" . $_POST['FirstName_S'] . "%'";
}
else {
$sql .= " WHERE FirstName LIKE '%'";
}
if($_POST['LastName_S'] !== ''){
$sql .= " OR LastName LIKE '%" . $_POST['LastName_S'] . "%'";
}
if($_POST['Firm_S'] !== ''){
$sql .= " OR Firm LIKE '%" . $_POST['Firm_S'] . "%'";
}
if($_POST['Country_S'] !== ''){
$sql .= " OR Country LIKE '%" . $_POST['Country_S'] . "%'";
}
if($_POST['City_S'] !== ''){
$sql .= " OR City LIKE '%" . $_POST['City_S'] . "%'";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql .= " OR State LIKE '%" . $_POST['State_S'] . "%'";
}
}
and for the SQL injections, you can check General_Twyckenham comment.
You could compose the WHERE command based on what parameters is entered...
if(isset($_POST)){
$sql_where = '';
$sql = "SELECT * FROM members ";
if($_POST['FirstName_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." FirstName LIKE '%" . $_POST['FirstName_S'] . "%' ";
}
if($_POST['LastName_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." LastName LIKE '%" . $_POST['LastName_S'] . "%' ";
}
if($_POST['Firm_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." Firm LIKE '%" . $_POST['Firm_S'] . "%' ";
}
if($_POST['Country_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." Country LIKE '%" . $_POST['Country_S'] . "%' ";
}
if($_POST['City_S'] !== ''){
$sql_where .= (($sql_where != '')?('OR '):(''))." City LIKE '%" . $_POST['City_S'] . "%' ";
}
if($_POST['State_S'] !== '' AND $_POST['State_S'] !== 'other'){
$sql_where .= (($sql_where != '')?('OR '):(''))." State LIKE '%" . $_POST['State_S'] . "%' ";
}
$sql .= (($sql_where != '')?('WHERE '.sql_where):(''));
}
I am trying to collect info from four separate text fields and generate queries in the backend to display the results. I have tried many solutions already suggested on here but I keep getting duplicate results.
I have it working with one query:
<?php
$query = "SELECT * FROM book WHERE booktitle LIKE '%" . mysql_real_escape_string($_POST['title']) . "%'";
$result = mysqli_query($con, $query) or die("Error in query");
while ($row = mysqli_fetch_array($result)) {
?>
<img src="<?php echo $row[12]; ?>" width="112px" height="150px" />
<?php
echo "<b>Title: </b>" . $row[1] . "<br />";
echo "<b>Author: </b>" . $row[2] . "<br />";
echo "<b>Price:</b> £" . $row[9] . "<br />";
echo "<b>Description:</b> " . substr($row[3],0,320) . "...<br /><hr>";
}
But I also need to incorporate results from the other 3 somehow??
$query = "SELECT * FROM book WHERE author LIKE '%" . mysql_real_escape_string($_POST['author']) . "%'";
$query = "SELECT * FROM book WHERE isbn LIKE '%" . mysql_real_escape_string($_POST['isbn']) . "%'";
$query = "SELECT * FROM book WHERE description LIKE '%" . mysql_real_escape_string($_POST['keyword']) . "%'";
Any help would be greatly appreciated. Thanks in advance.
You can use an OR statement with the LIKE keyword to search all of these at the same time.
$query = "SELECT * FROM book WHERE booktitle LIKE '%" . $title . "%' OR author LIKE'%" . $author . "%' OR isbn LIKE '%" . $isbn . "%' OR description LIKE '%" . $keyword . "%';
If the variables are empty then you will have WHERE booktitle LIKE '%%', which returns all rows. You will need to build the query based on the input.
// Determine the WHEREs to use
$where = array();
if ( ! empty($title))
$where[] = "booktitle LIKE '%" . $title . "%'";
if ( ! empty($author))
$where[] = "author LIKE '%" . $author . "%'";
if ( ! empty($isbn))
$where[] = "isbn LIKE '%" . $isbn . "%'";
if ( ! empty($description))
$where[] = "description LIKE '%" . $description . "%'";
// Build the query
$query = 'SELECT * FROM book';
if ( ! empty($where))
$query .= ' WHERE ' . implode(' OR ', $where);
Note: I have omitted escaping the input for readability.
<?php
$mysqli = new mysqli("localhost", "username", "password", "database_name");
$book_title = mysql_real_escape_string($_POST['title']);
$author = mysql_real_escape_string($_POST['author']);
$isbn = mysql_real_escape_string($_POST['isbn']);
$keyword = mysql_real_escape_string($_POST['keyword']);
$query = "SELECT * FROM book WHERE booktitle LIKE '%{$book_title}' OR author LIKE'%" . $author . "%'
OR isbn LIKE '%" . $isbn . "%' OR description LIKE '%" . $keyword . "%'";
$result = $mysqli->query($query);
while($row = $result->fetch_array()):?>
<img src="<?=$row['image_column_name']; ?>" width="112px" height="150px" />
<b>Title:</b> <?=$row['title_column_name']; ?> <br>
<b>Author:</b> <?=$row['author_column_name']; ?> <br>
<b>Price:</b> <?=$row['price_column_name']; ?> <br>
<b>Description:</b> <?=substr($row['desc_column_name'],0,320)?>
<hr>
<?php endwhile; ?>
I originally had this working:
url: http://server/blah.php?FacilityCode=FT
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
$result = mysql_query($sql);
But I want to change this so that people can submit multiple values in the query strying somehow, ie: http://server/blah.php?FacilityCode=FT,CC,DD,EE
I tried changing the query to an "IN" clause instead of an "equals" but I'm not sure how to get the ' marks around each element.
Use implode() function for IN (...).
$a = array('AB', 'CD', 'EF', 'ZE');
echo "field IN ('" . implode("', '", $a) . "')";
... will output:
field IN ('AB', 'CD', 'EF', 'ZE')
+escape every option you get.
$facilitycode = mysql_real_escape_string($_GET["FacilityCode"]);
$array=explode(',',$facilitycode);
foreach ($array as $a){$output.="'$a',";}
$clause=substr($output,0,-1);
If your trying to create a string which looks like this: 'AB', 'CD', 'EF', 'ZE'
Try this before its placed inside the query:
$facilitycode = preg_replace('/([^,]+)/', '\'$1\'', $facilitycode);
I wrote this based on your query, but still I dont get this part of query "AND ('" . $facilitycode . "' = ''", anyway you need to check if $_GET data have "," and if does explode that variable by "," so that you can add an OR clausule for everything that was separated by "," in $_GET data.
After that just form your query by doing a foreach for every element in exploded array like I done below:
<?php
$facilitycode = $_GET["FacilityCode"];
$facility_number_chk = strpos($facilitycode, ",");
if ($facility_number_chk > -1) {
$facilitycode = explode(",", $facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = ''";
foreach($facilitycode as $facode) {
$facode = mysql_real_escape_string($facode);
$sql .= " OR Facility.FacilityCode = '". $facode . "'";
}
$sql .= "')";
}
else {
$facilitycode = mysql_real_escape_string($facilitycode);
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
"AND ('" . $facilitycode . "' = '' OR Facility.FacilityCode = '". $facilitycode . "')";
}
$result = mysql_query($sql);
And if there is only one element in $_GET data just do an else like I done with your regular query.
I ended up using a combination of a few of the answers. Basically I exploded on the ",", then did a foreach to add the ' marks and call escape_string, and then imploded it back.
$facilitycodes = $_GET["FacilityCode"];
if ($facilitycodes == '') {
$additionalfilter = '';
}
else {
$facilitycodearray = explode(",", $facilitycodes);
foreach($facilitycodearray as &$facilitycode) {
$facilitycode = "'" . mysql_real_escape_string($facilitycode) . "'";
}
$facilitycodesformatted = implode(",", $facilitycodearray);
$additionalfilter = " AND Facility.FacilityCode IN (" . $facilitycodesformatted . ")";
}
$sql = "SELECT ..." .
"FROM ..." .
"WHERE ..." .
$additionalfilter;