Trying to get a wildcard search to pick up on any text in org_name field and also to pick up any INT fields that have a 1 in them are entered into the form,
e,g If someone types Childminder in the form I want all records with the childminder INT field with a 1 in it to show up on the results...
$sql_result= "SELECT * FROM table WHERE org_name LIKE '%" . $org_name . "%'
OR carer LIKE '1'
OR childminder LIKE '1' ";
Not sure why you would do such things, but sounds like a candidate to the manual query concatenation (hint: don't do this, it hurts). PDO does not support binding column names, so you're out of luck if you're trying to have any help from libraries / other estabilished solutions.
Update
If your schema does not change and you're concerned about SQLi, you could have some matching mechanism that would take search query and array of available ("matchable") columns and process them, reporting matching columns. Then you would just make query from the safe data. Sample code:
$columns = array(/* ... */);
$query = '/* ... */';
$matches = array();
foreach($columns as $column)
{
if(preg_match('/'.$column.'/', $query))
{
$matches[] = $column;
}
}
$sqlQuery = 'you select';
foreach($matches as $match)
{
$sqlQuery .= ' OR '.$match.' = 1';
}
Not exact code, but you should get the idea.
Related
I want to create a search form for my site and be able to search by selecting multiple parameters, using LIKE and eventually ORDER BY. Search by name, country and date.
InnoDB, collation utf8mb4_unicode_ci, php 5.6
<?php
if(isset($_POST['search'])){
$sql = 'SELECT * FROM radio_posts';
$where = array();
$params = array();
if (!empty($_POST['postRadioName'])) {
$where[] = "postName LIKE :searchRadioName";
$params[':searchRadioName'] = '%'.$_POST['postRadioName'].'%';
}
if (!empty($_POST['postCountryID'])) {
$where[] = "postCountryID = :postCountryID";
$params[':postCountryID'] = $_POST['postCountryID'];
}
if (!empty($where)) {
$sql .= ' WHERE (' . implode(') AND (', $where) . ') ' ;
}
$stmt = $db->prepare($sql);
foreach($params as $param => $value) {
$stmt->bindParam($param, $value);
}
$stmt->execute();
}
?>
My table is radio_posts, there are also a few columns, postID, postName, postCountryID, postDate. In postName I have few rows: new radio, new radio 2, new radio 3. When I search for a term, for example "new", all three rows are displayed, good. If I search by postCountryID, for example "3" only one row is displayed, also good because only one is assigned to id 3. But when I search both, postName "new" and postCountryID "3" no results are displayed. How to solve this? to display the row/s coresponding to both, postName and postCountryID. In phpMyAdmin is working but using the search form it doesn't work:
SELECT * FROM `radio_posts` WHERE postName LIKE '%new%' AND postCountryID = 3
Also, if possible, I would like to ask, what is the best approach to order the results by postDate column, ascending, descending.
After replacing $stmt->bindParam($param, $value); with $stmt->bindValue($param, $value); the code is working as expected. One result is retrieved for the term "new" and country ID = 3.
I have a HTML form that people can select some or all off to search a database for member profiles.
Some of the options are:
Male/Female
Age
Location
check boxes like intentions or interests
etc
I need to tailor a MySQL query to meet the selection the member has chosen.
I'm asking because I built a custom search like this before and it turned into a complete mess with multiple queries depending on what was selected.
Would it be best to just build one query and have parts that are added depending on what is selected?
Does anyone have a ruff example?
Database Schema:
I have a number of tables with the related information so I would need to use joins. That said everything works on one primary key PID so it would all join on this.
You could do something like this:
<?php
$whereClause = '';
if($_GET['gender'] == 'male'){
$whereClause .= ' AND gender = "M"';
}
if($_GET['age'] != ''){
$whereClause .= ' AND age = "'.$_GET['age'].'"';
}
?>
I would use an array:
$where = array();
if($_GET["gender"]!=""){
$clean = mysqli_escape_string($db, $_GET["gender"]);
array_push($where, "gender = '$clean'");
}
// etc...
$where = implode(" AND ", $where);
$sql = "SELECT * FROM table WHERE $where";
My database table has many columns.
I want to do a search based on multiple columns.
Sometimes it may not be the value of some columns.
How do these fields in sql query to be ineffective?
Thank you.
for examle:
$C1=$_POST[c1];
$C2=$_POST[c2];
SELECT * FROM mytable WHERE column1='$c1' AND column2='$c2'
i want if C2 be nulled, disable it from sql query.
One way is:
if(!$_POST[C2]){
SELECT * FROM mytable WHERE column1='$c1'
}
...
I want do it through sql query to do because My table has many columns.
First, you should never write queries with variables inside like that. Learn about PDO / mysqli and prepared statements.
Second, key references for an array should either be a string or integer; the expression $_POST[c1] will most likely cause a notice and implicit conversion to a string. It's better to write $_POST['c1'].
Third, and to answer your question, you can use isset() and strlen() to determine whether a value is "empty", i.e. empty string.
$params = array($_POST['c1']); // you should also check whether $_POST['c1'] is defined too
$sql = 'SELECT * FROM `table_name` WHERE column1 = ?';
if (isset($_POST['c2']) && strlen($_POST['c2'])) {
$sql .= ' AND column2 = ?';
$params[] = $_POST['c2'];
}
$stmt = $db->prepare($sql);
$stmt->execute($params);
Build an array of conditions by iterating through the POST values, adding a condition if the respective POST parameter is not empty:
$conditions = array();
foreach ($_POST as $key => $value) {
if (!empty($value)) {
$conditions[] =
$dbcolumn[$key] . " = '" . mysql_real_escape_string($value) . "'";
}
}
You will need an array $dbcolumn that matches POST variables to the database columns (or you have to provide some other means of translating between the two).
Now create a SQL query for the given conditions:
$query = 'SELECT * FROM mytable';
if (!empty($conditions)) {
$query .= ' WHERE ' . join(' AND ', $conditions);
}
Note that the extension that provides mysql_real_escape_string() is deprectaded. You should probably use some other extension to comunicate with the MySQL server and would than have to use the repsective call of the other extension.
This code not recomended, but if you realy want to do it on MySQL, you can use LIKE syntax like this:
SELECT * FROM mytable WHERE column1="$c1" AND column2="$c2%"
Add % character before or after $c2
Please don't do it!!
Trying to use a php generating the email address using the ID eg: peopleID from database using query function with people_mysql into an HTML table with array of emails from five people. The database do not have email addresses only peopleID in a field. Email suffix is #dot.com.
To explain better to what I'm talking about.
$peopleid = "12345";
$suffix = "#dot.com";
$email = $peopleid . $suffix;
// where $email then contains "people#dot.com" with MySQL
This is what I've come up with with string operator.
mysql> SELECT * FROM 'people';
mysql> SELECT *, CONCAT('peopleID', '#dot.com') AS 'Email' FROM 'people';
I would be grateful if anyone can come a php code.
Your query has a mistake in it. Look at the character just before the # symbol. It should be a single quote.
$emails = array();
$query = "SELECT *, CONCAT('peopleID', '#dot.com') AS 'Email' FROM 'people'";
$result = mysql_query($query,$conn_to_database);
while($row = mysql_fetch_object($result)):
$emails[] = $row->Email;
endwhile;
MySQL queries return a reference to the results, not the results themselves. So, you then need to fetch each row and perform any actions you need to perform. In this case, you are populating and array named $emails that you can then use in your php code.
I'm letting users search my database for data by city.
My query looks like:
$results = mysql_query("SELECT * FROM mydb WHERE City='".$city."' LIMIT 10");
I want a user to be able to search 'all cities', so I'd like to either remove the WHERE statement if $city=='all cities'; or use a wildcard for the WHERE statement that matches all cities in the db.
I used to have an IF statement that switched between two queries, but I want to add more filters like country/all countries, zipcode/all zipcodes, etc, So I'd rather keep one dynamic SQL query.
Well, you could still have just one query and build the where clause dynamically, as such:
$where = '';
// conditional statements (if/else, switch) for populating the where clause
$where .= " WHERE City = '{$city}'";
$where .= " AND Country = '{$country}'";
$results = mysql_query("SELECT * FROM mydb{$where} LIMIT 10");
One way would be a case statement:
WHERE City = case when '$city' = 'All cities' then City else '$city' end
If the user is searching for 'All cities', this turns the WHERE statement into:
WHERE City = City
Which is always true (at least for non-null cities ;))
P.S. Make sure you're running these queries using a read-only MySQL account. The user could enter funny stuff into the $city parameter!
You could try
WHERE City like '$city'
and permit the users to enter wildcards, if you think they'd be up to it.
although not PHP programmer, this pseudocode might offer an option... conditionally build out your where clause. Additionally, I would do it with parameterized queries instead of direct string building to prevent sql-injection attacks.
cYourSQL = "select * from YourTable where "
cAndRequired = ""
if city is NOT "all cities"
cYourSQL = cYourSQL + cAndRequired + " city = 'YourParameterValueProvided' "
cAndRequired = " AND "
endif
Now, always add your country selection
cYourSQL = cYourSQL + cAndRequired + " country = 'YourCountryValue' LIMIT 10 "
Run the query