Search the records of visible = 1 - mysql

I have a problem
when I get records from the database
mysql_select_db($database_Photo_con, $Photo_con);
$query_rsPhoto = "SELECT * FROM photographs WHERE visible = 1 ORDER BY id ASC";
This shows me all records with visible = 1
if search
mysql_select_db($database_Photo_con, $Photo_con);
$query_rsPhoto = sprintf("SELECT * FROM photographs WHERE caption LIKE %s OR caption_2 LIKE %s AND visible = 1 ", GetSQLValueString("%" . $colname_rsPhoto . "%", "text"),GetSQLValueString("%" . $colname_rsPhoto . "%", "text"));
it shows me all
Does anyone know why this is happening?

It is because the operator precedence (AND has higher priority than OR), so you should use brackets.
$query_rsPhoto = sprintf("SELECT * FROM photographs WHERE (caption LIKE %s OR caption_2 LIKE %s) AND visible = 1 ", GetSQLValueString("%" . $colname_rsPhoto . "%", "text"),GetSQLValueString("%" . $colname_rsPhoto . "%", "text"));
And if the GetSQLValueString do not return string with quotes, you have to add them in the query
$query_rsPhoto = sprintf("SELECT * FROM photographs WHERE (caption LIKE '%s' OR caption_2 LIKE '%s') AND visible = 1 ", GetSQLValueString("%" . $colname_rsPhoto . "%", "text"),GetSQLValueString("%" . $colname_rsPhoto . "%", "text"));

Related

How to define where condition (ex: userid != 0) in this below query?

How to define where condition in this below query?form the database except the zero value need to shown
private function totalVisitedPagesPerUser() {
$query = "SELECT COUNT(*), " . $this->_db->quoteName('customer_name') . "," .
"\n MAX(". $this->_db->quoteName('visit_timestamp') . ")," . $this->_db->quoteName('browser') . "," .
$this->_db->quoteName('os') . "," .
$this->_db->quoteName('session_id_person') . "," .
$this->_db->quoteName('ip') . "," .
"\n SUM(" . $this->_db->quoteName('impulse') . ")," .
$this->_db->quoteName('geolocation') .
"\n FROM ( SELECT * FROM #__realtimeanalytics_serverstats " . $this->whereQuery . " ORDER BY `visit_timestamp` DESC) AS INTABLE" .
$this->whereQuery .
"\n GROUP BY " . $this->_db->quoteName('session_id_person') .
"\n ORDER BY " . $this->_db->quoteName('customer_name');
$this->_db->setQuery($query);
$results = $this->_db->loadRowList();
if ($this->_db->getErrorNum()) {
throw new JRealtimeException(JText::sprintf('COM_JREALTIME_ERROR_RECORDS', $this->_db->getErrorMsg()), 'error');
}
return $results;
}
you can prepare where condition variable by checking conditions before query start, than append that variable at that point like:
$wherecondtion = "Where 1=1";
if($condition1){$wherecondtion."AND (add required filter 1)"}
if($condition2){$wherecondtion."AND (add required filter 2)"}
your subquery will be like:
"( SELECT * FROM #__realtimeanalytics_serverstats " . $wherecondtion . " ORDER BY `visit_timestamp` DESC)"
Is this the thing you needed or something different thing?

Right way to write multiple options search query

Belove is My search Query which works fine if I want any one of the passed value search , but what if i want exact match for particular value ?
I can use AND operator but that will increase number of lines ,for example how can i write query if I want particular location match ,pls can any one help me out with better search query
$sql = "SELECT * ";
$sql .= "FROM js_projects WHERE ";
$sql .= "jsp_title LIKE '%" . $valToSearch . "%' ";
$sql .= "OR jsp_nature LIKE '%" . $nature . "%' ";
$sql .= "OR jsp_etype LIKE '%" . $etype . "%' ";
$sql .= "OR jsp_location LIKE '%" . $location . "%' ";
$sql .= "OR jsp_date LIKE '%" . $jobdate . "%' ";
Edit
Suppose I have value for
valtosearch,location,jobdate,etype and I want exact match for all this values ,
or I can have any two of these values and I want exact match for them ,
or I can have any one of these values and I want exact match for that .
So how can I write query for all these possiblities?
Try like this. This will work fine
$condition=($location!=''?" AND jsp_location LIKE '%".$location."%":"");
$condition.=($jobdate!=''?" AND jsp_date LIKE '%".$jobDate."%":"");
$sql = "SELECT * FROM js_projects WHERE jsp_title LIKE '%".$valueToSearch."%' ".$condition;

Error in updating database row in MYSQL

I have a table
items: id, userid, item_name, item_description
I want to update a row and used the following sql statement for it.
$updateQuery = "UPDATE items SET item_name = '$item_name',
item_desc = '$item_desc' WHERE userid = '$userid'
AND item_name = '$old_name'";
But it fails. Is it because I used the item_name field, which is to be updated, for selecting the row?
I think I see the problem
item_desc = '$item_desc'
"4 columns id, userid, item_name, item_description."
Change your query to
$updateQuery = "UPDATE items SET item_name = '$item_name', item_description = '$item_desc' WHERE userid = '$userid' AND item_name = '$old_name'";
you not update item_name because you used it in where clause
or
you can echo this string and run in database terminal to verify.
Try :
$updateQuery = "UPDATE items SET item_name = '" . $item_name . "', item_desc = '" . $item_desc . "' WHERE userid = " . $userid . " AND item_name = '" . $old_name . "';"
Please notice, in your query, you are referring the last column as "item_desc" which does not exist, as the actual column name is "item_description" .
MySQL is treating "item_desc" as a separate column in your table, but unable to find it, and hence the error.
Also, it is a good idea to pay attention to how you are concatenating your variable to your query. After equal to(=) sign, always use this notation ' ".$variable_name." ' to concatenate. Example:
select column1, column2 from table1 where (column1 = ' ".$variable_name." ' && column2 = ' ".$variable_name." ') ";
You have to concatenate the strings.
$updateQuery = "UPDATE items SET item_name = '" . $item_name . "', item_desc = '" . $item_desc . "' WHERE userid = " . $userid . " AND item_name = '" . $old_name . "'";
Instead of item_desc, it should be item_description.

mysql_fetch_assoc() parameter 1 resource, object given in ... on line 6

Hi I've searched for a solution to this and found several answers and after many edits to the code and no success I'm asking here directly.
$return_arr = array();
$fetch = tep_db_query("select * from products, " . TABLE_PRODUCTS_DESCRIPTION . " WHERE products.products_status = '1' and products.products_id = " . TABLE_PRODUCTS_DESCRIPTION . ".products_id and " . TABLE_PRODUCTS_DESCRIPTION . ".language_id = '" . (int)$languages_id . "' and " . TABLE_PRODUCTS_DESCRIPTION . ".products_name LIKE '%" . $_GET['term'] . "%' LIMIT 0,10");
if($fetch === FALSE) {
die(mysql_error());
}
while ($row = mysql_fetch_assoc($fetch))
{
array_push($return_arr, $row['products_name']);
}
print json_encode($return_arr);
This returns: mysql_fetch_assoc() parameter 1 resource, object given in ... on line 6
I get where it is, just can't seem to find the problem.
Thanks in advance
Use tep_db_fetch_array()
$return_arr = array();
$fetch = tep_db_query("select * from products, " . TABLE_PRODUCTS_DESCRIPTION . " WHERE products.products_status = '1' and products.products_id = " . TABLE_PRODUCTS_DESCRIPTION . ".products_id and " . TABLE_PRODUCTS_DESCRIPTION . ".language_id = '" . (int)$languages_id . "' and " . TABLE_PRODUCTS_DESCRIPTION . ".products_name LIKE '%" . $_GET['term'] . "%' LIMIT 0,10");
echo $fetch; die;
if($fetch === FALSE) {
die(mysql_error());
}
while ($row = tep_db_fetch_array($fetch))
{
array_push($return_arr, $row['products_name']);
}
print json_encode($return_arr);
string mysqli_real_escape_string ( mysqli $link , string $escapestr )
link- A link identifier returned by mysqli_connect() or mysqli_init()
escapestr- The string to be escaped.
You can find an example http://php.net/manual/en/mysqli.real-escape-string.php the first parameter needs to be the link identifier returned by mysqli_connect()

SQL search multiple values in same field

I'm building a simple search algorithm and I want to break my string with spaces, and search my database on it, like so:
$search = "Sony TV with FullHD support";
$search = explode( ' ', $search );
SELECT name FROM Products WHERE name LIKE %$search[1]% AND name LIKE %$search[2]% LIMIT 6
Is this possible?
Yes, you can use SQL IN operator to search multiple absolute values:
SELECT name FROM products WHERE name IN ( 'Value1', 'Value2', ... );
If you want to use LIKE you will need to use OR instead:
SELECT name FROM products WHERE name LIKE '%Value1' OR name LIKE '%Value2';
Using AND (as you tried) requires ALL conditions to be true, using OR requires at least one to be true.
Try this
Using UNION
$sql = '';
$count = 0;
foreach($search as $text)
{
if($count > 0)
$sql = $sql."UNION Select name From myTable WHERE Name LIKE '%$text%'";
else
$sql = $sql."Select name From myTable WHERE Name LIKE '%$text%'";
$count++;
}
Using WHERE IN
$comma_separated = "('" . implode("','", $search) . "')"; // ('1','2','3')
$sql = "Select name From myTable WHERE name IN ".$comma_separated ;
This will works perfectly in both cases, one or multiple fields searching multiple words.
Hope this will help someone. Thanks
declare #searchTrm varchar(MAX)='one two three four';
--select value from STRING_SPLIT(#searchTrm, ' ') where trim(value)<>''
select * from Bols
WHERE EXISTS (SELECT value
FROM STRING_SPLIT(#searchTrm, ' ')
WHERE
trim(value)<>''
and(
BolNumber like '%'+ value+'%'
or UserComment like '%'+ value+'%'
or RequesterId like '%'+ value+'%' )
)
This has been partially answered here:
MySQL Like multiple values
I advise against
$search = explode( ' ', $search );
and input them directly into the SQL query as this makes prone to SQL inject via the search bar. You will have to escape the characters first in case they try something funny like: "--; DROP TABLE name;
$search = str_replace('"', "''", search );
But even that is not completely safe. You must try to use SQL prepared statements to be safer. Using the regular expression is much easier to build a function to prepare and create what you want.
function makeSQL_search_pattern($search) {
search_pattern = false;
//escape the special regex chars
$search = str_replace('"', "''", $search);
$search = str_replace('^', "\\^", $search);
$search = str_replace('$', "\\$", $search);
$search = str_replace('.', "\\.", $search);
$search = str_replace('[', "\\[", $search);
$search = str_replace(']', "\\]", $search);
$search = str_replace('|', "\\|", $search);
$search = str_replace('*', "\\*", $search);
$search = str_replace('+', "\\+", $search);
$search = str_replace('{', "\\{", $search);
$search = str_replace('}', "\\}", $search);
$search = explode(" ", $search);
for ($i = 0; $i < count($search); $i++) {
if ($i > 0 && $i < count($search) ) {
$search_pattern .= "|";
}
$search_pattern .= $search[$i];
}
return search_pattern;
}
$search_pattern = makeSQL_search_pattern($search);
$sql_query = "SELECT name FROM Products WHERE name REGEXP :search LIMIT 6"
$stmt = pdo->prepare($sql_query);
$stmt->bindParam(":search", $search_pattern, PDO::PARAM_STR);
$stmt->execute();
I have not tested this code, but this is what I would do in your case.
I hope this helps.
You can try and execute below query:
SELECT name FROM Products WHERE REGEXP '.*Value1|.*Value2';
Pls note that there should not be a space before or after the pipe symbol
(|).
I know this is long time ago, but I have a solution. It can solved like this:
#intial query
query = 'SELECT var1, var2 FROM dbo.db_name WHERE'
if status :
query = query + " AND status='" + status + "'"
if type :
query = query + " AND Type='" + type + "'"
if number :
query = query + " AND Number='" + number + "'"
if cancel_request:
query = query + " AND CancelRequest='" + cancel_request + "'"
query = query + ' ORDER BY transid DESC'
cur.execute(query)