I have a multiple checkbox search query which fetches data from database. Below is the code:
HTML code:
<form action="search.php" method="post">
<input type="checkbox" name="cloth_color[]" value="Red" /> Red <br>
<input type="checkbox" name="cloth_color[]" value="Yellow" /> Yellow <br>
<input type="checkbox" name="cloth_color[]" value="Blue" /> Blue <br>
<input type="checkbox" name="cloth_color[]" value="Green" /> Green <br>
<input type="checkbox" name="cloth_color[]" value="Magenta" /> Magenta <br>
<input type="checkbox" name="cloth_color[]" value="Black" /> Black <br>
<input type="checkbox" name="cloth_color[]" value="White" /> White <br>
<input type="submit" value="SEARCH">
</form>
PHP code:
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1;
}
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
}
?>
Now if I choose one option from the search select box I get query. But if I select two or more color I dont get the query. A help will be really appreciated.
P.S. I do have multiple joins in Mysql query but this is the place I am stuck so presenting as clear question as possible here. Also I intent to convert mysql to mysqli before the launch of this code. Thank you :)
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= $chk1 . ",";
}
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($chk)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
?>
you can try this code which will use IN() of MySQL where you can pass multiple , separated values.
Hope this helps
Ok this is what i did. first of all got great help from #Dhaval and #Carlos as wasn't familiar with IN function in Mysql.
<?php
$checkbox1 = $_POST['cloth_color'];
$chk="";
foreach($checkbox1 as $chk1)
{
$chk .= "'" . $chk1."', ";
//This is important as it is not the number it is a word so it should have a single quote if in query we are using double quote or vice versa.
}
$check_e = rtrim($chk,", ");
//Although i havn't checked in real time if mysql query will take last comma or not but it is a good practice to remove the last comma by rtrim.
if($_POST['cloth_color'] != "") {
$query = "SELECT * FROM clothings WHERE colorofcloth IN($check_e)";
$result = mysql_query($query);
while($row = mysql_fetch_array($result)) {
$colorofcloth = $row['colorofcloth'];
echo 'The cloth with ' . $colorofcloth . ' color';
echo '<br>';
}
?>
What you may want to use is the Mysql IN CLause.
For this example, i am assuming that you use the correct syntax for the elements inside de IN Clause.
The correct syntax would be all the values that you need separated by commas, if you select red and blue.
$chk = 'red, blue'
Using the 'IN Clause' this query
$query = "SELECT * FROM clothings WHERE colorofcloth = '$chk'";
should transform to this.
$query = "SELECT * FROM clothings WHERE colorofcloth IN ('$chk')";
I do not know much about PHP, but for a database stand it should work.
Let me know if it works.
Related
I have a form with two fieldsets which contains checkboxes:
<fieldset style="width:300px; height:200px; overflow:scroll;">
<input type="checkbox" name="table[]" id="01" value='ado'> Adoption <br />
<input type="checkbox" name="table[]" id="02" value='acc'> Accomodations <br />
<input type="checkbox" name="table[]" id="03" value='ann'> Announcements <br />
<input type="checkbox" name="table[]" id="04" value="bea"> Beauty/Fitness <br />
<input type="checkbox" name="table[]" id="05" value="bus"> Business Oportunities
</fieldset>
and this one
<fieldset style="width:300px; height:200px; overflow:scroll;">
<input type="checkbox" name="State[]" id="01" value='AL'> Alabama <br />
<input type="checkbox" name="State[]" id="02" value='AK'> Alaska<br />
<input type="checkbox" name="State[]" id="03" value='AZ'> Arizona<br />
<input type="checkbox" name="State[]" id="04" value='AR'> Arkansas <br />
<input type="checkbox" name="State[]" id="05" value='CA'> California <br />
</fieldset>
Im using this code to go into their respective tables
$table = $_POST['table'];
$name = $_POST['name'];
$state = $_POST['State'];
if(is_array($table)){
while(list($tables) = each($table)){
$sql2 = "INSERT INTO tableName (name,table) VALUES ('$name','$tables')";
$q2 = mysqli_query($db_conx,$sql2);
}
}
if(is_array($state)){
while(list($key,$value) = each($state)){
$sql3 = "INSERT INTO states (name,State) VALUES ('$name','$value')";
$q3 = mysqli_query($db_conx,$sql3);
}
}
when it gets executed the only data that gets entered is states
I used
echo "table; ".$table."<br /> State; ".$state;
and got
table; Array
State; Array012ALAKAZ
someone help me!
You are vulnerable to sql injection attacks.
And your table query is using a reserved word, so the entire insert query is failing. Since you failed to check for failure, and simply assumed success, you'll never see any error messages.
Never EVER assume success when dealing with an external resource (especially a database). There's exactly ONE way for a query to succeed, and a near infinite number of ways for it to fail. Yet you seem to think that 1:infinity odds are really good.
$sql2 = "INSERT INTO tableName (name,`table`) VALUES ('$name','$tables')";
^-----^---you need these
$q2 = mysqli_query($db_conx,$sql2) or die(mysqli_error($db_conx));
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^---you also need this
Here you have solution what makes only 2 queries instead of 20 and so queries:
$tables = $_POST['table'];
$name = $_POST['name'];
$states = $_POST['State'];
$states_values = '';
$tables_values = '';
$i = 0;
foreach($states as $state)
{
$i++;
$last = $i == count($states) ? true : false;
$states_values .= '(' . $name . ', ' . $state . ')' . ($last ? '' : ',');
}
$i = 0;
foreach($tables as $table)
{
$i++;
$last = $i == count($tables) ? true : false;
$tables_values .= '(' . $name . ', ' . $table . ')' . ($last ? '' : ',');
}
mysqli_query($db_conx, 'INSERT INTO states (name, State) VALUES ' . $states_values;
mysqli_query($db_conx, 'INSERT INTO tableName (name, table) VALUES ' . $tables_values;
As Marc said, you should escape your inputs.
I'm trying to create new page in PHP(new_page.php), successful created page will be insert into database (create_page.php), but now it is not working, not sure which steps i am missing, any helps are appreciate. Below is my code & screenshots:
Mysql table:
http://i60.tinypic.com/2h3aofr.png
new_page.php
http://i60.tinypic.com/21dmop2.png
<?php $host = "localhost";
$name = "root";
$password = "";
$db = "test_son";
$connection = mysqli_connect($host, $name, $password, $db);
//Check if connect to MySQL works
if (mysqli_connect_errno()){
die("Connection to MySql error " . mysqli_connect_errno());
}?>
<?php
function find_all_pages(){
global $connection;
$query = "select * from pages ";
$query .= "order by position asc";
$page_set = mysqli_query($connection, $query);
confirm_query($page_set);
return $page_set;
}?>
<h2>Create Page</h2>
<form action="create_page.php" method="post">
<p>Subject Id:
<input type="number" name="subject_id" value="" />
</p>
<p>Book name:
<input type="text" name="book_name" value="" />
<br/><br/>
</p>
<p>Position:
<select name="position">
<?php
$page_set = find_all_pages();
$page_count = mysqli_num_rows($page_set);
for ($count=1; $count <= $page_count; $count++){
echo "<option value=\"1\">{$count}</option>";}
?>
</select>
</p>
<p>visible
<input type="radio" name="visible" value="0" /> No
<input type="radio" name="visible" value="0" /> Yes
</p>
<input type="submit" name ="submit" value="Create Page" />
</form>
create_page.php
<?php
if (isset($_POST["submit"])){
//Process the form
$subject_id = $_POST["subject_id"];
$book_name = $_POST["book_name"];
$position = $_POST["position"];
$visible = $_POST["visible"];
$book_name = mysqli_real_escape_string($connection, $book_name);
$subject_id = mysqli_real_escape_string($connection, $subject_id);
//Perform database query
$query = "insert into pages (";
$query .= " subject_id, 'book_name', position, visible";
$query .= " ) values ( ";
$query .= "$subject_id, '$book_name', $position, $visible ";
$query .= ")";
$result = mysqli_query($connection, $query);
if ($result){
//Success will redirect to manage content page
$_SESSION["message"] = "page was created. ";
redirect("manage_content.php");
} else {
//Failure will redirect to new subject page
//$_SESSION["message"] = "subject was not created. Please check following possible errors: <br/> "
//. " menu name is not blank <br/> visible is not blank";
//redirect("new_page.php");
echo "fail " . mysqli_error($connection) ;
}
}
?>
When i submitted the create page button, error appears:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''book_name', position, visible ) values ( 121, 'how to win influence 1234', 1, 0'
You shouldn't have a ' character in the list of column_names .... column names are not string literals, they're column names. If they absolutely have to be quoted (e.g. if you have a column name that is a MySQL reserved word, then you use backticks(`) not quotes (')
$query = "insert into pages (";
$query .= " subject_id, book_name, position, visible";
$query .= " ) values ( ";
$query .= "$subject_id, '$book_name', $position, $visible ";
$query .= ")";
Now please learn about prepared statements and bind variables
There are security vulnerabilities in the way you are creating that query. But to specifically respond to your issue, get rid of the ' around 'book_name'.
Trying to get this to allow for more then 1 check box to be selected.
Form
<fieldset>
<legend>Rooms</legend>
<ol>
<li>
<label for =youthCafe>Youth Cafe</label>
<input type="checkbox" name="roomid[]" value="1" ><br>
<label for =inkwellMain>Inkwell Main</label>
<input type="checkbox" name="roomid[]" value="2"><br>
<label for =inkwellSmall>Inkwell Small</label>
<input type="checkbox" name="roomid[]" value="3"><br>
<label for =kitchen>Kitchen</label>
<input type="checkbox" name="roomid[]" value="4"><br>
<label for =outsideCatering>Outside Catering</label>
<input type="checkbox" name="roomid[]" value="5"><br>
</li>
</ol>
</fieldset>
PHP
mysql_select_db('eydg');
$query = "insert into orders (customerNo)
values ($customerNo)";
$result = mysql_query($query);
$query = "select * from orders where customerNo = '$customerNo'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$bookingNo= $row['bookingNo'];
if ( isset($_POST['roomid']) ){
foreach( $_POST['roomid'] as $value ){
$query = "insert into bookings (bookingNo,roomNo)
values ('$bookingNo','$value')";
$result = mysql_query($query);
}
}
At the moment it will only allow for 1 selection to be added to the database. They all work on their own but if more then 1 is selected then it only inserts the 1st one.
Really cant see what is wrong with it.
Thanks
Sorry, but I can't comment yet.
How many checkboxes have you checked?
Most browsers do not submit unchecked checkboxes.
Also, please provide output of var_dump($_POST) or var_dump($_POST['roomid'])
Note :
the mysql extension is deprecated as of PHP 5.5.0, and will be removed
in the future. Instead, the MySQLi or PDO_MySQL extension should be
used.
You code is ok for me.
I advise you to use xdebug to watch your code running, this will clearly tell you where is the trouble.
But a first step can be to see what this code returns :
foreach( $_POST['roomid'] as $key => $value ){
echo "\n<br>\n<br>array key=" . $key . ' : value=' . $value;
$query = "insert into bookings (bookingNo,roomNo) values ('$bookingNo','$value')";
echo "\n<br>query" . ' : ' . $query;
$result = mysql_query($query, $link);
if(!$result){
echo "\n<br><h1>Error : " . mysql_errno($link) . ": " . mysql_error($link) . '</h1>';
}
}
Here $link is the var holding you connection. So replace this variable before running this code.
I am trying to create a form which allows the user to search for an event using the Venue and category fields which are scripted as dropdown boxes and the Price and finally by event title, as shown via the code if a keyword is entered which matches the fields on the database it should output all the related information for that event if any matches have been made on either search fields, but it seems to output every single event from the database no matter what I type in the search field.
DATABASE: http://i.imgur.com/d4uoXtE.jpg
HTML FORM
<form name="searchform" action ="PHP/searchfunction.php" method = "post" >
<h2>Event Search:</h2>
Use the Check Boxes to indicate which fields you watch to search with
<br /><br />
<h2>Search by Venue:</h2>
<?php
echo "<select name = 'venueName'>";
$queryresult2 = mysql_query($sql2) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult2)) {
echo "\n";
$venueID = $row['venueID'];
$venueName = $row['venueName'];
echo "<option value = '$venueID'";
echo ">$venueName</option>";
}# when the option selected matches the queryresult it will echo this
echo "</select>";
mysql_free_result($queryresult2);
mysql_close($conn);
?>
<input type="checkbox" name="S_venueName">
<br /><br />
<h2>Search by Category:</h2>
<?php
include 'PHP/database_conn.php';
$sql3 ="SELECT catID, catDesc
FROM te_category";
echo "<select name = 'catdesc'>";
$queryresult3 = mysql_query($sql3) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult3)) {
echo "\n";
$catID = $row['catID'];
$catDesc = $row['catDesc'];
echo "<option value = '$catID'";
echo ">$catDesc </option>";
}
echo "</select>";
mysql_free_result($queryresult3);
mysql_close($conn);
?>
<input type="checkbox" name="S_catDes">
<br /><br />
<h2>Search By Price</h2>
<input type="text" name="S_price" />
<input type="checkbox" name="S_CheckPrice">
<br /><br />
<h2>Search By Event title</h2>
<input type="text" name="S_EventT" />
<input type="checkbox" name="S_EventTitle">
<br /><br />
<input name="update" type="submit" id="update" value="Search">
searchfunction.php file
<?php
$count = 0;
include 'database_conn.php';
$venuename = $_REQUEST['venueName']; //this is an integer
$catdesc = $_REQUEST['catdesc']; //this is a string
$Price = $_REQUEST['S_price'];
$EventT = $_REQUEST['S_EventT'];
$sql = "select * FROM te_events WHERE venueID LIKE '%$venuename%' OR catID LIKE '%$catdesc%' OR eventPrice LIKE '%Price%' OR eventTitle LIKE '%$EventT%'";
$queryresult = mysql_query($sql) or die (mysql_error());
while ($row = mysql_fetch_assoc($queryresult))
{
echo $row['eventTitle'];
echo $row['eventDescription'];
echo $row['venueID'];
echo $row['catID'];
echo $row['eventStartDate'];
echo $row['eventEndDate'];
echo $row['eventPrice'];
}
mysql_free_result($queryresult);
mysql_close($conn);
?>
The query should be
$sql = "select * FROM te_events
WHERE (venueID LIKE '%$venuename%'
OR catID LIKE '%$catdesc%'
OR eventPrice LIKE '%$Price%'
OR eventTitle LIKE '%$EventT%')
;
To get values from the form submitted with method POST we use $_POST to access form data and not $_REQUEST:
$venuename = $_POST['venueName']; //this is an integer
$catdesc = $_POST['catdesc']; //this is a string
$Price = $_POST['S_price'];
$EventT = $_POST['S_EventT'];
That was about your problem - now some important notes:
Do not use mysql extension as it's deprecated. Read this official documentation.
Use mysqli and prevent SQL injections by using prepared queries and parameters like in official documentation again.
Since you are matching on any fields surrounded by wildcards, if any of the fields are blank, then the MySQL query will match all rows.
Also, you need to prevent MySQL injection. Otherwise, your MySQL table will eventually be hacked.
By the way, the code eventPrice LIKE '%Price%' is invalid and is missing a dollar sign.
Lastly, the mysql extension has been deprecated. I would recommend using mysqli instead as it is fairly similar.
I have made a simple search engine that can search my database. It works this way: you check the word you want to search for in a checkbox. Result are sent using a form. The issue is that it only searches for the last word checked. This mean do I check 3 words it’s only showing results for the last word checked. Here is my form:
<form method="POST" action="<?=$_SERVER["PHP_SELF"]?>">
<p>Search for:
</p>
Books: <input type="checkbox" name='search' value="Books">
Movies: <input type="checkbox" name='search' value="Movies">
Outdoor: <input type="checkbox" name='search' value="Outdoor">
Indoor: <input type="checkbox" name='search' value="Indoor">
</p>
<p><input type='submit' value='Search'></p>
</form>
This is my codes that generate the result:
<?php
if(isset($_POST['search']))
{
$connx = mysql_connect('localhost', 'USER', 'PASSWORD') or die("connx");
$db = mysql_select_db('DB_NAME') or die(mysql_error());
# convert to upper case, trim it, and replace spaces with "|":
$search = (ini_get('magic_quotes_gpc')) ? stripslashes($_POST['search']) :
$_POST['search'];
$search = mysql_real_escape_string($search);
$search = strtoupper(preg_replace('/\s+/', '|', trim($_POST['search'])));
# create a MySQL REGEXP for the search:
$regexp = "REGEXP '[[:<:]]($search)[[:>:]]'";
$query = "SELECT * FROM `galleries` WHERE UPPER(`keywords1`) $regexp OR ".
"`keywords2` $regexp";
$result = mysql_query($query) or die($query . " - " . mysql_error());
echo "<table>\n";
while($row = mysql_fetch_assoc($result))
{
echo "<tr>";
echo "<td><img src=../thumbs/{$row['type']}/{$row['folder']}/{$row['date']}-{$row['num']}/{$row['thumbimage']} border=1></td>";
echo "<td>{$row['name']}</td>";
echo "<td>{$row['date']}</td>";
echo "<td><a href=../view.php?id={$row['id']} target=blank>View</a></td>";
echo "</tr>\n";
}
}
?>
Can someone help me telling me how do I get the search engine to search and/or show more than 1 word searched result?
You have input fields with same name therefore you are getting the last one you need to make the array for search fields like name="search[]" and the loop through your query against the array values
Books: <input type="checkbox" name='search[]' value="Books">
Movies: <input type="checkbox" name='search[]' value="Movies">
Outdoor: <input type="checkbox" name='search[]' value="Outdoor">
Indoor: <input type="checkbox" name='search[]' value="Indoor">
something like this
$regexp ="";
$searharray =$_POST['search'];
$count=count($searharray);
$index=1;
foreach($searharray as $s){
$s = (ini_get('magic_quotes_gpc')) ? stripslashes($s) :$s;
$s= mysql_real_escape_string($s);
$s = strtoupper(preg_replace('/\s+/', '|', trim($s)));
$regexp .= " UPPER(`keywords1`) REGEXP '[[:<:]](".$s.")[[:>:]]' OR `keywords2` REGEXP '[[:<:]](".$s.")[[:>:]]'";
if($index<$count){
$regexp .=" OR ";
}
$index++
}
$query = "SELECT * FROM `galleries` WHERE $regexp";
Problem fixed! I replaced the 2 lines:
$search = mysql_real_escape_string($search);
$search = strtoupper(preg_replace('/\s+/', '|', ($_POST['search'])));
With:
$search = implode( '|', $_POST['search'] );
And now its working - just if anyone else should need the info :)