PHP Optimized query call if nothing is selected - php

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);

Related

Search multiple values if present

sorry my English is weak ....
how can i search multi values from db SQL So that there was any.
i can search name && family together but
I want when the user searched name And family leave empty Return result correctly
how can i write this
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE name='{$_POST['searchname']}' && family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Your 3 main issues here..
the first being WHERE name= now.. name is already used by mysql therefore you shouldn't use it however.. If you do use it run it like this:
WHERE `name`=
You should always backtick database tables and columns to make life easier in the long haul.
The second issue being you used && where it should be AND
the third is you shouldn't be placing your variables straight into your query as you're left open for SQL Injection.
Now I'm running on the assumption you're using $mysqli as your variable however, this may need adjusting to suit the correct variable you are using:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$searchName = $_POST['searchname'];
$family = $_POST['searchfamily'];
$sql = $mysqli->prepare("select * from `myinfo` WHERE `name` = ? OR `family`= ? ORDER BY `id` DESC");
$sql->execute([$searchName, $family]);
} else {
$sql = $mysqli->prepare("select * from `myinfo` ORDER BY `id` DESC");
$sql->execute();
}
If you want to search with both then you need to change your if also. And change && to and in your query
if (isset($_POST['searchname']) && isset($_POST['searchfamily'])) {
$sql = "select * from myinfo WHERE `name`='{$_POST['searchname']}' AND family='{$_POST['searchfamily']}' ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}
Edit
As per your comment try this:
if (isset($_POST['searchname']) || isset($_POST['searchfamily'])) {
$where="";
if(isset($_POST['searchname']))
$where=" WHERE `name`='{$_POST['searchname']}'";
if(isset($_POST['searchfamily']))
{
if($where=="")
$where=" WHERE family='{$_POST['searchfamily']}'";
else
$where=" AND family='{$_POST['searchfamily']}'";
}
$sql = "select * from myinfo $where ORDER BY id DESC";
}
else {
$sql = "select * from myinfo ORDER BY id DESC";
}

ORDER BY is not working with mysql multiple queries

I am using multiple queries and it's working fine, the only issue I am facing is that order by is not working. I tried some code like
$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ORDER BY `id` DESC";
it's working fine in phpmyadmin and giving me a proper result. But it's not working where I want to use it.
$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ";
if ( $name !="" ){
$query .= " AND `name` LIKE '".$name."%'"; // id is greater then
}
if ( $status !="" ){
$query .= " AND `status` LIKE '".$status."%'"; // id is greater then
}
if ( $id_from !="" ){
$query .= " AND id >= $id_from "; // id is greater then
}
if ( $id_to !="" ){
$query .= " AND id <= $id_to "; // id is shorter then
}
if ( $class !="" ){
$query .= " AND class IN($class)"; // Selecting class
}
if ( $section !="" ){
$query .= " AND section IN($section)"; // selecting section
}
$result = mysql_query($query);
I want to use order by in this query but order by is not working with this.
$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ORDER BY `id` DESC";
AND also used
$query = "SELECT id, name, reg_number, class, section FROM register where id IS NOT NULL ORDER BY id DESC";
I don't know what's the problem with my code.
Just add ORDER BY when finish your WHERE:
if ( $section !="" ){
$query .= " AND section IN($section)"; // selecting section
}
$query .= " ORDER BY id DESC";
$result = mysql_query($query);

if argument inside mysql query

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";

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);

PHP rand query results - check so the new randomized query is not the same as previous

my PHP code looks like this right now:
$query = mysql_query("SELECT * FROM `questions` WHERE `id` = '$id' ORDER BY RAND()") or die(mysql_error());
$cmd = mysql_fetch_assoc($query);
$question = $cmd['question'];
Right now, the questions just get randomized - which is fine - but sometimes the same question appears again, and I don't want that. I assume you can fix this with a session. But how? If someone can fix the code, I'd really appreciate.
Perhaps something like this:
$query = "SELECT * FROM `questions` WHERE `id` = `$id` AND `id` NOT IN (";
$query .= implode(', ', array_keys($_SESSION['questions']));
$query .= ') ORDER BY RAND()';
mysql_query($query) or die(mysql_error());
// Here add the returned questions to the $_SESSION['questions'] array so they would not appear again.
I don't know how the rest of the program works, so the logic you need may be a little different, but I'm sure that sort of query is what you're looking for.
This should do what you need:
$query = mysql_query("SELECT * FROM `questions` WHERE `id` = '$id' ORDER BY RAND()") or die(mysql_error());
$question = null;
while ($cmd = mysql_fetch_assoc($query)) {
if (array_search($cmd['question'], $_SESSION['asked']))
continue;
$question = $cmd['question'];
$_SESSION['asked'][] = $question;
break;
}
if (!$question) {
// No unique questions found.
} else {
// $question will be unique here
}
You can store the ID of all previous asked questions inside your session:
if (!isset($_SESSION['QuestionAsked']))
{
$_SESSION['QuestionAsked'] = array();
}
You can then extend your query to exclude all asked questions:
$query = 'SELECT * FROM `questions`';
if ($_SESSION['QuestionAsked'])
{
$askedIds = implode(',', $_SESSION['QuestionAsked']);
$query .= sprintf(' WHERE `id` NOT IN (%s)', $askedIds);
}
$query .= ' ORDER BY RAND()';
And finally after querying a new question, add it to the session:
$_SESSION['QuestionAsked'][] = $currentQuestionId;

Categories