Search multiple values if present - php

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

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

PHP elseif statement defaults to first block

I am trying the following elseif statement to call the correct code based on a POST from the previous page and it has been defaulting to using only the first block of code i am aware that this might not be the best way to carry out the code in this situation so i'd like to ask if anyone has a more efficient way of doing this THANKS
elseif ($toyota="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";
}
elseif ($bmw="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";
}
elseif ($subaru="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";
}
elseif ($mitsubishi="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";
}
elseif ($nissan="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";
}
elseif ($mazda="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";
}
elseif ($chrysler="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";
}
Forgot to mention,the post from html comes like
"toyota=on", "bmw=on" and so on
$cars = array('toyota', 'bmw', 'nissan');
foreach ($cars as $car) {
if (!isset($_POST[$car]) || $_POST[$car] != 'on') {
continue;
}
$query = "SELECT * FROM `products` WHERE name LIKE '%$car%'";
break;
}
There is difference between = and ==.
= assigns value, whereas == compares value.
replace all your = with ==
($toyota=="on"){
There is much better way to do that instead of using so many if else blocks. try using a varibale in the query based on the input.
A single = will set a value whereas a double == will test for equality
elseif ($toyota=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%toyota%'";
}
elseif ($bmw=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Bmw%'";
}
elseif ($subaru=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Subaru%'";
}
elseif ($mitsubishi=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mitsubi%'";
}
elseif ($nissan=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Nissan%'";
}
elseif ($mazda=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Mazda%'";
}
elseif ($chrysler=="on"){
$query = "SELECT * FROM `products` WHERE name LIKE '%Chrysler%'";
}

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

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