Can't get the values from multiple select with $_GET request - php

I'd like some help please.
I'm sending with a GET request from a multiple select field the selected values to my proccess page (archive.php)
<form id="form1" class="four columns" action="archive.php" method="get" name="form1">
<select id="select2" multiple="multiple" name="location[]">
<option value="103001000">value1</option>
<option value="103002000">value2</option>
<option value="103003000">value3</option>
<option value="103004000">value4</option>
</select>
I get the selected locations on my url like this
location[]=103002000&location[]=103003000
and in the archive.php I'm trying to fetch data from the database like this
if (( isset($_GET['location']) && !empty($_GET['location']) )) {
die(var_dump($_GET['location'])); // the var_dump doesn't return an array at all
$loc = implode(', ', $_GET['location']);
$sql="SELECT * FROM locations WHERE AreaID IN (". $loc.")";
}
but I'm getting the following error: Error: Unknown column 'Array' in 'where clause'.
How can I fix this?

try with as below it might be simple
if (( isset($_GET['location']) && !empty($_GET['location']) )) {
die(var_dump($_GET['location'])); // the var_dump doesn't return an array at all
//$loc = implode(', ', $_GET['location']);
$_GET['location'] = array('first'=>'loc1','second'=>'loc2','third'=>'loc3');
$loc = implode('","', $_GET['location']);
$loc ='"'.$loc.'"';
$sql='SELECT * FROM locations WHERE AreaID IN ('.$loc.')';
echo $sql;
}
result query
SELECT * FROM locations WHERE AreaID IN ("loc1","loc2","loc3")

Related

How to filter based on two arguments from php, in a SQL database

I have a MySQL database, and the table I need to work with has 9 columns of information. My goal is to be able to filter, based on two arguments. For instance, the table is about students so it has data for first name, last name, id, course they are signed up for, status, occupation age and another 2 fields that are not that important. I need to be able to filter, based on the student's status and/or the course.
So far, I managed to get the php work done, with a form and a select tag, to filter based on status, but I have no idea how to add the second part. The done thing should be able to filter, based on status only, based on course only, or based on the selected status and course. The code looks like this:
if (isset($_POST['filter'])) {
$search_term = mysqli_real_escape_string($conn, $_POST['filter_status']);
$q .= " WHERE status = '$search_term'";
}
echo $q;
<form method="POST" action="index.php">
<select name="filter_status" >
<option value="confirmed">confirmed</option>
<option value="declined">declined</option>
<option value="rejected">rejected</option>
<option value="pending">pending</option>
<option value="unconfirmed">unconfirmed</option>
</select>
<input type="submit" name="filter">
</form>
This works correctly, I have it a second time for the second criteria, but they don't work together.
try to change,
$q .= " WHERE status = '$search_term'";
to
$q .= " WHERE CONCAT_WS(',',status,course) like %'$search_term'%";
you can add as many columns after course.
$filter_status = $_POST['filter_status'];
$course = $_POST['course'];
$where = 'WHERE 1';
$where .= $filter_status ? " AND status = {$filter_status}" : '';
$where .= $course ? " AND course = {$course}" : '';
Did you mean this? when user select course and filter_status use this two conditions, on the other hand use one of conditions which is being selected.
The WHERE 1 will always be TRUE, so it can be followed by AND statements
Use the term AND or OR in your query after WHERE
WHERE status = '$search_term' AND course = '$something'
Thank you all for your input. It helped nudge me in the right direction. The code that ended up doing what I needed is as follows. It's not very elegant, but it does the job well:
$q = "SELECT *
FROM students";
if (isset($_POST['filter'])) {
if ($_POST['filter_status'] == null) {
$search_term2 = mysqli_real_escape_string($conn, $_POST['filter_course']);
$q .= " WHERE course = '$search_term2'";
} elseif ($_POST['filter_course'] == null) {
$search_term = mysqli_real_escape_string($conn, $_POST['filter_status']);
$q .= " WHERE status = '$search_term'";
} else {
$search_term = mysqli_real_escape_string($conn, $_POST['filter_status']);
$search_term2 = mysqli_real_escape_string($conn, $_POST['filter_course']);
$q .= " WHERE status = '$search_term' AND course = '$search_term2'";
}
}
And the form:
<form method="POST" action="index.php">
<select name="filter_status" >
<option value= ""></option>
<option value="confirmed">confirmed</option>
<option value="declined">declined</option>
<option value="rejected">rejected</option>
<option value="pending">pending</option>
<option value="unconfirmed">unconfirmed</option>
</select>
<select name="filter_course">
<option value= ""></option>
<option value="php">php</option>
<option value="java">java</option>
</select>
<input type="submit" name="filter">
</form>

Searching using PDO

So I'm trying to execute a search using PDO. I have this search set up:
echo "<form action = 'user.php?search=yes' method = 'post' id='searchform'>
<a href='user.php?newuser=yes'>Add New User</a> || Search By
<select name = 'paramet' form = 'searchform'>
<option value = 'userID'>User ID</option>
<option value = 'firstname'>First Name</option>
<option value = 'lastname'>Last Name</option>
<option value = 'email'>E-Mail</option>
<option value = 'mobileno'>Mobile Number</option>
<option value = 'homeno'>Home Number</option>
</select>
<select name = 'howso' form = 'searchform'>
<option value = 'contains'>which contains</option>
<option value = 'equalto'>which is equal to</option>
</select>
<input type = 'text' name='criteria' required>
<input type = 'submit' value='Search'>
</form>
And then this handling the query:
{
$param = $_POST['paramet'];
$how = $_POST['howso'];
$crite = $_POST['criteria'];
if($how == 'contains')
{
$query = $hsdbc->prepare("SELECT * FROM user WHERE :param LIKE :crite");
$query->bindParam(':param', $param);
$query->bindValue(':crite', '%' . $crite . '%');
$query->execute();
}
else{
$query = $hsdbc->prepare("SELECT * FROM user WHERE :param = :crite");
$query->bindParam(':param', $param);
$query->bindParam(':crite', $crite);
$query->execute();
}
I'm getting no-where near the correct results. Any help?
You can't bind column names. The best you can do is add the name to a white list array or something and insert it manually.
if(in_array($param, $good_params_array)) {
$query = $hsdbc->prepare("SELECT * FROM user WHERE $param LIKE :crite");
$query->bindValue(':crite', '%' . $crite . '%');
$query->execute();
}
I've seen people query the DB for the table description to get the columns to see if the column name is listed, but that requires an addition DB request. Also, you might want to limit the fields they can search against

Insert multiple form selections into one single table column (set)

I have a simple form with the following:
<form action="#" method="post" name="form1" >
<input name="criteria1" size="64">
<input name="criteria2" size="64">
<select name="criteria3[]"multiple="multiple" >
<option value="5 ">5</option>
<option value="7">7</option>
<option value="10">10</option>
</select>
</form>
Now, if the user selects more then one option from criteria3, how do I insert that in a single database table field as well as insert the other two criteria in their own column?
I have tried many different ways and just get no where. My last attempt was as follows:
$values = array();
$type = explode(",", $_POST['criteria3']);
foreach ($type as $value) {
$values[] = sprintf('(%d)', $value);
}
$values = implode(',', $values);
if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
$insertSQL = sprintf("INSERT INTO table (name, date, number)
VALUES (%s, %s, '$values')",
GetSQLValueString($_POST['criteria1'], "text"),
GetSQLValueString($_POST['criteria2'], "text"));
Not really sure what is going wrong – have tried several iterations and am getting no where.
Here are the most recent errors:
Warning: explode() expects parameter 2 to be string, array given in /filename.php on line 84
Warning: Invalid argument supplied for foreach() in /filename.php on line 86
Try the following(If you want separate records corresponding to separate values for criteria3 for a single entity):
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
$arr=$_POST['criteria3'];
foreach($arr as $criteria3)
{
$sql="insert into table_name (criteria1, criteria2, criteria3) values('".$criteria1."', '".$criteria2."', '".$criteria3."')";
mysql_query($sql);
}
And if you want a single record for a single entity with multiple criteria3-values use the following code:
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
if(isset($_POST['criteria3'])) //true when at least on of the options is selected.
{
$criteria3=implode(',', $_POST['criteria3']);
}
else //i.e. when no option is selected.
{
$criteria3='';
}
$sql="insert into table_name (criteria1, criteria2, criteria3) values('".$criteria1."', '".$criteria2."', '".$criteria3."')";
mysql_query($sql);
Since I am the only one that will be inserting data - I found a crude work around until I can get the code that Rajesh provided to work - I think this is the right path if I can get it to work.Thanks to all for your input. If I could, I would give you all the up vote!
remove the explode function from $_POST['criteria3'], Because it is already array it not need of explode so you try directly
$type = $_POST['criteria3'];
foreach($type as $k => $v) {
// here do the INSERT query with value $v
}
or if you prefer this link
1).Getting data from a multiple select dropdown with PHP to insert into MySQL
hope this helpful for you :)
<form action="" method="post" name="form1" >
<input name="criteria1" size="64">
<input name="criteria2" size="64">
<select name="criteria3[]" multiple >
<option value="5 ">5</option>
<option value="7">7</option>
<option value="10">10</option>
</select>
<?php
if(isset($_POST['submit']))
{
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
if(isset($_POST['criteria3']))
{
$query = "insert into table_name (criteria1, criteria2, criteria3) values";
foreach($_POST['criteria3'] as $list)
{
$query .= "('$criteria1','$criteria2','$list')";
}
echo $query;
}
}
?>
Explode only works with a string.
What you get from your form for criteria3 is an array, so you should act accordingly:
$criteria1 = $_POST['criteria1'];
$criteria2 = $_POST['criteria2'];
$criteria3 = implode(",", $_POST['criteria3']);
Here we generate a string based on the content of the table returned by your form.
We seperate each element by a comma.
Then we create the SQL query.
$sql = sprintf("INSERT INTO table (name, date, number) VALUES (%s, %s, %s);", $criteria1, $criteria2, $criteria3);
Hope this helps.

How to use "any" in select list of a form to work in mysql?

I have form which use below codes:
<select name="ptype">
<option selected="selected" value="">Any</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
now, how can the php page process the "Any" field in mysql. I tried below code, but didnot worked on process page:
$q = mysql_query("SELECT * FROM `listing` WHERE ptype='{$_POST['ptype']}'");
echo mysql_error();
while($r=mysql_fetch_array($q)){
}
There are multiple select option which use "any", all fields run on same query. here any means all value
what may be the error ? or how to use "any" value ?
$ptype = $_POST['ptype'];
if ($ptype == "Any") {
$w = " WHERE 1";
} else {
$w = " WHERE ptype = '" . $ptype . "'";
}
$q = mysql_query("SELECT * FROM `listing`" . $w);
echo mysql_error();
while ($r = mysql_fetch_array($q)) {
....
}
Check for it separately:
SELECT *
FROM `listing`
WHERE '{$_POST['ptype']}' = 'ANY' or ptype='{$_POST['ptype']}'
If any means that both can work, just drop the WHERE clause from your query if $_POST['ptype'] doesn't have a value (or give it a value and check for that).
If the option is any, programitically change your query as :
$q=mysql_query("SELECT * FROM `listing`");

search by category with php mysql

hello im using this code to do search
<form action="arama.php" method="get">
<input type="text" name="lol">
<select name='kategori'>
<option value="tum">Tum kategoriler</option>
<?
while ($kat = mysql_fetch_array($kategori_isim)) {
echo "
<option value=".$kat[kategori_isim].">".$kat[kategori_isim]."</option>";
}
?>
</select>
<input type="submit" value="ara">
</form>
<?
$lol = mysql_real_escape_string($_GET['lol']);
$kategori = mysql_real_escape_string($_GET['kategori']);
if ($kategori == "tum") {
$ara = mysql_query("select * from dosyalar where baslik like '%$lol%'");
}
else {
$ara = mysql_query("select * from dosyalar where baslik like '%$lol%' order by kategori = '%$kategori%'");
}
?>
search by term works but not listing by kategori.. what can i do?
I'm not sure I understand the question (I can't really figure out what those fields mean), but I think that your second query should be more like:
$ara = mysql_query("SELECT * FROM dosyalar WHERE kategori LIKE '%$kategori%'");
ORDER BY only specifies how to sort the results, you can only use a column name, not a check as in your code.
Extending my answer: the ORDER BY kategori = '%$kategori%' isn't a syntax error but I don't think it does anything useful. The check kategori = '%$kategori%' will always be false (unless you have a value with percent signs both at start and at end) so the ORDER BY clause will be useless and you will just do the same select you're doing in the other branch of the if block.
Specifying ORDER BY kategori = '$kategori' will return 0 for all the records where kategori is not equal to $kategori, 1 for the ones where it matches. This will basically sort all the matching rows at the end of your query.
Maybe the query failed. In that case mysql_query() returns FALSE and mysql_error() returns a description of the error.
Try
<form action="arama.php" method="get">
<input type="text" name="lol" />
<select name='kategori'>
<option value="tum">Tum kategoriler</option>
<?php
while ( false!==($kat=mysql_fetch_array($kategori_isim)) ) {
$htmlIsim = htmlspecialchars($kat['kategori_isim']);
echo ' <option value="', $htmlIsim, '">', $htmlIsim, "</option>\n";
}
?>
</select>
<input type="submit" value="ara" />
</form>
<?php
$lol = isset($_GET['lol']) ? mysql_real_escape_string($_GET['lol']) : '';
$kategori = isset($_GET['kategori']) ? mysql_real_escape_string($_GET['kategori']) : '';
$query = "select * from dosyalar where baslik like '%$lol%'";
if ( 'tum'!==$kategori ) {
$query .= "order by kategori = '%$kategori%'";
}
$ara = mysql_query($query) or die( htmlspecialchars(mysql_error().': '.$query) );
echo '<pre>Debug: ', mysql_num_rows($ara) , ' records in the result set for ', htmlspecialchars($query), "</pre>\n";
?>

Categories