Quick question on a method to search mysql database with php.
Right now, I have a function that is supposed to search and return results. Say I have two databases, one being User and one being Profile. User stores the username, email, password. while Profile stores user first name, last name, address, birth day. Right now, I'm not sure how to go about this, but this is what I have so far.
I want to be able to search both tables and return a list of results via a table which I've got covered, but I don't know how to get the intricacies down.
The function will contain either NULL or value of the variable. Right now, this is my sketch up:
if(!empty($username)):
$append .= "WHERE";
$append .= "username = ".$username."";
endif;
if(!empty($email)):
$append .= "WHERE";
$append2 .= "email= ".$email."";
endif;
if(!empty($firstname)):
$append .= "WHERE";
$append2 .= "firstname = ".$firstname."";
endif;
if(!empty($lastname)):
$append .= "WHERE";
$append2 .= "lastname= ".$lastname."";
endif;
$sql = "select * FROM Users ".$append."";
$result = mysql_query($sql);
$sql2 = "select * FROM Profile ".$append2."";
$result2 = mysql_query($sql2);
$userId = mysql_fetch_row($result2);
$userId['id'] = $id; <-- this is the one I will call to display data.
How can I efficiently do this and search/return all unique/distinct user ID's? Both tables include a user ID / incremented ID number (User table is User_ID, Profile table is acct_id). I know this code is a bit wrong... Don't worry about escaping - I;'ve gotten that sorted. Should I use a JOIN statement?
Other problem I am facing is changing between WHERE and AND because sometimes if one var is set but another isn't, then we must use AND instead of just one WHERE. Any idea how to tackle this issue?
Thanks for your input!
For your WHERE clause it is probably best to use arrays and then implode() like this
$and_where = array();
if (!empty($username))
$and_where[] = "username = ".$username;
if (!empty($email))
$and_where[] = "email = ".$email;
//etc
if (count($and_where) > 0)
$where = " WHERE ".implode(" AND ", $and_where);
else
$where = "";
Are the two tables related in some matter? If acct_id is a foreign key to User_id you can just use an INNER JOIN ($where as shown above)
$query = "SELECT Users.col, ..., Profile.col, ... FROM Users
INNER JOIN Profile ON Users.user_id = Profile.acct_id".$where;
If they aren't, you could simply UNION them
$users_and_where = array();
$profiles_and_where = array();
if (!empty($username))
$users_and_where[] = "username = ".$username;
if (!empty($email))
$users_and_where[] = "email = ".$email;
//etc
if (!empty($firstname))
$profiles_and_where[] = "firstname = ".$firstname;
if (!empty($lastname))
$profiles_and_where[] = "lastname = ".$lastname;
//etc
if (count($users_and_where) > 0)
$users_where = " WHERE ".implode(" AND ", $users_and_where);
else
$users_where = "";
if (count($profiles_and_where) > 0)
$profiles_where = " WHERE ".implode(" AND ", $users_and_where);
else
$profiles_where = "";
$query = "(SELECT col1, col2, ... FROM Users".$users_where.")
UNION
(SELECT col1, col2, ... FROM Profile".$profiles_where.")";
You should try to avoid * in your queries and select the rows specifically, this way you don't have too much overhead in the future, when additional columns are introduced that your code doesn't use here.
Related
I have to insert several values in a PgSQL Table using these variables
$knr = $reader->getAttribute('Nr');
$kname = $reader->getAttribute('Name');
And this insertion code:
$SQL = "";
$SQL .= "SELECT
(konzern).knr AS knr, (konzern).name AS name
FROM konzern";
$SQL .= "INSERT INTO konzern (";
$SQL .= "knr, name";
$SQL .= ") VALUES (";
$SQL .= "'".$knr."', '".$kname."'";
$SQL .= ");".PHP_EOL;
And I want to check if the table "Konzern" already have a row with the $knr and if yes it should insert into this, if not it should create a new row
$query = doQuery("select nr from konzern where knr = '".$knr."'");
$num_rows = ($query->num_rows);
if ($num_rows > 0) {
// do nothing
}
else {
$sql .= "select nextval('konzern_nr_seq')";
}
But I have some problems puting this into the right order.
Can someone complete this code?
You can do this with a single query in this way :
INSERT INTO konzern SELECT val1, val2
WHERE NOT EXISTS(
SELECT nr from konzern where knr = 'var1'
)
Implement this approach it will be more straigth forward .
And remember to use query parameters instead of concatenating the query text, to avoid SQL Injections.
Trying to create a dynamic search functionality.
Goal : allowing user to search by email (if not empty), if empty (by last name), if both are not empty, than by both, etc.
I know I can write if statement depicting every scenario and than insert SQL command based on that, question is can this be handled in a more simplified manner. Thanks for your help.
Current function set up does OR across all fields, values are coming from $_POST:
find_transaction($email,$last_name,$first_name, $transaction_id)
{
GLOBAL $connection;
$query = "SELECT * ";
$query .= "FROM transactions WHERE ";
$query .= "email='{$email}' ";
$query .= "OR last_name='{$last_name}' ";
$query .= "OR first_name='{$first_name}' ";
$query .= "OR transaction_id='{$transaction_id}' ";
$query .= "ORDER BY date DESC";
$email = mysqli_query($connection,$query);
confirm_query($email);
return $email;
}
I do this all the time, it's not too much work. Basically build your WHERE statement dynamically based off your POST variables, using a series of if statements.
For example:
$where_statement = "";
// First variable so is simpler check.
if($email != ""){
$where_statement = "WHERE email = '{$email}'";
}
// Remaining variables also check if '$where_statement' has anything in it yet.
if($last_name != ""){
if($where_statement == ""){
$where_statement = "WHERE last_name = '{$last_name}'";
}else{
$where_statement .= " OR last_name = '{$last_name}'";
}
}
// Repeat previous 'last_name' check for each remain variable.
SQL statement would change to:
$query = "SELECT * FROM transactions
$where_statement
ORDER BY date DESC";
Now, the SQL will only contain filters depending on what values are present, so someone puts in just email, it would generate:
$query = "SELECT * FROM transactions
WHERE email = 'smith#email.com'
ORDER BY date DESC";
If they put in just last name, it would generate:
$query = "SELECT * FROM transactions
WHERE last_name = 'Smith'
ORDER BY date DESC";
If they put both, would generate:
$query = "SELECT * FROM transactions
WHERE email = 'email#email.com' OR last_name = 'Smith'
ORDER BY date DESC";
Etc., etc.
You could add as many variables you wish here, and basically if the specific variable is not blank, it will add it to the "$where_statement", and depending on if there is anything in the "$where_statement" yet or not, it will decide to start with = "WHERE ", or append .= " OR" (notice the '.=' and the space before 'OR'.
Better use Data Interactive table : http://datatables.net/
It's useful and no SQL-injection :) Good luck !
Im trying to fill query with array. As I know I can display array with function foreach(); but im not able to put it in mysql query
Im trying to do something like this:
<?php
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");
$query = mysql_query("SELECT * FROM users WHERE user = '1'".
foreach($arr as $arr) {
echo "AND user = '".$arr++."'";
}
." ORDER BY id";
?>
Script have to display this as:$query = mysql_query("SELECT * FROM users WHERE user = '1' AND user = 'arr_1' AND user = 'arr_2' AND user = 'arr_3' AND user = 'arr_4'");
But this doesnt work becouse you cant put foreach() in mysql_query();.
So what I need is script that do the same thing ( display array in query string )
Thanks.
if you want to add multiple conditions from array, do concatenation instead of echo
<?php
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");
$query = mysql_query("SELECT * FROM users WHERE user = '1'";
foreach($arr as $id) {
$query .= "AND user = '".$id."'";
}
$query .= " ORDER BY id";
?>
Not the best solution, but an alternative:
$arr = array("arr_1", "arr_2", "arr_3", "arr_4");
$arr_string="'".implode("','", $arr)."'"; // surround values in quotes
$query = mysql_query("SELECT * FROM users WHERE user IN (".$arr_string.") ORDER BY id";
Im trying to call all users from a database with the same interests as the current, logged in user on my website.
I have the following
// Get Session USER interest
$interestsquery = "SELECT `interest` FROM `user_interests` WHERE `user_id` = " . $usersClass->userID();
$result = mysql_query($interestsquery);
$interests = array();
while(list($interest) = mysql_fetch_array($result))
$interests[] = $interest;
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interests_query = "SELECT * FROM produgg_users
join user_interests on produgg_users.id = user_interests.user_id
where interest = '$interest1' and produgg_users.id != '".$usersClass->userID()."'";
$interests_result = mysql_query($interests_query) or die(mysql_error());
if($interests_result != 0) {
while($interests_row = mysql_fetch_array($interests_result, MYSQL_ASSOC))
{
echo $interests_row['user_id'];
}
}
else
{
print "No users to display!";
}
//END SAME INTERESTS
which doesnt bring back any data, yet if I add (beneath //USers with Same Interests)
$interest1 = 'footy';
the interests_query seems to work, can anybody see where im going wrong?
My problem seems to lie here...
$interest1 = $interests['1'];
$interest2 = $interests['2'];
$interest3 = $interests['0'];
// END INTERESTS
//USers with Same Interests
$interest1 = 'footy';
If I manually assign a value to $interest variable it works, but i need to get use the value from the array above, does this make sense?
If your code brings back the correct data when you add $interest1 = 'footy'; line, that would imply that there is something wrong with the value of that variable when you don't. Have you tried var_dump($interest1); right under //Users with Same Interests line to see what kind of input you get from your interestsquery?
I would expect the var_dump to not return a valid string (since if it would, the query would work following the $interest1 = 'footy'; assumption), so you would have to look at what interestsquery returns wrong.
Looks like you querying user_id from user_interests as number, but from produgg_users as string. Maybe there's a problem
You can do it with one query:
$userID = mysql_real_escape_string($usersClass->userID());
$sql = "
SELECT * FROM user_interests AS ui1
JOIN LEFT user_interests AS ui2 ON ui1.id = ui2.id
JOIN LEFT produgg_users AS pu ON ui2.user_id = pu.id
WHERE ui.user_id = " . userID ;
*Here is what I am trying to acheive: *
Basically I have a form where people can submit events to our database. In the CMS I have a page which displays a record of the number of events.
*Here is what I have: *
After the button is clicked, this script is called:
if($subject_type == 'Event') {
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
$querys = $this->tep_db_query($query);
$rows = $this->tep_db_fetch_array($querys);
extract($rows); //extract rows, so you don't need to use array
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
This works fine, however I cant seem to solve the next bit
This is the Problem
As you can see, it checks the database for the current month and adds it, this is providing that the sitename and that month are there, not a site and another month.
How would I get it to add the row in IF the sitename and month are not there?
I have been manually adding the months in now so that it works, and I am sure you can agree that's a ball ache.
Cheers peeps
if you want to check if site A + Month 11 exists do a select query against it and store the number of rows returned in a variable. ( $exists = mysql_num_rows("your query here"); )
then do an if statement against the $exists variable and proceed as you wish
if($exists) {
// update
} else {
// add
}
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$eventid = 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
}
}
this is what I have for the else statement there, however it will add one to the value if its there but will not add a new entry if its isnt.. ?
I don't see exactly how your method "checks the database for the current month and adds it "; I'll just assume that the tep_db_perform() method of your class handles this somehow.
(uhk! n00bed it; rest of the post was somehow chopped off?) Since you're already hitting the database with the select with the intent of using the data if a record is found, then you could use the resultset assigned to $rows as a means of checking if a record exists with SITENAME and Month.
See below:
if($subject_type == 'Event') {
// build query to check the database for sitename, month and year.
$query = "SELECT town, update_id, event_validex ";
$query .= "FROM dev_town ";
$query .= "LEFT JOIN updates ON dev_town.town_id = updates.town ";
$query .= " WHERE sitename = '".SITENAME."'";
$query .= " AND month = " .date('m')." AND year =" .date('Y');
// Execute Query(wrapper for $result = mysql_query I guess?)
$querys = $this->tep_db_query($query);
// Get a resultset from database. --> you could merge this into one method with $this->tep_db_query
$rows = $this->tep_db_fetch_array($querys);
if(count($rows) > 0) {
extract($rows); //extract rows, so you don't need to use array --> I try to stay away from extract() as it makes for random variables being created.
$eventid = $event_validex + 1;
$sql_data_array = array('event_validex' => $eventid);
$submit_to_database = $this->tep_db_perform('updates', $sql_data_array, 'update', "town='".$town."'");
} else {
// insert new record into database
// updated with code to execute insert SQL query.
$insert = "INSERT INTO updates ('town','month','year','event_validex') VALUES ('".$town."','". date('m')."','". date('Y')."','1')";
$result = $this->tep_db_query($query);
}
....
}
If I've misunderstood something, please let me know, happy to work through it with you.
Hope this helps. :)