Check if databasefield contains value from imploded variable - php

$users = explode(",", $particiTemp);
foreach($users as $user) {
echo "$user";
}
$checkSQL = mysql_query("SELECT * FROM this WHERE x>'$y' && v<'$z' && user IN ($particiTemp)");
while($checkData = mysql_fetch_array($checkSQL)){
}
I´m kinda stuck right here...
I want to check if $particiTemp (for example: $particiTemp = "2,23,11,4,") is in the field $checkData[user] ($checkData[user] = "5,22,11,23";).
I tried to explode both and tried mysql IN but I don´t know how to check if the field $checkData[user] CONTAINS one of the imploded $particiTemp

"In" clause need values as '2','23','11','4' instead of "2,23,11,4,"
so manipulate your array for result.
$innval = '';
foreach($users as $user) {
if($user != '')
$innval .= "'".$user."',";
}
$innval = substr($innval,0,-1); // to remove last extra ,
and now use this $innval variable in your query to get result
$checkSQL = mysql_query("SELECT * FROM this WHERE x>'$y' && v<'$z' && user
IN ($innval)");
Hope this helps

Idea: explode array to check, for each a mysql_query with INSTR.
Should work, trying it now.

Related

How to add Distinct function to a array or return only unique values

How to add distinct function so that the result is not repetitive?
Any help is much appreciated.
$yearnow=$_POST['yearnow'];
$stmts = $db->query("select * from tblgencol where year='$yearnow'");
while($row= $stmts->fetch(PDO::FETCH_OBJ)){
$pdf->Row(Array($row->busname,$row->business));
}
}
Here is the output of my code:
I'm using fpdf to display my data from database. And its working fine. Its just that the name is repeating.
This is what I want to achieve:
or what if i want to display this?
option 2
To achieve your desired result, you need to check if the current business name is the same as the last displayed one, and if so, not output it:
$yearnow=$_POST['yearnow'];
$stmts = $db->query("select * from tblgencol where year='$yearnow'");
$busname = '';
while ($row = $stmts->fetch(PDO::FETCH_OBJ)) {
$thisbusname = ($row->busname != $busname) ? $row->busname : '';
$pdf->Row(array($thisbusname,$row->business));
$busname = $row->busname;
}

IN clause is not working properly in MYSQL php

I have a sql query like this
$statusData = $DB->get_records_sql("SELECT id, element, value FROM {scorm_scoes_track} WHERE scormid = ? AND userid = ? AND element =$DB->get_in_or_equal('cmi.core.lesson_status','cmi.core.total_time')", array($scorm_id, $userid) );
So i am trying to fetch the values from query
<?php
$statusData = reset($statusData);
if($statusData->element == 'cmi.core.lesson_status')
$status = $statusData->value ;
elseif($statusData->element == 'cmi.core.total_time')
$totaltimes = $statusData->value ;
but its just showing only status value..it's not showing total time value..Can any one help me
Thanks in advance..
You do not have any in operator in your code, so there is nothing that could work at all as an in!
Replace the = with in and remove the moodle call as well as shown below:
...AND element IN ('cmi.core.lesson_status','cmi.core.total_time')

Return value in foreach loop in CodeIgniter

I am having some trouble in returning values from model to controller Using CodeIgniter. I am passing two arrays from controller to model. I am checking whether both the arrays are not empty and looping them using foreach loop to fetch some values from database and returning the query to controller. Here's my current code
if (!empty($search_for_area) && !empty($search_for_requirement))
{ foreach($search_for_requirement as $search_value_1)
{
foreach($search_for_area as $search_value_2)
{
if($search_value_2 != null && $search_value_1 != null)
{
$nearbytution = $this->db->query('select name,area,contactno from tut_listing where area = "'.$search_value_2.'" and categoryfilter like "%'.$search_value_1.'%" and partner > "" group by name');
print_r($nearbytution->result());
}
}
}
//Line 1
}
print_r($nearbytution->result()); works fine and i am able to view the results. Where should i put return $nearbytution; so that i can get all the fetched values? I tried it in Line 1 but i was getting only values of last array value.
function returnStuff($search_for_area,$search_for_requirement) {
$arr_area = array();
$arr_filter = array();
if ( ! empty($search_for_area) and ! empty($search_for_requirement)) {
foreach($search_for_requirement as $search_value_1) {
foreach($search_for_area as $search_value_2) {
if($search_value_2 != null && $search_value_1 != null) {
$arr_area[] = $this->db->escape($search_value_2);
$arr_filter[] = $this->db->escape_like_str($search_value_1);
}
}
}
}
$str_area = 'NULL';
if ($arr_area)
$str_area = implode(', ', $arr_area);
$str_filter = "'^-$'";
if ($arr_filter)
$str_filter = "'(".implode('|', $arr_filter).")'";
$query = $this->db->query("
SELECT name, area, contactno
FROM tut_listing
WHERE area IN ({$str_area}) AND categoryfilter REGEXP {$str_filter} and partner > '' group by name
");
return $query->result();
}
Seriously, do consider this approach. You only need to bother the poor Mysql server with one call and you get all the data you want at the same time.
Apart from that, practice consistent style in your code. It will save both your time and your hair in the long run.
CodeIgniter escape()
MySQL REGEXP
Try this in the loop:
$nearbytution[] = $this->db->query('select name,area,contactno from tut_listing where area = "'.$search_value_2.'" and categoryfilter like "%'.$search_value_1.'%" and partner > "" group by name')->result();
return $nearbytution;may then be placed at your "Line 1". It will contain an array of query results.
Unless I misunderstand your question why don't you just store all the results in a big array and then return that array?
function returnStuff($search_for_area,$search_for_requirement) {
$data = array();
if (!empty($search_for_area) && !empty($search_for_requirement)) {
foreach($search_for_requirement as $search_value_1) {
foreach($search_for_area as $search_value_2) {
if($search_value_2 != null && $search_value_1 != null) {
$nearbytution = $this->db->query('select name,area,contactno from tut_listing where area = "'.$search_value_2.'" and categoryfilter like "%'.$search_value_1.'%" and partner > "" group by name');
$data[] =$nearbytution->result());
}
}
}
}
return $data;
}
Now $data will be an array of results, each containing the query results. If your result set has to be cleaned up (to remove duplicates for instance) you can just loop through it and do that cleanup.
What you could also maybe do is build a large SQL query in your foreach loops and then just do that one big query and return the results.

Creating an SQL query when the values to be used in the query are unknown

I have some search functionality that works with 3 drop down boxes. Based on the criteria chosen, a profile is returned. The 3 drop downs are:
County
Constituency
Gender
Now I am trying to build a query but have just realised that actually a person does not have to choose an option from each drop down and nor do I want them to.
So for instance I do not want to disable the search button until an option is selected from each drop down.
Having chosen a value from any drop down, and possibly having no value selected from any drop down at all, and just clicking the search button, I am trying to understand how I can cope with the unknown combinations.
My first thought was that I could use something like a truth table but I imagine this is simply overkill and in fact this is a very common piece of functionality.
Then I thought maybe I could have something like:
$county = "$_GET['county'];";
$constituency = "$_GET['constituency'];";
$gender = "$_GET['gender'];";
Then I could check to see if they are empty and somehow use this value, e.g.
if($county !== '') {
???SOMEHOW MAKE USE OF THIS IN AN SQL QUERY???
PERHAPS PASS IT TO ANOTHER PARAMETER
$sqlparams = "county = '$county'";
}
SELECT * FROM profile
WHERE {$sqlparams};
I think I'm on the right tracks but could use some guidance.
All help is greatly appreciated.
This should do want you want, I think.
<?php
$tooLookFor = array("county", "constituency", "gender");
foreach($tooLookFor as $key){
if(isset($_GET[$key]) && strlen($_GET[$key])>0){
$queryParams[] = $key.'="'.$_GET[$key].'"';
}
}
$query = "SELECT * FROM profile WHERE ".implode(' AND ', $queryParams);
?>
You could do something like:
$county = $_GET['county'];
$constituency = $_GET['constituency'];
$gender = $_GET['gender'];
$sqlparams = array();
if($county !== '') {
$sqlparams[] = "county = '$county'";
}
if($constituency !== '') {
$sqlparams[] = "constituency = '$constituency'";
}
if($gender !== '') {
$sqlparams[] = "gender = '$gender'";
}
$query = "SELECT * FROM profile";
if (count($sqlparams) > 0) {
$query .= " WHERE " . implode(" AND ", $sqlparams);
}
You can do that with something like this:
$where = array();
//repeat as needed
$where[$column] = $value;
$where2 = array();
foreach($where as $key => $value){
$where2[] = "$key = '$value'";
}
$where_string = implode(' AND ', $where2);
$where_string will have the string to insert after WHERE.
Yes, you are on the right track, you're just not at the right switch yet. ;)
You can't build the query until you know what you have to work with. So first, in your validation, determine (as you are doing) with the key words actually are and what fields they represent. Presumably these map to fields in tables, maybe 3 tables? Point is, your query will need to be dynamically built.

Array_Push not adding to end of array, it is replacing the whole array

I have tried to create a small 'bookmarking' feature for my website. Users are able to click on the ".bookmarkButton" which will execute the following script:
<!--Add To Bookmarks-->
$(".bookmarkButton").click(function() {
var pid=$(this).closest('div').attr('id');
$('#noBookmark').hide();
$.post('bookmarks/addBookmark.php', 'rid=' + pid, function (addBookmark) {
$("#bookmarkResults").add(addBookmark);
});
});
Here is the code for "addBookmark.php":
<?php
session_start();
if (isset($_SESSION['ridArray']) && count($_SESSION['ridArray'] > 0)){
addBookmark();
} else if (isset($_POST['rid']) && !isset($_SESSION['ridArray'])) {
$_SESSION['ridArray'] = array();
addBookmark();
}
function addBookmark() {
if (is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray']) && isset( $_POST['rid']) ) {
array_push($_SESSION['ridArray'], $_POST['rid']); //push the id value from post to the session array
//$_SESSION['ridArrayClean'] = array_unique($_SESSION['ridArray']); //remove duplicates
print_r($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
// Get all the data from the "example" table
$result = mysql_query("SELECT * FROM example WHERE id = $x")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}}}
?>
The variable $_SESSION['ridArray'] holds the array with all the id's that have been accumulated.
My problem is that this script works only when one item is bookmarked. When there is more than one product bookmarked, I only get the product name that was last bookmarked and not every thing that I've bookmarked.
So for example instead of getting multiple product id's after clicking the bookmarkButton class like this: 0,1,2,3 in the array. I only get the one that was clicked last i.e. 6.
I've been looking into this for a while now and I can't seem to see what I'm doing wrong.
The script only echos the productnames, if you posted a "rid".
Also you could write the if like this:
if (isset($_SESSION['ridArray'], $_POST['rid']) && is_array($_SESSION['ridArray'])) {
Checking isset() first. Also you could additionally check for
... && count($_SESSION['ridArray'] > 0)
I do not think that your session starts automatically (is it possible to set its autostart in php.ini, but it does not by default), so
<?php
session_start();
Other thoughts:
SELECT * FROM example WHERE id = $x
Have you ever heard about SQL Injection?
ps: no need in secondary check (they are checked before) and from the first condition follows the second one
is_array($_SESSION['ridArray']) && isset($_SESSION['ridArray'])
I would write it as
<?php
session_start();
if (isset($_POST['rid'])) {
addBookmark(intval($_POST['rid']));
}
function addBookmark($rid) {
$_SESSION['ridArray'][] = $rid;
$_SESSION['ridArray'] = array_unique($_SESSION['ridArray']);
foreach($_SESSION['ridArray'] as $x) {
$result = mysql_query("SELECT * FROM example WHERE id = '$x'")
or die(mysql_error());
$row = mysql_fetch_array( $result );
echo $row['productname'];
}
}
?>

Categories