MYSQL - Don't add to query if string is empty - mysql

I have a query that selects based on multiple things. For example, game_name is a string that can be empty if the user so chooses. Is there any way to not do the searching part for game_name if the input is "" but still look for the others?
$stmt = $connection->prepare("SELECT * FROM $config->tablename WHERE id = ? OR game_name = ? OR gamer_tag = ? LIMIT ?");
$stmt->bind_param("ssss", $request->id, $request->game_name, $request->gamer_tag, $request->limit);

You should do a little workaround to control it and when the user wants the field to be empty, you should control that and add to query something like this:
convert this
game_name = ?
into this
game_name = ? OR game_name = game_name
So this will make always to be true for that field.
EDIT:
Combining #Amado's solution and my proposal resolves in less IF statements (only my POV).
$MyWhere = "id = ? OR gamer_tag = ? OR game_name = ?"
if(game_name !="") $MyWhere = $MyWhere." OR game_name = game_name";
$stmt = $connection->prepare("SELECT * FROM $config->tablename WHERE ".$MyWhere." LIMIT ?");
$stmt->bind_param("ssss", $request->id, $request->gamer_tag, $request->game_name, $request->limit);

You can add a little checking before performing the query:
$MyWhere = "id = ? OR gamer_tag = ?"
if(game_name !="") $MyWhere = $MyWhere." Or game_name = ?";
$stmt = $connection->prepare("SELECT * FROM $config->tablename WHERE ".$MyWhere." LIMIT ?");
if(game_name !=""){
$stmt->bind_param("ssss", $request->id, $request->game_name, $request->gamer_tag, $request->limit);
}
else{
$stmt->bind_param("sss",$request->id,$request->gamer_tag, $request->limit);
}

Related

How to convert this query to doctrine DQL

SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid='20'
and not exists (
select 1
from `distribution_mobiletokens`
where userid = '20'
and deviceid = dm.deviceid
and created > dm.created
)
What this query does is selects all mobiletokens where the user id is equal to 20 and the deviceid is the same but chooses the newest apntoken for the device.
My database looks like below.
For more information on this query, I got this answer from another question I asked here(How to group by in SQL by largest date (Order By a Group By))
Things I've Tried
$mobiletokens = $em->createQueryBuilder()
->select('u.id,company.id as companyid,user.id as userid,u.apntoken')
->from('AppBundle:MobileTokens', 'u')
->leftJoin('u.companyId', 'company')
->leftJoin('u.userId', 'user')
->where('u.status = 1 and user.id = :userid')
->setParameter('userid',(int)$jsondata['userid'])
->groupby('u.apntoken')
->getQuery()
->getResult();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}
die();
This gives me the incorrect response of
63416A61F2FD47CC7B579CAEACB002CB00FACC3786A8991F329BB41B1208C4BA
9B25BBCC3F3D2232934D86A7BC72967A5546B250281FB750FFE645C8EB105AF6
latestone
Any help here is appreciated!
Other Information
Data with SELECT * FROM
Data after using the SQL I provided up top.
You could use a subselect created with the querybuilder as example:
public function selectNewAppToken($userId)
{
// get an ExpressionBuilder instance, so that you
$expr = $this->_em->getExpressionBuilder();
// create a subquery in order to take all address records for a specified user id
$sub = $this->_em->createQueryBuilder()
->select('a')
->from('AppBundle:MobileTokens', 'a')
->where('a.user = dm.id')
->andWhere('a.deviceid = dm.deviceid')
->andWhere($expr->gte('a.created','dm.created'));
$qb = $this->_em->createQueryBuilder()
->select('dm')
->from('AppBundle:MobileTokens', 'dm')
->where($expr->not($expr->exists($sub->getDQL())))
->andWhere('dm.user = :user_id')
->setParameter('user_id', $userId);
return $qb->getQuery()->getResult();
}
I did this for now as a temporary fix, not sure if this is best answer though.
$em = $this->em;
$connection = $em->getConnection();
$statement = $connection->prepare("
SELECT apntoken,deviceid,created
FROM `distribution_mobiletokens` as dm
WHERE userid=:userid
and not exists (
select 1
from `distribution_mobiletokens`
where userid = :userid
and deviceid = dm.deviceid
and created > dm.created
)");
$statement->bindValue('userid', $jsondata['userid']);
$statement->execute();
$mobiletokens = $statement->fetchAll();
//#JA - Get the list of all the apn tokens we need to send the message to.
foreach($mobiletokens as $tokenobject){
$deviceTokens[] = $tokenobject["apntoken"];
echo $tokenobject["apntoken"]."\n";
}

Is there a variable for mysql that returns all?

I have a MySQL query using a WHERE clause based on a variable. I am trying to figure out if there is a way to set the variable to something like a wildcard that would return any value in that field?
WHERE c.call_state_id = $state
AND (follow_emp_id = $user_id OR follow_emp_id = 117)
ORDER BY $sort
Instead of limiting the results to 1 specific $user_id, I want to virtually eliminate the AND portion of the query.
I would build the query dynamically, and check for the value before putting it into the WHERE clause.
if (empty($userid)) {
$userid_check = ""
} else {
$userid_check = "AND (follow_emp_id = $user_id OR follow_emp_id = 117)"
}
$sql = "SELECT ...
WHERE c.call_state_id = $state
$userid_check
ORDER BY $sort";
See https://stackoverflow.com/a/28909923/1491895 for a more general approach to building queries dynamically.
If you know a value that will not be used, such as 0 (or -1); you can just check for that:
WHERE c.call_state_id = $state
AND ($user_id = 0 OR follow_emp_id = $user_id OR follow_emp_id = 117)
ORDER BY $sort

mySql statement

I have a sql statement where I want to get all the entry with the category of "Game" but do not want to retrieve the record with the code of "A00001".
Below is my sql code but there is an error in the where clause.
$sql1 = "SELECT * FROM productItem WHERE productName = '$name' AND skuCode != '$mySKU';";
$mySKU = 'A00001';
$sql1 = "SELECT * FROM productItem WHERE productName = '$name' AND skuCode != '$mySKU'";
You have an extra ; lurking somewhere in there. Be sure to sanitize $mySKU if it is user input and use prepared statements.
update: Using PDO:
$stmt = $dbh->prepare("SELECT * FROM productItem WHERE productName = :name AND skuCode != :mySKU");
if ($stmt->execute(array('name' => $name, "mySKU" => $mySKU))) {
$rows = $stmt->fetchAll(); //if you are sure there are records
Try this:
"SELECT * FROM productItem WHERE productName = '$name' AND skuCode <> '$mySKU';";
Not equal statement is <>
http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#operator_not-equal

Codeigniter query

My Query :
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where("`pos_item_sales`.`transaction_id` = '$transaction_id' AND (`pos_item_sales`.`item_barcode` = '$term' OR `pos_batch_infos`.`item_mbarcode` = '$term' OR `pos_item_infos`.`item_id` = '$term')");
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();
its solve my prob but i need like this query :
$term = $this->input->get('term',TRUE);
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where('pos_item_sales.transaction_id',$transaction_id);
$this->db->where('pos_item_sales.item_barcode',$term);
$this->db->or_where('pos_batch_infos.item_mbarcode',$term);
$this->db->or_where('pos_item_infos.item_id',$term);
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();
But I need a Query like :
SELECT *
FROM (`pos_item_infos`)
JOIN `pos_item_sales` ON `pos_item_sales`.`item_id` = `pos_item_infos`.`item_id`
JOIN `pos_batch_infos` ON `pos_batch_infos`.`item_id` = `pos_item_infos`.`item_id`
WHERE `pos_item_sales`.`transaction_id` = '11355822927'
AND (`pos_item_sales`.`item_barcode` = '8801962686156'
OR `pos_batch_infos`.`item_mbarcode` = '8801962686156'
OR `pos_item_infos`.`item_id` = '8801962686156')
how i solve this prob pls help because its not include ( ) in my or condition.
if you go through the codeigniter userguide.. you can see that there are 4 ways to call where clause...
All of these does the same things... and your first code is codeigniter style (if incase you are worried that is not) that is the 4th method by codeigniter userguide where you can write your own clauses manually... there is no difference in calling the where function in anyways...
so i would go with your first query
$this->db->select('*');
$this->db->join('pos_item_sales', 'pos_item_sales.item_id = pos_item_infos.item_id');
$this->db->join('pos_batch_infos', 'pos_batch_infos.item_id = pos_item_infos.item_id');
$this->db->where("`pos_item_sales`.`transaction_id` = '$transaction_id' AND (`pos_item_sales`.`item_barcode` = '$term' OR `pos_batch_infos`.`item_mbarcode` = '$term' OR `pos_item_infos`.`item_id` = '$term')");
$query = $this->db->get('pos_item_infos');
echo $this->db->last_query();
which is perfectly fine...
In cases of complex queries i find it easier to just send raw query like this :
$query = "your query";
$result = $this->db->query($query);
Don't forget to escape variables before inserting them to the query like this :
$var = $this->db->escape($var);
$query="SELECT *
FROM pos_item_infos
JOIN pos_item_sales ON pos_item_sales.item_id = pos_item_infos.item_id
JOIN pos_batch_infos ON pos_batch_infos.item_id = pos_item_infos.item_id
WHERE pos_item_sales.transaction_id = ?
AND (pos_item_sales.item_barcode = ?
OR pos_batch_infos.item_mbarcode = ?
OR pos_item_infos.item_id = ?)";
$params=array();
$params[]='11355822927';
$params[]='8801962686156';
$params[]='8801962686156';
$params[]='8801962686156';
$result=$this->db->query($query,$params);
$result=$result->result_array();
print_r($result);
Also, simplify your syntax with USING.
SELECT *
FROM pos_item_infos
JOIN pos_item_sales USING (item_id)
JOIN pos_batch_infos USING (item_id)
WHERE pos_item_sales.transaction_id = ?
AND (pos_item_sales.item_barcode = ?
OR pos_batch_infos.item_mbarcode = ?
OR pos_item_infos.item_id = ?)

Mysql query always returns empty value

This is my code:
$pass = mysql_query("SELECT `password` FROM acc WHERE account_id = '122' LIMIT 1;");
$p = mysql_fetch_object($pass);
$passwd = ( ( $p->password != "" ) ? $p->password : "empty" );
Then I'm doing echo $passwd; and it's always is retuning the "empty" string.
Of course the row with account_id 122 exists.
What is wrong with that?
Try this code:
$query = mysql_query("SELECT * FROM `acc` WHERE `account_id`='122'") or die(mysql_error());
while($data=mysql_fetch_object($query)){
$pass = $data->password;
}
echo $pass
You should now be able to acces all fields from that row including the password field.
what if you change
$passwd = ( ( $p->password != "" ) ? $p->password : "empty" );
to
$passwd = (empty($p->password)) ? $p->password : "empty" );
You don't need the semi-colon at the end of your query. Why do you have a limit 1? acc should be unique on account_id as having multiple passwords for the same account should be impossible.
$pass = mysql_query("SELECT `password` FROM acc WHERE account_id = '122'");
As #shawn pointed out if your account_id is indeed a number it's better not to rely on the implicit character to number conversion. Though it doesn't actually matter it's not good practice.