if argument inside mysql query - php

I have now three different PHP pages that contain almost the same information so to be able to reduce this to one page I need to have a php variable inside the mysql query.
Today it is like this:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";`
I need that the " AND Bruk = '1'" is removed from this query-line if i put ?nobruk=no in the adressbar. Is this possible and if so, how?

You don't want to (and can't) put an if inside your query; you want to use an if to create your query based on some condition. There are lots of ways to write this, one of which is
if (!empty($_GET['nobruk'])) {
$query1 = "SELECT ... WHERE `Kategori` = '1' ORDER BY ...";
}
else {
$query1 = "SELECT ... WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY ...";
}
Another way, which is shorter and involves the ternary operator, is
$includeBruk = empty($_GET['nobruk']);
$query1 = "SELECT ... WHERE `Kategori` = '1' ".
($includeBruk ? "AND `Bruk` = '1' " : "").
"ORDER BY ...";

A simple if statement:
$query1 = "SELECT * FROM `Yrker` WHERE `Kategori` = '1'";
if ($_GET['nobruk']!='no') {
$query1.=" AND `Bruk` = '1'";
}
$query1.= " ORDER BY yearstart DESC, mndstart DESC";

Like this :
<?php
$query = ($_REQUEST['nobruk'] == "no") ? "SELECT * FROM `Yrker` WHERE `Kategori` = '1' ORDER BY yearstart DESC, mndstart DESC": "SELECT * FROM `Yrker` WHERE `Kategori` = '1' AND `Bruk` = '1' ORDER BY yearstart DESC, mndstart DESC";
echo $query;
?>

$query1 = "SELECT * FROM `Yrker` WHERE `Kategori`='1' ".($_GET['nobruk'] === 'no' ? "" : "AND `Bruk`='1' ")."ORDER BY yearstart DESC, mndstart DESC";

Related

How can i order by id ascending?

I want to order data by Id, how can i do this ?
if($_GET["grupid"]>0){
$DUZEN = array();
$sql = "SELECT * FROM siparis_ana WHERE grupid =".$_GET["grupid"];
$rsDuzen = mysql_query($sql, $conn) or die(mysql_error());
while ($r = mysql_fetch_assoc($rsDuzen)) {
$DUZEN[] = $r;
}
}
i can read all data with this code which have same group id. But data aline random.
You have to use mysql order clause in your query like order by id asc. Which you can use at the end of your query.
$sql = "SELECT * FROM siparis_ana WHERE grupid =".$_GET["grupid"]." order by id asc";
Your sql query should be like given below...
$sql = "SELECT * FROM siparis_ana where grupid = " . $_GET['grupid'] . " ORDER BY id asc ";

Double WHERE NOT statement sql

I have this query:
$query = "SELECT pic_square,
name,
highest_score,
num_tries,
avg_total
FROM users
WHERE NOT played_game = '0'
ORDER BY avg_total DESC";
Where I select pic_square,name,highest_score,num_tries and avg_total FROM for all users that
DO NOT have their played game set as ''0''.
I would like to add another condition so I select only the users that:
DO NOT have their played_game set as ''0''
DO NOT have their name empty
PS: The name cannot be null, it just can be empty, I cannot change the DB structure itself.
So how do I add these dual WHERE NOT together?
WHERE NOT (played_game = '0' or name = '')
or
WHERE played_game <> '0' and name <> ''
$query = "SELECT pic_square,name,highest_score,num_tries,avg_total FROM users
WHERE NOT (played_game = '0' OR name IS NULL OR name='' )
ORDER BY avg_total DESC";
$query = "SELECT pic_square,name,highest_score,num_tries,avg_total FROM users
WHERE played_game <> '0' AND name <> '' ORDER BY avg_total DESC";
simply change condition like
where played_game <> '0' AND name <> ''
$query = "SELECT pic_square,name,highest_score,num_tries,avg_total
FROM users
WHERE played_game != '0'
AND name NOT NULL
ORDER BY avg_total DESC";
You can use this query:
$query = "SELECT pic_square,
name,
highest_score,
num_tries,
avg_total
FROM users
WHERE NOT played_game = '0'
AND IFNULL(name,'') <> ''
ORDER BY avg_total DESC";
Using IFNULL you'll get sure that NULL values and empty values are treated just the same.

PHP Optimized query call if nothing is selected

I am trying to make my coding more efficient and I am stuck at how to tell the query to display all the categories if nothing is selected.
I have 15 categories that the user can chose from, if none is selected, display all items. Rather than doing AND .. AND .. AND 15 times if nothing is selected, is there a smarter way for this?
This will work for one category selection:
$cate = mysql_query("SELECT * FROM `posts` ORDER BY `id` ASC");
while($row = mysql_fetch_assoc($cate)){
if($user_data['category'] === $row['id']) {
echo '<li>'.$row['name'].'</li>';
}
}
$category_list = "AND `category_id` = '".$user_data['category']."'";
You should generate your query dynamically
// General query
$query = "SELECT * FROM `posts`";
// If category selected
if ($user_data['category'] != 0) {
$query .= " WHERE `category_id` = '".$user_data['category']."'";
}
// Order
$query .= " ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);
Or it can be simplified using Ternary Operator:
// Generate query
$query = "SELECT * FROM `posts` ".($user_data['category'] != 0 ? "WHERE `category_id` = '".$user_data['category']."'" : "" )." ORDER BY `id` ASC";
// Run query
$cate = mysql_query($query);

String to Query for All Records in Table

When I pull each leadstatus individually (?leadstatus=New, ?leadstatus=Hot, etc.) they work, but when trying to get All, I can't seem to get it to work. The default on the page is New leads as you can see.
`$query = "SELECT * FROM contacts WHERE contacttype IN ('New','Buyer','Seller','Buyer / Seller','Investor') AND leadstatus = 'New' ORDER BY date DESC";
if(isset($_GET['leadstatus']) && in_array($_GET['leadstatus'], array('New', 'Hot', 'Warm', 'Cold', 'Rejected', 'Closed')))
{
$status = $_GET['leadstatus'];
$query = "SELECT * FROM contacts WHERE leadstatus = '".$status."' ORDER BY contacts.date DESC";
}`
Here are some of the strings I've tried with no luck:
?leadstatus=New&leadstatus=Hot&leadstatus=Warm&leadstatus=Rejected&leadstatus=Cold - Only pulls last listed, which is Cold
?leadstatus[]=New&leadstatus=[]Hot&leadstatus[]=Warm&leadstatus[]=Rejected&leadstatus[]=Cold - Returns default, which is New
?leadstatus=New&Hot&Warm&Rejected&Cold
Returns default, which is New
if(isset($_GET['leadstatus']) && $_GET['leadstatus'] == "all") {
$query = "SELECT * FROM contacts ORDER BY contacts.date DESC";
} else if (in_array($_GET['leadstatus'], array('New', 'Hot', 'Warm', 'Cold', 'Rejected', 'Closed'))) {
$status = $_GET['leadstatus'];
$query = "SELECT * FROM contacts WHERE leadstatus = '".$status."' ORDER BY contacts.date DESC";
}
Then, make leadstatus = all.
Try this:
if(isset($_GET['leadstatus']) && in_array($_GET['leadstatus'], array('New', 'Hot', 'Warm', 'Cold', 'Rejected', 'Closed')))
{
$status = $_GET['leadstatus'];
if(!empty($status)) {
$query = "SELECT * FROM contacts WHERE leadstatus = '".$status."' ORDER BY contacts.date DESC";
} else {
$query = "SELECT * FROM contacts ORDER BY contacts.date DESC";
}
}`
However, may I also suggest that you use a parameterized query? You are wide open to a SQL Injection attack here.
Something like this should match multiple conditions, allowing you to mix-and match several at a time, rather than 1 or all.
$status = join(',',$_GET['leadstatus']);
$query = "SELECT * FROM contacts WHERE leadstatus IN($status) ORDER BY contacts.date DESC";

MySQL: Combining two repetitive queries to make WHERE clause dynamic

How can I combine these two queries into one so I don't have to repeat the same lines again and again?
if(empty($cat_id))
{
$sql = "
SELECT *
FROM root_category_contacts
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);
}
else
{
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql,array($cat_id));
}
I don't need WHERE clause when I don't have the cat_id.
Is it feasible?
Test if ? is null or equals cat_id. Something like this:
Edit based on xdazz's comment. And assuming that cat_id > 0
$sql = "
SELECT *
FROM root_category_contacts
WHERE root_category_contacts.cat_id != ?
ORDER by cat_order ASC"
if(empty($cat_id)) {
$cat_id = 0;
}
$items_category = $connection->fetch_all($sql,array($cat_id));
if(empty($cat_id)) $where = "";
else $where = "WHERE root_category_contacts.cat_id != '$cat_id'"
$sql = "
SELECT *
FROM root_category_contacts
$where
ORDER by cat_order ASC
";
$items_category = $connection->fetch_all($sql);

Categories