I have done some looking but to be honest I just dont know what exactly to search. What I am trying to do is create a dynamic query as the tittle says. That is, one where I query only the variables that are sent to the php file. For example if I want to look up users but I only know their last name and username however for another user I know his firstname and email. I want to give the search form many fields and create a query based on what fields were entered.
Build up a list of WHERE clauses first and then add these into your query. For example:
$where = "";
if (isset($firstname) {
$firstname = mysql_real_escape_string($firstname);
$where .= "AND firstname='$firstname'";
}
if (isset($lastname) {
$firstname = mysql_real_escape_string($lastname);
$where .= "AND lastname='$lastname'";
}
mysql_query("SELECT * FROM users WHERE 1 ".$whereClause);
Of course you will need to change the table/row/etc names and add extra if (isset sections for each attribute.
Related
I'm looking for a way to use a field in a database as a query. This is what I have:
Column Title: banemail
The contents of this field is updated using the vBulletin Settings page. It stores the email addresses I want to ban from registering. I need a query that will delete all users who are already registered and use a banned email. I want to retrieve the contents from the table, then use it a query of my own.
Query so far:
$datastoreemails = $vbulletin->db->query_read("SELECT data FROM ".TABLE_PREFIX."datastore WHERE title = 'banemail'");
while($content = $vbulletin->db->fetch_array($datastoreemails))
{
echo $content['data']."<br />";
}
This output is:
.cc .co hotmail
How can I then turn this output into a query to delete anyone in the database that has an email address containg the above?
This works when I run it manually but I have 20-30 banned email address and I would like to do it all in 1 query if possible.
DELETE FROM TABLE_PREFIX_user WHERE email LIKE '%.com%';
TIA
I've never used vbulletin so you may need ot adjust the below. I didn't know what the users table was for examples so I just entered "users".
$datastoreemails = $vbulletin->db->query_read("SELECT data FROM ".TABLE_PREFIX."datastore WHERE title = 'banemail'");
//Create an array of banned emails.
$bannedEmails = [];
while($content = $vbulletin->db->fetch_array($datastoreemails))
{
//Explode your data by a space to return an array of items you are looking for
$bannedEmails = array_merge($bannedEmails, explode(" ", $content['data']));
}
//check if there is anything in the banned Emails, if so build your "delete" query
if(is_array($bannedEmails) && count($bannedEmails) > 0) :
$deleteQuery = "DELETE FROM ".TABLE_PREFIX."users WHERE";
$deleteWhere = "";
//Loop through the array adding each email stub in to the query
foreach($bannedEmails as $email):
//If this is the second time through the loop add the AND clause
if($deleteWhere != "") $deleteWhere .= "OR ";
//Add in where email like %hotmail.com% to match anything that looks like it.
$deleteWhere .= " email like '%" .$email . "%' ";
endforeach;
//Add the where on the end of the query
$deleteQuery .= $deleteWhere;
//Now all you need to do is execute the delete, I'm just going to print it out so you can check the
//sql first!
echo $deleteQuery;
endif;
From your code it looks like there is a single text field which will hold the banned email addresses in your database. If that is the case then you might want to use "query_first" like this $vbulletin->db->query_first($query) as that will just pull one row out, and you won't have to loop through the results. I've written the code above in case there are multiple rows with banned emails in, which should work even if there is just one.
you could use the reult of select fro delete directly
assuming you have
SELECT data FROM ".TABLE_PREFIX."datastore WHERE title = 'banemail'"
then you could
("DELETE
FROM " .TABLE_PREFIX ."user
WHERE email in ( SELECT data
FROM " .TABLE_PREFIX."datastore
WHERE title = 'banemail'" );
First of all, I'm a newbie PHP Developer.
I am developing a website which has a database that contains employee records. Each is assigned ID, Name, mobNo, Address etc..
There's a filter panel in the website with many filters to use like name filter, mobNo filter...
What I exactly want is, if 1 filter is selected, PHP will process just 1 MySQLi Query something like:
WHERE '$param' LIKE '%$paramValue%'
If user selects 2 filters, say Name and mobNo, PHP should process 2 queries something like:
WHERE '$param' LIKE '%$paramValue%'AND '$param2' LIKE '%$paramValue2%';
Chain should follow on..
I will use AJAX but you need NOT to worry about it.. I will integrate it myself.
You should use a function like isset() or any other way to check what the user selected, and then display the appropriate query.
i.e.
$query = "SELECT blabla WHERE ";
$int = 0; //checks if query needs an 'AND'
if (isset(filter1)) {
$query += "$param1 LIKE $paramValue1";
$int = 1;
}
if (isset(filter2)) {
if ($int = 1)
$query += " AND ";
$query += "$param2 LIKE $paramValue2";
$int = 1;
}
and so on.
Not quite sure that's what you need but hopefully its something like that. Be creative :)
$sql = "WHERE '$param' LIKE '%$paramValue%'";
if($param2 != '')$sql .= "AND '$param2' LIKE '%$paramValue2%'";
if($param3 != '')$sql .= "AND '$param3' LIKE '%$paramValue3%'";
...
if you want the paramenters to be modular you need to add them in pieces depending on wether they are set or not.
I'm trying to create a dynamic search query, based on the user input.
Requirements:
A user could fill in none, some, or all fields.
The query searches in a table for a record that matches all the requirements.
Now I have done my research, and I found out multiple ways on doing this. But none of them work, and if they do, they are far from practical.
Attempt:
At the moment I'm creating a query like this:
SELECT *
FROM assignments
WHERE (id = $id OR id = '')
AND (field1 = $field1 OR field1 = '')
This query works, but only if you fill in all the fields.
I got this from a stackoverflow article, that I can't find anymore, that said:
If the user has filled in an input field it will check the first rule
"id = $input"
and if the user hasn't specified any input it will check for "id = '' " and when it
checks for that, it will just return everything. Because it escapes the empty search rule.
But as you might already know, it doesnt work..
How would you suggest me to approach this?
Try getting all of the post vars and looping through them to see if they are valid, and then build your query
<?php
$id = $_POST[id];
$field1 = $_POST[field1];
$field2 = $_POST[field2];
$field3 = $_POST[field3];
$whereArr = array();
if($id != "") $whereArr[] = "id = {$id}";
if($field1 != "") $whereArr[] = "field1 = {$field1}";
if($field2 != "") $whereArr[] = "field2 = {$field2}";
if($field3 != "") $whereArr[] = "field3 = {$field3}";
$whereStr = implode(" AND ", $whereArr);
$query = "Select * from assignments WHERE {$whereStr}";
Something like that should handle what you need
You should start with a string like yours up to the WHERE statement, then after that you loop through all the fields the user wants to search with and add them to an array, then use the PHP function "implode" to glue the fields together with an AND statement as "glue".
Now add on the glued string to the startquery and voila!
I'd give example but on phone atm!
Building the query dynamically based on the responses is definitely a must. But another nice feature that allows users to find results based on even partial responses is using a MySQL REGEXP query. So for instance, if they wanted to find "maverick" in a Top Gun database, a query REGEXP = 'mav' | 'rick' would return results. This brings your search much closer to the search engine functionality that users are accustomed to.
Here's a REGEXP example, simplified.
I have a form where I am trying to implement a tag system.
It is just an:
<input type="text"/>
with values separated by commas.
e.g. "John,Mary,Ben,Steven,George"
(The list can be as long as the user wants it to be.)
I want to take that list and insert it into my database as an array (where users can add more tags later if they want). I suppose it doesn't have to be an array, that is just what seems will work best.
So, my question is how to take that list, turn it into an array, echo the array (values separated by commas), add more values later, and make the array searchable for other users. I know this question seems elementary, but no matter how much reading I do, I just can't seem to wrap my brain around how it all works. Once I think I have it figured out, something goes wrong. A simple example would be really appreciated. Thanks!
Here's what I got so far:
$DBCONNECT
$artisttags = $info['artisttags'];
$full_name = $info['full_name'];
$tel = $info['tel'];
$mainint = $info['maininst'];
if(isset($_POST['submit'])) {
$tags = $_POST['tags'];
if($artisttags == NULL) {
$artisttagsarray = array($full_name, $tel, $maininst);
array_push($artisttagsarray,$tags);
mysql_query("UPDATE users SET artisttags='$artisttagsarray' WHERE id='$id'");
print_r($artisttagsarray); //to see if I did it right
die();
} else {
array_push($artisttags,$tags);
mysql_query("UPDATE users SET artisttags='$artisttags' WHERE id='$id'");
echo $tags;
echo " <br/>";
echo $artisttags;
die();
}
}
Create a new table, let's call it "tags":
tags
- userid
- artisttag
Each user may have multiple rows in this table (with one different tag on each row). When querying you use a JOIN operation to combine the two tables. For example:
SELECT username, artisttag
FROM users, tags
WHERE users.userid = tags.userid
AND users.userid = 4711
This will give you all information about the user with id 4711.
Relational database systems are built for this type of work so it will not waste space and performance. In fact, this is the optimal way of doing it if you want to be able to search the tags.
I'm having problems getting $schoolname to read in the "insert into" mysqlcommand.
I'm just creating a small thing for a fan club that spans a few schools. So i created a different database table for each school. Each school has a unique id, and the table name corresponds to that. The code is below. Please help. Well, the problem area is the insert portion.
"insert into $schoolname ('cat','...)
For some reason $schoolname is not catching with the $_POST if statement
the mysql command " insert into .... " passes values if i specify a hard coded table name, but it does not pass values if i specify the variable ($schoolname) in place of the table name. I need to specify the variable because there a number of schools with each having their own tables.
<?php
require_once('include.php');
include('imageupload.php');
$schoolid='';
if(isset($_GET['schoolid']) && isset($_GET['schoolid']) != '')
{
$schoolid .= 'and id ='.$_GET['schoolid'];
}
$sqlschoolid = "select * from schools where status = 'Active' ".$schoolid;
$resschoolid = $obj->sql_query($sqlschoolid);
$school = $resschoolid[0];
$schoolname = $school['parameter'];
$schoolid2 = $school['id'];
if($_POST)
{
(isset($_POST['pr']) && $_POST['pr'] != "") ? $price=mysql_real_escape_string($_POST['pr']) : $pr="" ;
$sqlclass = "insert into $schoolname(`category`,`type`,`price`,`title`,`description`,`weburl`,`image`,`email`,`phone`,`address`,`city`,`state`,`zip`,`postdate`,`sponser`,`status`)
values('".$_POST['subcategory']."','".$_POST['type']."','".$pr."','".mysql_real_escape_string($_POST['title'])."','".mysql_real_escape_string($_POST['description'])."','".mysql_real_escape_string($_POST['weburl'])."','".$imagename."','".mysql_real_escape_string($_POST['email'])."','".mysql_real_escape_string($_POST['phone'])."','".mysql_real_escape_string($_POST['address'])."','".mysql_real_escape_string($_POST['city'])."','".mysql_real_escape_string($_POST['state'])."','".mysql_real_escape_string($_POST['zip'])."','".date('Y-m-d H:i:s')."','0','Active')";
}
?>
Since you haven't specified what problem you're seeing, this is only a guess:
if(isset($_GET['schoolid']) && isset($_GET['schoolid']) != '')
Shouldn't that be
if(isset($_GET['schoolid']) && $_GET['schoolid'] != '')
As a side note, consider what happens if the user entered the following in schoolid:
0; delete from schools
This is known as SQL Injection, and you should be using "bind variables" instead of building the query by concatenating strings.
The problem seems to be the below query:
$sqlschoolid = "select * from schools where status = 'Active' ".$schoolid;
What is $schoolid variable at the end? I see what is $schoolid variable and I assume that the variable isn't set correctly.
From what I understand is that the above query might be throwing an error and therefore $schoolname isn't populated at all. Can you please try to print how that query looks like?
EDIT 1 Reading the past discussions, it is clear that $schoolname variable is empty, i.e. has no value. It is not the scope issue because from your code $schoolname is in the global scope and is therefore available inside the $_POST IF check. So let us try to debug the code to analyse options:
Can you put an echo $sqlschoolid; just after where you have written the query? This will confirm that the query format is correct
Assuming that the query is good, let us now check if the query is returning the right data? I'm not sure what DB class are you using, so I can't say what does $obj->sql_query() returns? Perhaps the MySQL resultset. Anyways, can you put var_dump($resschoolid) right after where it is initialized? And another var_dump($school) below?
This is how I would like you to put the debug statements:
$sqlschoolid = "select * from schools where status = 'Active' ".$schoolid;
echo $sqlschoolid;
$resschoolid = $obj->sql_query($sqlschoolid);
var_dump($resschoolid);
$school = $resschoolid[0];
var_dump($school);
$schoolname = $school['parameter'];
$schoolid2 = $school['id'];
I hope the above will give more insight into the problem. Let me know if you've any questions.