PHP Advanced search - multiple parameters - php

I'm working on a advanced search function:
$colname_SokvansterImp = "-1";
mysql_select_db($database_Audiologiska, $Audiologiska);
if (isset($_POST['Personnummer_search']))
{
//Visa bara det som söks
$searchword = $_POST['Personnummer_search'];
$query_SokvansterImp = "SELECT * FROM patient left join person on person.Personnummer = patient.Patient left join vanster_implantat on vanster_implantat.Patv = patient.Patient WHERE vanster_implantat.patv LIKE '%".$searchword."%'";
}
else//Visa all data
{
$query_SokvansterImp = "select * from patient left join person on person.Personnummer = patient.Patient left join vanster_implantat on vanster_implantat.patv = patient.Patient";
}
$SokvansterImp = mysql_query($query_SokvansterImp, $Audiologiska) or die(mysql_error());
$row_SokvansterImp = mysql_fetch_assoc($SokvansterImp);
$totalRows_SokvansterImp = mysql_num_rows($SokvansterImp);
This is working for searching with one parameters, however, I'm wondering how to make it accepts multiple parameters? "Personnummer_search" is the name of my field. How can I make so it can search for example Name and/or Surname? I'm using Dreamweaver

Add a new conditional block ?
if (isset($_POST['Personnummer_search']))
{
//Visa bara det som söks
$searchword = mysqli_real_escape_string($_POST['Personnummer_search']);
$query_SokvansterImp = "SELECT * FROM patient left join person on person.Personnummer = patient.Patient left join vanster_implantat on vanster_implantat.Patv = patient.Patient WHERE vanster_implantat.patv LIKE '%".$searchword."%'";
}
else if(isset($_POST['Name_search']) && isset($_POST['Surname_search']))
{
$name = mysqli_real_escape_string($_POST['Name_search']);
$surname = mysqli_real_escape_string(($_POST['Surname_search']);
$query_SokvansterImp = "YOUR SQL QUERY...";
}
else//Visa all data
{
$query_SokvansterImp = "select * from patient left join person on person.Personnummer = patient.Patient left join vanster_implantat on vanster_implantat.patv = patient.Patient";
}

Check out the PHP Site, There is a function called "func_get_args"
http://php.net/manual/en/function.func-get-args.php

Ok, to search for all possible filters, you can do:
$where = array();
if (isset($_POST['Personnummer_search']))
{
$searchword = mysqli_real_escape_string($_POST['Personnummer_search']);
$where[] = "vanster_implantat.patv LIKE '%".$searchword."%'";
}
if(isset($_POST['Name_search']))
{
$name = mysqli_real_escape_string($_POST['Name_search']);
$where[] = "nameField LIKE '%".$name."%'";
}
if(isset($_POST['Surname_search']))
{
$surname = mysqli_real_escape_string($_POST['Name_search']);
$where[] = "surnameField LIKE '%".$surname."%'";
}
if(count($where))
{
$query_SokvansterImp = "SELECT * FROM patient left join person on person.Personnummer = patient.Patient
left join vanster_implantat on vanster_implantat.Patv = patient.Patient
WHERE ".implode(" AND ",$where);
}
else//Visa all data
{
$query_SokvansterImp = "select * from patient left join person on person.Personnummer = patient.Patient left join vanster_implantat on vanster_implantat.patv = patient.Patient";
}

Related

MySQL - Join part of query to a new query?

I've got the following code which queries a table. Then it uses the result to make another query. That result is then used to make a third query.
But how do I grab the userid field from the 2nd query in order to grab a name from a users table and join that to the result of the 3rd query?
Please note once I figure out the code I will convert this to a prepared statement. It's just easier for me to work with legacy code when figuring out queries.
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "SELECT opid, userid from audioposts WHERE audioid = $newaudio" ;
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$opid = $row[opid];
$opuserid = $row[userid];
$getreplies =
"SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
} "SELECT * from audioposts ap WHERE opid = $opid AND opid
NOT IN (SELECT opid FROM audioposts WHERE audioposts.opid = '0' )";
$getreplyresults = $dblink->query($getreplies);
if ($getreplyresults->num_rows>0) {
while ($row = $getreplyresults->fetch_assoc()) {
$dbdata[]=$row;
}
}
}
}
}
}
echo json_encode($dbdata);
The result I need are rows of json encoded instances of $getreplyresults with the $row[userid] from the original result joined to each row.
Here's what I did in the end. Now I just have to figure out how to convert this to a prepared statement in order to avoid malicious injection.
$selectaudioid = "SELECT audioid FROM subscribe WHERE userid = $userid";
$audioResult=$dblink->query($selectaudioid);
if ($audioResult->num_rows>0) {
while ($row = $audioResult->fetch_assoc()) {
$newaudio = $row[audioid];
$getallaudio = "
SELECT ap.audioid, ap.title, us.name FROM audioposts ap
INNER JOIN audioposts a2 ON a2.audioid = ap.opid
INNER JOIN users us ON us.id = a2.userid
WHERE ap.opid = $newaudio AND ap.opid <> '0'
";
$getallresult = $dblink->query($getallaudio);
if ($getallresult->num_rows>0) {
while ($row = $getallresult->fetch_assoc()) {
$dbdata[]=$row;
}}}}

Three SELECT and two jsons

I created a SELECT to get my communities.
And create two SELECTs to get the communities I'm following.
But I get just my communities.
I do not get the communities I'm following.
$user_id = $_GET["id"];
$row1 = array();
$row2 = array();
// get my communities
$res1 = mysql_query("SELECT * FROM communities where user_id = '$user_id'");
while($r1 = mysql_fetch_assoc($res1)) {
$row1[] = $r1;
}
// get "id" of my communities I'm following
$res = mysql_query("SELECT * FROM communities_follow where user_id = '$user_id'");
while($r = mysql_fetch_assoc($res)) {
$coid = $r["coid"];
// get my communities I'm following
$res2 = mysql_query("SELECT * FROM communities where id = '$coid'");
while($r2 = mysql_fetch_assoc($res2)) {
$row2[] = $r2;
}
}
$resp = array_replace_recursive($row1, $row2);
print json_encode( $resp );
The inner join will get you those communities only, where you are following:
SELECT c.* FROM communities c
INNER JOIN communities_follow cf ON c.id = cf.coid
WHERE cf.user_id = '$user_id';
Or, without a JOIN:
SELECT * FROM communities
WHERE EXISTS (SELECT 1 FROM communities_follow cf
WHERE c.id = cf.coid AND cf.user_id = '$user_id')
Try this sql.
SELECT * FROM communities c LEFT JOIN communities_follow cf ON c.user_id = cf.user_id where
cf.user_id = '$user_id';

Complicated array comparison

1- I'm building a comparison app which compares the relationship between two users.
If the user A and user B has the same country address then it will print alert to any of the same similar values.
2- There is another issue which is some users has multiple addresses for example user A has address x1 and user b has address x1 and address x2, in this scenario how do I compare user A's address with the multiple addresses with user B and alert that the address x1 is matched between the two users?
here is the queries for both users
$query1 = "
SELECT
a.PID, a.`Name`, a.Avatar, a.Email,
b.City, a.LDate, b.Country, b.MPhone,
b.Gender, b.Birthday
FROM
`Profile` AS a
LEFT JOIN Details AS b ON a.PID = b.PID
WHERE
a.PID = '1'
";
$UserInfo1 = mysqli_query($mysqli, $query1);
while( $row = mysqli_fetch_array($UserInfo1) ){
$Avatar1 = "{$row['Avatar']}";
$Name1 = "{$row['Name']}";
$Email1 = "{$row['Email']}";
$Country1 = "{$row['Country']}</td>";
$MPhone1 = "{$row['MPhone']}</td>";
$Gender1 = "{$row['Gender']}</td>";
$City1 = "{$row['City']}</td>";
$Birthday1 = "{$row['Birthday']}</td>";
}
$query2 = "
SELECT
a.PID, a.`Name`, a.Avatar, a.Email,
b.City, a.LDate, b.Country, b.MPhone,
b.Gender, b.Birthday
FROM
`Profile` AS a
LEFT JOIN Details AS b ON a.PID = b.PID
WHERE
a.PID = '2'
";
$UserInfo2 = mysqli_query($mysqli, $query2);
while( $row = mysqli_fetch_array($UserInfo2) ){
$Avatar2 = "{$row['Avatar']}";
$Name2 = "{$row['Name']}";
$Email2 = "{$row['Email']}";
$Country2 = "{$row['Country']}</td>";
$MPhone2 = "{$row['MPhone']}</td>";
$Gender2 = "{$row['Gender']}</td>";
$City2 = "{$row['City']}</td>";
$Birthday2 = "{$row['Birthday']}</td>";
}
3- The final results is that I want to make flowchart and point the matched information to each other something like this screenshot:
What would be the best and simplest way to make this comparison in php or Mysql?
Your help is highly needed and appreciated.

adding a where variable inside sql

if user select anything besides "all" it will lead to a where statement involving KodDaerah
$where = '';
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".mysql_real_escape_string($where)."
ORDER BY koddaerah.NamaDaerah ";
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
if user select all then the system will just use the current sql statement that i provided, for now im not sure what's wrong, so here is where user select the KodDaerah from drop down list box
<?php include('dbase.php');
$sql = "SELECT KodDaerah, NamaDaerah FROM koddaerah";
$result = mysql_query($sql);
echo "<select name='KodDaerah' id='KodDaerah' class='input_field' required />
<option>Pilih Daerah</option>
<option value='all'>Seluruh Pahang</option>";
while ($kod = mysql_fetch_array ($result)){
echo "<option value=".$kod['KodDaerah'].">" .$kod['NamaDaerah']."</option>
<option value='all'>Seluruh Pahang</option>";
}
echo "<?select>";
?>
The problem is now even when i select a certain KodDaerah, it will just run the provided sql query without using the WHERE statement in the $where. Can anybody help?
EDIT:
$sql = $sql . $where;
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);
try to move up the if statement:, remove mysql_real_escape_string
(escape before)
$where = '';
if($KodDaerah != "all"){
$where = "AND maklumatakaun.KodDaerah = '$KodDaerah' "; //Add your where statement here
//Whatever you want to do
}
else {
$where = "";
}
$sql= "SELECT * FROM maklumatakaun
LEFT JOIN detailakaun ON maklumatakaun.id = detailakaun.id
LEFT JOIN maklumatbilakaun ON maklumatakaun.NoAkaun = maklumatbilakaun.NoAkaun
LEFT JOIN kodjenisakaun ON detailakaun.KodJenisAkaun = kodjenisakaun.KodJenisAkaun
LEFT JOIN kodlokasi ON detailakaun.KodLokasi = kodlokasi.KodLokasi
LEFT JOIN kodkategori ON maklumatakaun.KodKategori = kodkategori.KodKategori
LEFT JOIN koddaerah ON maklumatakaun.KodDaerah = koddaerah.KodDaerah
WHERE maklumatakaun.KodKategori = '$KodKategori'
AND detailakaun.KodJenisAkaun = '$KodJenisAkaun'
AND maklumatbilakaun.BulanBil = '$BulanBil'
AND maklumatbilakaun.TahunBil ='$TahunBil'
".$where."
ORDER BY koddaerah.NamaDaerah ";
and then do not append $where again
$result = mysql_query ($sql);
$BilAkaun = mysql_num_rows ($result);

CodeIgniter partially override a method

I am trying to refactor this code a bit. Originally I had two different models, both extending MY_Model. However, most of the code was repetitive so now I am having First_model extend MY_Model and Second_model extends First_model. I cleaned up most of code from Second_model that it inherits from First_model, but I have several methods within Second_model that are only slightly different from the same method in First_model. Consider the following code:
First_model
class First_model extends MY_Model
{
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date('Y');
$month = date('n');
$sql = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
post.ts_created,
UNIX_TIMESTAMP(post.ts_created) post_timestamp,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
sum(ka.karma) monthly_karma
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (SELECT
IFNULL(u_all.id, user.id)
FROM UserAccounts ua
INNER join Users u ON u.id = ua.user_id
LEFT join Users u_all ON u_all.facebook_uid = u.facebook_uid
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year}
AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
$query = $this->db->query($sql);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row["id"]] = $row;
}
return $functionResults;
}
}
Second_model
class Second_model extends First_model
{
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date("Y");
$month = date("n");
$sql = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
UNIX_TIMESTAMP(post.ts_created) ts_created,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
SUM(ka.karma) monthly_karma,
post.answer_status_flags
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (
SELECT
IFNULL(u_all.id, user.id)
FROM
UserAccounts ua
INNER JOIN Users u ON (u.id = ua.user_id)
LEFT OUTER JOIN Users u_all ON (u_all.facebook_uid = u.facebook_uid)
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year} AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
$query = $this->db->query($sql);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row['id']] = $row;
}
return $functionResults;
}
}
Notice the only thing different is the query in the $sql variable. I am wondering can I somehow make the method in the first model protected and only change the query in the second? Or is there a more efficient way to trim down this code? I have several methods this same thing applies to and it seems a bit much to keep redefining the methods in the new Class.
I would think about pass the $sql as a variable in your models:
In your First Model you would have:
private $sqlPostId = '';
public function __construct() {
$this->sqlPostId = "SELECT
post.id,
post.useraccount_id,
user.first_name user_first_name,
user.last_name user_last_name,
user.gender user_gender,
user.profile_pic user_profile_pic,
post.class_id,
post.school_id school_id,
school.display_name school_name,
school.state,
school.city,
post.karma_awarded_id,
post.is_parent_post,
post.reply_to_post_id,
post.comment_text,
post.image_url,
post.ts_created,
UNIX_TIMESTAMP(post.ts_created) post_timestamp,
post.ts_modified,
user.facebook_uid user_facebook_id,
user.id user_id,
sum(ka.karma) monthly_karma
FROM
WallPosts post
JOIN UserAccounts account ON (account.id = post.useraccount_id)
JOIN Users user ON (user.id = account.user_id)
LEFT JOIN Schools school ON (post.school_id = school.id)
LEFT JOIN KarmaAwarded ka ON (ka.user_id IN (SELECT
IFNULL(u_all.id, user.id)
FROM UserAccounts ua
INNER join Users u ON u.id = ua.user_id
LEFT join Users u_all ON u_all.facebook_uid = u.facebook_uid
WHERE ua.id = post.useraccount_id)
AND YEAR(ka.ts_created) = {$year}
AND MONTH(ka.ts_created) = {$month})
WHERE
post.id IN ({$postIDSqlArray})
GROUP BY post.id";
}
private function getPostsByPostIDs($postIDs)
{
$postIDs = $this->strictCastIntArray($postIDs);
$postIDSqlArray = implode(",", $postIDs);
$year = date('Y');
$month = date('n');
// Here you use the defined variable in the constructor
$query = $this->db->query($this->sqlPostId);
$queryResults = $query->result_array();
$functionResults = array();
foreach ($queryResults as $row) {
$functionResults[$row["id"]] = $row;
}
return $functionResults;
}
And then you just have to change the SQL in the construct function in your second Model and go.

Categories