I simply want to check, if a query give me 'NULL' as the result.
$check = ' SELECT some_data FROM user
WHERE condition = my_condition LIMIT 1';
if ( is_null($check) )
{
echo "yep, it's null";
}
But i don't get the echo. The query definitly gives me the result 'NULL'. Whats wrong?
Just execute the query and fetch a row of results.
Related
my table
This is my table i have to display the data using multiple where conditions. First i select using dms_expire_date,for this i got answer and i am using dms_doc_name in where conditions but i didn't got correct result.
I have tired so far.
]
See this picture if i use "or" in "where" i got testie not within this date.but if i use "and" in "where" i didn't got result for dms_expiry_date
See this picture
i don't know how to do this.please help to solve this problem.
SELECT * FROM `dms_document` WHERE dms_expire_date BETWEEN '2020-05-01' AND '2020-07-16' AND dms_doc_name = '' OR dms_category_id = '' OR dms_subcategory_id=''
I have tired in array also but i didn't result.
$this->db->select('*');
$this->db->join('dms_category as C', 'C.dms_category_id = D.dms_category_id', 'left outer');
$this->db->join('dms_sub_category as S', 'S.dms_subcategory_id = D.dms_subcategory_id', 'left outer');
$this->db->where('dms_expire_date >=', $newstart);
$this->db->where('dms_expire_date <=', $newend);
$this->db->where(array('dms_doc_name' =>$docname,'D.dms_category_id'=>$category,'D.dms_subcategory_id'=>$subcategory));
$data['documents']= $this->db->get('dms_document as D')->result_array();
try
SELECT *
FROM dms_document
WHERE dms_expire_date BETWEEN $newstart AND $newend
AND CASE WHEN $docname IS NULL THEN 1 = 1 ELSE dms_doc_name = $docname END
AND CASE WHEN $category IS NULL THEN 1 = 1 ELSE dms_category_id = $category END
AND CASE WHEN $subcategory IS NULL THEN 1 = 1 ELSE dms_subcategory_id = $subcategory END
--
edited. waiting for clearance.
if I get what you mean correctly, it is problem with understanding AND, OR, and the priority with brackets ()
--
if anyone want to use the fiddle, I have created the sample data for this issue
You can write OR using CodeIgniter's or_where() (v3 docs) or orWhere() (v4 docs).
//your initial query
$sql = "SELECT
*
FROM
`dms_document`
WHERE
dms_expire_date BETWEEN '2020-05-01' AND '2020-07-16'
AND dms_doc_name = ''
OR dms_category_id = ''
OR dms_subcategory_id=''";
//building the same query using CI
$this->db->select('*');
$this->db->from('dms_document');
$this->db->where('dms_expire_date >=', '2020-05-01');
$this->db->where('dms_expire_date <=', '2020-07-16');
$this->db->where('dms_doc_name', '');
$this->db->or_where('dms_category_id', '');
$this->db->or_where('dms_subcategory_id', '');
You can confirm the query this generates by running $this->db->_compile_select(); or $this->db->last_query(); (https://stackoverflow.com/a/6145021/1499877 for reference).
echo '<pre>';
var_dump($sql);
var_dump($this->db->_compile_select());
echo '</pre>';
die();
1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 4SELECT a.* FROM ws_items a WHERE 1 AND enabled=1 AND visible=1 ORDER BY created DESC LIMIT 0,
I searched the website, but none matches my query. I have no idea on how to use mysql, but I really need to solve this problem...
Maybe someone here knows the solution
if ($params["page_name"]=="index")
{
$filter = "";
if ($_SESSION['user_data']['type']!="admin")
{
$filter = " AND `enabled`=1 AND `visible`=1 ";
}
$sql = "SELECT a.* FROM
`".DB_PREFIX."items` a WHERE 1 $filter
ORDER BY `created` DESC
LIMIT ".($_SESSION['itemsPerPage']*($page-1)).",".$_SESSION['itemsPerPage'];
$items = $DB->getAll($sql);
for($i=0; $i<count($items); $i++)
{
$items[$i][third] = "";
$items[$i][thumb_rating] = rating_bar($items[$i]['id'], '5', 'static');
if($i%3==2)
$items[$i][third] = 'style="margin-right:0;"';
}
$smarty->assign("items", $items);
$sql = "SELECT COUNT(a.id) as `total` FROM
`".DB_PREFIX."items` a WHERE 1 $filter
";
$items = $DB->get($sql);
$total = $items['total'];
$smarty->assign("pagination", $DB->show_pagination($total, $page, $_SESSION['itemsPerPage']));
$output = $this->display(__FILE__, 'latestwallpapers.tpl');
}
return $output;
}
What I think is happening is that
$_SESSION['itemsPerPage']
is null and when multiplying by $page - 1 is being converted to 0 so it's evaluating to 0 in the query, but when concatenated at the end is just producing nothing which is causing the syntax error in the LIMIT clause:
DESC LIMIT 0,
If you have a safe way of creating $filter that prevents SQL injection, then try changing it to:
$sql = "SELECT a.* FROM
`".DB_PREFIX."items` a WHERE 1=1 $filter
ORDER BY `created` DESC
LIMIT ".($_SESSION['itemsPerPage']*($page-1)).",".($_SESSION['itemsPerPage']+0);
If your query ends with LIMIT 0 then it won't return any rows and if it ends LIMIT 0, then it is indeed syntactically incorrect.
You need to make sure that you have a value for the offset.
I have tweaked the query to add zero to the offset, so it should now end with LIMIT 0,0 but beware this won't return any rows. I guess your session variable doesn't have a value.
Why not try var_dump($_SESSION['itemsPerPage']); as suggested by #VMai?
EDIT: I bet you $_SESSION['itemsPerPage'] is set after the first time you reference it. Hence the first time you load the page it fails, then when you refresh, that value is there and it works.
I was told that I could check whether a SELECT statement finds a column with the syntax
$rows = query( "SELECT * FROM tbl WHERE id = idx");
if ( $rows == false )
and it seems to work.
Anyway, if I check if ( $rows == 0 ) it doesn't return the same value.
Shouldn't 0 and false be the same (apart from the type, of course)?
What's the actual value returned by the query when it finds no row? I ask because it doesn't seems to be false, since the statement var_dump( $rows === false ) prints false..
***EDIT: I'm sorry guys, query() was a function from a library someone else wrote and I had no idea (i'm starting now with sql...). It simply excutes an SQL statement, returning an array of all rows in result set or false on (non-fatal) error (like row not found).
I have still a little question, though.
The function returns false when it finds no row, so shouldn't I be able to catch that with if ( $rows === false )?
Why var_dump(false) doens't print me out anything, while var_dump(true) prints me out 1?
I'm not pretty sure if you use simple mysql_* functions, MySQLi or PDO but in any case $rows is not returning the number of resulting rows. It is a boolean value / object returned / created depending of success of your query.
$sql = $mysqli->query("SELECT * FROM tbl WHERE id='1'");
if(!$sql->error)
$number_of_rows = $sql->num_rows; // for sure it will output 1
I have this Perl code:
my $cmd = "
SELECT COUNT(id)
FROM tblUsers
WHERE UPPER(username) = UPPER(?) AND password = ?
";
db_connect();
my $sql = $dbh->prepare($cmd);
my $count = 2;
$sql->execute(
$args{login_username},
crypt($args{login_password}, $args{login_username})
) or die "SQL Error: ".$sql->errstr;
$sql->bind_columns(\$count);
$sql->fetch;
which is returning 0, but should be returning a 1
If I output the following:
$msg = "wrong username/password: $count;$args{login_username};$args{login_password};" . crypt($args{login_password}, $args{login_username});
I get:
wrong username/password: 0;skeniver;password;skh9dtk2bCasY
and the crypt part is exactly what I have in the database. Running the same values in MySQL returns a count of 1.
I really can't figure out what's going wrong here.
Does anyone else see something I'm missing?
Assuming your select returns a non 0 value and assuming that the column password in tblUsers has skh9dtk2bCasY for username=skeniver, Try
$sql->execute($args{login_username}, crypt($args{login_password},$args{login_username}))
or die "SQL Error: ".$sql->errstr;
$count = $sql->fetchrow_array();
Or, if there is a possibility that the query returns multiple rows then-
$sql->execute($args{login_username}, crypt($args{login_password},$args{login_username}))
or die "SQL Error: ".$sql->errstr;
while (($count) = $sql->fetchrow_array()){
print "Count is: $count\n";
}
I have a function which takes an argument that is used in where clause
function(string x)-->Now this will create a sql query which gives
select colname from tablename where columnname=x;
Now I want this function to give all rows i.e. query equivalent to
select colname from tablename;
when I pass x="All".
I want to create a generic query that when I pass "All" then it should return me all the rows else filter my result.
Just leave the where condition out.
If you really want it that complicated use
where columnname LIKE '%'
which will only filter nulls.
select colname from tablename
where columnname=(case when #x ="All" then columnname
else #x end)
Try this
select colname from tablename where 1=1
hope the above will work
where 1=1 worked for me, Although where clause was being used all records were selected.
You can also try
[any_column_name]=[column_name_in_LHL]
(LHL=left hand side.)
refer my answer for more details
I had the same issue some time ago and this solution worked for me
select colname from tablename where columnname=x or x = 'ALL'
SELECT * FROM table_name WHERE 1;
SELECT * FROM table_name WHERE 2;
SELECT * FROM table_name WHERE 1 = 1;
SELECT * FROM table_name WHERE true;
Any of the above query will return all records from table.
In Node.js where I had to pass conditions as parameter I used it like this.
const queryoptions = req.query.id!=null?{id : req.query.id } : true;
let query = 'SELECT * FROM table_name WHERE ?';
db.query(query,queryoptions,(err,result)=>{
res.send(result);
}
It's unclear what language you're using for your function, but you have to somehow parse the 'All' prior to getting to sql:
public void query(String param) {
String value = "":
switch (param) {
case 'All':
value = "*";
break;
default:
value = param;
}
String sql = "select colname from tablename where colname="+value;
//make the query
}
If you have to allow 'ALL' to be passed through as the parameter value to your function, then you will need to put some manipulation code in your function to construct your SELECT statement accordingly. I.e. You can detect if the parameter has 'ALL' in it and then omit the WHERE clause from your SQL statement. If a value other than 'ALL' comes through, then you can include the WHERE clause along with the relevant filter value from the parameter.
An example of a piece of code to do this would be;
IF x = 'ALL'
THEN
SELECT COLNAME FROM TABLENAME;
ELSE
SELECT COLNAME FROM TABLENAME WHERE COLUMNNAME = X;
END IF;
Give a conditional check in your code(assuming Java) to append the WHERE clause only when x != 'All'
mySqlQuery = "SELECT colname FROM tablename" +
(x.equals("All") ? "" : "WHERE columnname = "+x);