if statement in mysql query codeigniter - mysql

I have to execute a query checking if a variable is empty or not. like:
if($symbol == ""){
$data_array = $this->db->select('*')
->select_max('date')
->get('company')
->row_array();
}else{
$data_array = $this->db->select('*')
->select_max('date')
->where('symbol',$symbol)
->get('company')
->row_array();
}
How can I make it in a single query?

I think you can do it like this:
if($symbol == ""){
$where = "symbol != 0"; ##$where = "symbol != ''"; whichever suits your case
}else{
$where = "symbol = '".$symbol."'";
}
$data_array = $this->db->select('*')
->select_max('date')
->where($where, false, false)
->get('company')
->row_array();

Related

Using the LIKE operator in MYSQL voids the "id > ? operation"

I am using the like operator to select where like %x% and using the id > ? at the same time but it doesn't work for whatever reason where I keep pulling in the same row of information.
My code is concise and works well I think but the like operator is making it so I keep pulling in the same data (I used = and it worked). Any help please, thank you.
var query = 'SELECT * FROM products WHERE 1 = 1';
var arr = [];
if(typeof(req.body.category) == 'string' && req.body.category.trim() !== '') {
// query += ' AND category LIKE ? OR title LIKE ?'; //doesnt work keep pulling in same data
// arr.push('%' + req.body.category + '%', '%' + req.body.category + '%'); //doesnt work keep pulling in same data
// query += ' AND category = ? OR title = ?'; //works
// arr.push(req.body.category, req.body.category); //works
}
if(typeof(req.body.reset_index) == 'boolean' && req.body.reset_index == true) {
req.session.last_id_main_products = 0;
}
query += ' AND id > ?';
arr.push(req.session.last_id_main_products);
if(
typeof(req.body.longitude) == 'number' &&
typeof(req.body.latitude) == 'number' &&
typeof(req.body.if_location) == 'boolean' && req.body.if_location == true
) {
var left_long = req.body.longitude - 0.3;
var right_long = req.body.longitude + 0.3;
var upper_lat = req.body.latitude + 0.3;
var lower_lat = req.body.latitude - 0.3;
query += ' AND (room_geo_longitude > ? AND room_geo_longitude < ?) AND (room_geo_latitude > ? AND room_geo_latitude < ?)';
arr.push(left_long, right_long, lower_lat, upper_lat);
}
query += ' AND hidden = false LIMIT 1';
pool.query(query, arr, (err, result) => {
if(err) {
res.json(err);
return;
}
if(result.length > 0) {
req.session.last_id_main_products = result[result.length - 1].id;
}
res.json({
room_products: result,
query: query,
arr: arr
});
});
UPDATE: When using query, use parentheses around specific types of operations or else will return bad data.

adding a condition to a WHERE clause based on a passed variable value mysql

I am a relative novice and could use some help with this problem.
This will be used in a search filter situation.
Users need to search by a value and 1 or more other values passed by the search form.
$name = $_POST['name'];
$sdate = $_POST['sdate'];
$startdate = $_POST['startdate'];
$enddate = $_POST['enddate'];
$vehicle = $_POST['vehicle'];
$triptype = $_POST['triptype'];
If any of these values are '' I do not want them in the query, If they contain a value I do want them in the query.
SELECT * FROM form_data WHERE `resp_person` = '$name',
IF $sdate != '' then `sdate` = '$sdate',
IF $startdate != '' then `sdate` = *all values between $startdate and $enddate*,
IF $triptype != '' then `triptype` = '$vehicle',
IF $vehicle != '' then `vehicle` = '$vehicle', `sdate`
ORDER BY `sdate` DESC, `stime` DESC")
I know the code is wrong but it should give you a good idea of what I am trying to accomplish. Any guidance would be greatly appreciated.
A better way is to not use string concatenation to build the entire query, but rather use an sql library that supports prepared statements, such as PDO.
$pdo = new PDO('... connection string ...', username, password);
$where = '';
$possible_values = array('name', 'sdate', 'startdate', 'enddate', 'vehicle', 'triptype' );
$params = array();
foreach($possible_values as $val)
{
if(isset($_POST[$val]))
{
$params[] = $_POST[$val];
if($where == '')
{
$where = "WHERE $val = ?";
}
else
{
$where .= " AND $val = ?";
}
}
}
$stmt = $pdo->prepare("SELECT * FROM form_data " . $where);
$stmt->execute($params);
In cases like this, I prefer to build the query in pieces...
$wheres = array(); // Collect things to AND together
if ($searchterm != 'All') $wheres[] = "subject LIKE '%searchterm'";
if (...) $wheres[] = "...'";
...
if (count($wheres) > 0)
$where_str = "WHERE " . implode(' AND ', $wheres);
else
$where_str = '';
$order_str = (...) ? "ORDER BY ..." : '';
$limit_str = $limit ? "LIMIT $limit" : '';
$query = "SELECT ... FROM foo $where_str $order_str $limit_str";
Oh, and don't forget to use escape the strings on any data coming in from a form -- else a user can do nasty things to the SQL statement!

mysql_num_rows doesn't work (will not return 0)

I have created a condition in which if a query returns a result, it would execute a code and would return 1 or more. However if the query is empty, we would get 0 and the if statement would not activate.
However I have been getting 1 and the if statement activates despite the fact that no rows are returning (tested it out in a phpmyadmin SQL executor.
One hint is that it says that 'Your SQL query has been executed successfully' while no rows return instead if saying 'MySQL returned an empty result set'.
What is happening and how do I fix this?
$search_num_rows_2 = mysql_query("SELECT * FROM (SELECT tags_movie.name_movie, tags_game.name_game, tags_sport.name_sport, tags_music.name_music, tags_show.name_show FROM tags_game, tags_movie, tags_sport, tags_music, tags_show WHERE tags_game.relation = '$user_id' && tags_movie.relation = '$user_id' && tags_sport.relation = '$user_id' && tags_music.relation = '$user_id' && tags_show.relation = '$user_id') somealias WHERE name_movie LIKE '{$movie}%' && name_game LIKE '{$name_game}%' &&name_sport LIKE '{$sport}%' &&name_music LIKE '{$music}%' && name_show LIKE '{$show}%'");
$number = mysql_num_rows($search_num_rows_2);
echo $number;
if ($number != 0){
}
As I understood, you didn't implement to catch empty result in your if block and it should be like,
if ($number != 0){
echo $number;
} else {
echo 'Empty result';
}
EDIT 1
$res = mysql_query("SELECT * FROM (SELECT tags_movie.name_movie, tags_game.name_game, tags_sport.name_sport, tags_music.name_music, tags_show.name_show FROM tags_game, tags_movie, tags_sport, tags_music, tags_show WHERE tags_game.relation = '$user_id' && tags_movie.relation = '$user_id' && tags_sport.relation = '$user_id' && tags_music.relation = '$user_id' && tags_show.relation = '$user_id') somealias WHERE name_movie LIKE '{$movie}%' && name_game LIKE '{$name_game}%' &&name_sport LIKE '{$sport}%' &&name_music LIKE '{$music}%' && name_show LIKE '{$show}%'");
$data = mysql_fetch_array($res);
if (count($data) > 0){
print_r($data);
} else {
echo 'Empty result';
}

query with parentheses in zend framework 2.2

I want my query like this:
SELECT tbl_bids. * , tbl_department.vDeptName, tbl_user.vFirst
FROM tbl_bids
LEFT JOIN tbl_bids_department ON tbl_bids_department.iBidID = tbl_bids.iBidID
LEFT JOIN tbl_department ON tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID
LEFT JOIN tbl_user ON tbl_user.iUserID = tbl_bids.iUserID
WHERE tbl_user.iUserID = '1' // with parantheses in where clause
AND (
tbl_department.vDeptName = 'PHP'
OR tbl_department.vDeptName = 'android'
)
GROUP BY tbl_bids.iBidID
ORDER BY iBidID DESC
LIMIT 0 , 30
But i can't find the way to get parantheses in my query,there are mutiple condition and loop will be there to make where clause..
here is my code
$select = $this->tableGateway->getSql()->select();
$select->columns(array('*'))
->join('tbl_bids_department', 'tbl_bids_department.iBidID = tbl_bids.iBidID', array(),"LEFT")
->join('tbl_department', 'tbl_department.iDepartmentID = tbl_bids_department.iDepartmentID',array(tbl_department.vDeptName),"LEFT")
->join('tbl_user', 'tbl_user.iUserID = tbl_bids.iUserID',array(tbl_user),"LEFT")
->group('tbl_bids.iBidID');
$where = new \Zend\Db\Sql\Where();
$where->equalTo( 'tbl_bids.eDeleted', '0' );
$sWhere = new \Zend\Db\Sql\Where();
for ( $i=0 ; $i<count($aColumns) ; $i++ )
{
if (isset($data['sSearch_'.$i]) && $data['sSearch_'.$i] != "")
{
if($aColumns[$i] == 'vDeptName'){
$allDept = explode(',', $data['sSearch_'.$i]);
foreach ($allDept as $key => $value) {
if($key == 0)
$sWhere->AND->equalTo("tbl_department.vDeptName", $value);
else
$sWhere->OR->equalTo("tbl_department.vDeptName", $value);
}
}elseif($aColumns[$i] == 'vFirst')
$sWhere->AND->equalTo("tbl_user.iUserID",$data['sSearch_'.$i]);
else
$sWhere->AND->like("tbl_bids.".$aColumns[$i], "%" . $data['sSearch_'.$i] . "%");
$select->where($sWhere); // here my where clause is create
}
}
//var_dump($select->getSqlString());
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
I have others many fields to pass through where which also have same problem of paratheses
if there is no any condition i can use nest() and unnest() predicate , but it will show me that string is not nested error,
So pls help me to find the solution.
Pls attach example with solution.
here is a short example
$where = new Sql\Where();
$where->equalTo('col',thirdVal')
->NEST //start braket
->equalTo('col','someVal')
->OR
->equalTo('col','secondVal')
->UNNEST //close bracet
hope this will help

MySQL IF Condition in Where Clause

Is it possible to decide by IF Condition which Where Clause I want to choose.
Something like:
IF(DATE_FORMAT(DATE(akDate), '%a')='SAT', USE WHERECLAUSE1, USE WHERECLAUSE2)
This is the case you can still write using rather common WHERE statement such as this:
... WHERE
(
(DATE_FORMAT(DATE(akDate), '%a') = 'SAT')
AND
(WHERECLAUSE1)
)
OR
(
(DATE_FORMAT(DATE(akDate), '%a') != 'SAT')
AND
(WHERECLAUSE2)
)
where, of course, you should replace WHERECLAUSE1 and WHERECLAUSE2 with appropriate conditions.
Easy, you should read on Boolean Algebra. In your case, here we go:
A = WhereClause1
B = WhereClause2
X = Choice
You need to select lines with X && A OR lines with !X && B. So basically your expression will be: (X && A) || (!X && B). Which leads to:
(
(Choice AND WhereClause1)
OR
((NOT Choice) AND WhereClause2)
)
$query = " SELECT apt.apt_id,apt.reg_id,apt.u_id,apt.b_id,apt.apt_bathroom,apt.apt_size,apt.apt_rent,apt.apt_desc,apt.negotiable,apt.apt_status,apt.govt_program,building.b_borough,building.b_zipcode,building.b_type,building.b_intersection,building.b_intersection2,building.b_desc FROM apt LEFT JOIN building ON apt.b_id = building.b_id WHERE apt.apt_status = 1 AND ";
if ($search_size != 'empty')
{
$query .= "apt.apt_size = '".$search_size."' ";
if ($search_borough != 'empty' || $search_zipcode != 'empty' )
{
$query .= " AND ";
}
}
if ($search_borough != 'empty')
{
$query .= "building.b_borough= '".$search_borough."' ";
if ($search_zipcode != 'empty')
{
$query .= " AND ";
}
}
if ($search_zipcode != 'empty')
{
$query .= "building.b_zipcode = '".$search_zipcode."' ";
}
$query .= "ORDER BY apt.apt_id DESC LIMIT $start,$perpage ";
$query_run = mysql_query ($query);
if (!$query_run)
{
echo 'Error In the Query limit.';
}