I have a search function on my website with 4 checkboxes. These are then pasted to the next page where I want to find all products which match the criteria of the check boxes.
As I have 4 check boxes I want to use 4 'ands' but I believe 3 is the max (?)
How can I get around this so it searches to see if all products are matched?
HTML Form
<div id = "search">
<form name = search action = "search.php" method = "POST">
<p class = "big"> Refine Menu </p>
<hr>
<input type = "text" name = "search" placeholder = "Search for an item" size = "12">
<input type = "submit" value = "Go">
<br><br>
<input type = "checkbox" name = "vegetarian"> Vegetarian
<br><input type = "checkbox" name = "vegan"> Vegan
<br><input type = "checkbox" name = "coeliac"> Coeliac
<br><input type = "checkbox" name = "nutFree"> Nut free
</form>
</div>
PHP
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = NULL;
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = NULL;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = NULL;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = NULL;
}
$sql = "SELECT * FROM products WHERE vegan = '$vegan' and nutFree = '$nutFree' and vegetarian = '$vegetarian' and coeliac = '$coeliac'";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
I've tried a number of different thing but I don't know the correct syntax for the sql.
NOTE: In my database whether it meets the requierment on it is saved as either a 1 or 0 that is why I changed it from 'on' or 'off'
Rather than a large, unmaintainable chain of if statements, you might consider something similar to the following, which will dynamically build up your query depending on which of your required fields have been checked in your form:
<?php
$search_fields = array( 'vegetarian', 'vegan', 'nutFree', 'coeliac', ...);
$ands = array( '1' => '1');
foreach($search_fields as $req)
{
if(isset($_POST[$req]) && $_POST[$req] != '')
{
$ands[$req] = "$req = '1'";
}
}
$and_part = implode(" AND ", $ands);
$query = "select .... from ... WHERE $and_part ... ";
?>
I managed to solve my problem. I was mistaken when I posted the question because the reason I thought my sql statement wasn't working was because there were too many ands and I didn't see that rather my sql didn't do what I thought it should.
Here is what I changed it to or it has set values or the check boxes ticked but always the ones which aren't to be either or.
Thanks for everyone's help!
<?php
session_start();
include "connection.php";
if(!isset($_SESSION["username"])){
header("Location: login.php");
}
if(isset($_POST["search"])){
$search = $_POST["search"];
}
if(isset($_POST["vegetarian"])){
$vegetarian = 1;
}
else{
$vegetarian = " ";
}
if(isset($_POST["vegan"])){
$vegan = 1;
}
else{
$vegan = " " ;
}
if(isset($_POST["coeliac"])){
$coeliac = 1;
}
else{
$coeliac = " " ;
}
if(isset($_POST["nutFree"])){
$nutFree = 1;
}
else{
$nutFree = " ";
}
$sql = "SELECT * FROM products WHERE (vegan = '$vegan' or vegan = 1 xor 0) and (nutFree = '$nutFree' or nutFree = 1 xor 0) and (vegetarian = '$vegetarian' or vegetarian = 1 xor 0) and (coeliac = '$coeliac' or coeliac = 1 xor 0)";
$result = mysqli_query($con, $sql);
while($row = mysqli_fetch_assoc($result)){
echo $row ["name"];
}
PHP's NULL have no significance when converted to a string (the SQL query), they will evaluate to empty and your query will look like nutFree = '' and vegetarian = '' and coeliac = ''.
If those fields are 0 in the database, you must set the variables to 0 then.
On a second case, if they are NULL in the database, you must change both your query and the way you define NULL here.
First, those string wrappers should go away. You don't need them for numbers anyway, those are supposed to wrap strings only:
$sql = "SELECT * FROM products WHERE vegan = $vegan and nutFree = $nutFree and vegetarian = $vegetarian and coeliac = $coeliac";
And then instead of setting the variables to NULL, you will set them to the string "NULL".
$nutFree = "NULL";
This will make NULL show on the SQL query as its expected to.
Related
I want to update multiple authors but when i click the update button it saves last inputted value on all of the fields. Your response is highly appreciated. Thank you so much!!!
Here is my code
<?php
}elseif($ID[0]=="Update"){
$Author_Query = mysql_query("SELECT a.*, b.* FROM tblAuthor a, tblResources b WHERE a.Accession_No = b.Accession_No AND a.Accession_No = '".$ID[1]."'");
while($Author = mysql_fetch_array($Author_Query)){
?>
<td><input type="text" name="Author[]" value="<?php echo $_POST['Author']; ?><?php echo $Author['Author']; ?>" /></td>
<?php }} ?>
Update button code
if($_POST['Update'] == "Update"){
$Ac1 = $_POST['Accession1'];
$Ac2 = $_POST['Accession2'];
do{
mysql_query("UPDATE tblResources SET
Accession_No = '".$Ac1."',
Month = '".$_POST['Month']."',
Day = '".$_POST['Day']."',
RYear = '".$_POST['RYear']."',
Class = '".$_POST['Class']."',
Title = '".$_POST['Title']."',
Edition = '".$_POST['Edition']."',
Volumes = '".$_POST['Volumes']."',
Pages = '".$_POST['Pages']."',
Source_of_Fund = '".$_POST['Source_of_Fund']."',
Cost_Price = '".$_POST['Cost_Price']."',
Publisher = '".$_POST['Publisher']."',
Year = '".$_POST['Year']."',
Remarks = '".$_POST['Remarks']."',
Category_ID = '".$_POST['Category']."',
Type_ID = '".$_POST['ResType']."',
Copies = '1',
Availability = '".$_POST['Availability']."',
Tag = 'Title',
Year_Level = '".$_POST['Year_Level']."'
WHERE
Accession_No = '".$Ac1."'");
//$q = $Text."/";
//$gets = explode("/",$q);
$Get = $_POST['Author'];
$Box = count($Get);
for($Text = 0; $Text < $Box; $Text++){
$TextBox = $Get[$Text];
mysql_query("UPDATE tblAuthor
SET Author = '".$TextBox."'
WHERE Accession_No = '".$Ac1."'");
}
$Ac1++;
}while($Ac1 <= $Ac2);
echo "<script language=javascript>
alert('Successfully Updated!');
location.href='Resources.php';
</script>";
}
The problem happen because field 'Accession_No' it's same for author, so the effective update always the last one.
I think something like this solve your problem:
$Get = $_POST['Author'];
$Box = count($Get);
if($Box > 0) {
mysql_query("DELETE FROM tblAuthor WHERE Accession_No = '".$Ac1."'");
foreach($Get as $author){
mysql_query("INSERT INTO tblAuthor (Author, Accession_No) VALUES ('".$author."', ".$Ac1.");
}
}
It's necessary remove the author, because if one author isn't in table before, the mysql not update, the record doesn't exists. So, it's easy remove all authors and insert again.
I have a blog where I'm selecting the articles from a database using PHP. The problem is that becuase of my search terms I'm hitting an error. Here is my code:
<?php
if(isset($_GET["cat"])){
$cat = $_GET["cat"];
}else{
$cat = "all";
};
?>
<?php
if($cat == "all"){
$cat_var = "";
}else{
$cat_var = "WHERE cat = '$cat'";
}; // NOTE THIS LINE
?>
<?php
if(isset($_GET["issue"])){$issue = $_GET["issue"];}else{
$issue = "all";
};
?>
<?php
if($issue == "all"){
$issue_var = "";
$limit = 4;
}
else{
$issue_var = "AND issue = '$issue'"; // NOTE THIS LINE
$limit = 200;
};
?>
<?php
$count_posts_sql = "SELECT id FROM articles $cat_var $issue_var"; // NOTE THIS LINE
$count_posts_res = mysqli_query($con, $count_posts_sql);
$num_init_posts = mysqli_num_rows($count_posts_res);
//If None, Then Exit
if($num_init_posts == 0){
header("Location: /home");
exit();
}
...
?>
So my url would be http://website.com/articles/all/2015-10, which is what I want. However $cat_var & $issue_var is causing the error because it's selecting:
SELECT * FROM articles AND issue = '2015-10' // NO WHERE STATEMEMT IS SHOWN
How do I overcome this error?
You could get this going by sticking a WHERE 1=1 in
$count_posts_sql = "SELECT id FROM articles WHERE 1=1 $cat_var $issue_var"; // NOTE THIS LINE
This is because you start off with an AND value = 1 without starting the WHERE clause, which creates an invalid query.
Then take the WHERE out of this line and replacing it with an AND:
$cat_var = "AND cat = '$cat'";
You can initialize your where query string like this:
$where = 'WHERE 1 = 1 ';
and for there after you can concatenate depending on your inputs.
I am having a problem when I want to echo "The stock is less than what you want". The problem is the user still can update the cart when the stock in my database less that what the user wants. It should show an error "The stock is less than what you want".
This is my code.
<?php session_start();
require("config.php");
$user = $_SESSION['userlogin'];
$cek = mysql_query("SELECT * FROM transaksitbl WHERE username = '$user' AND status ='0'") or die(mysql_error());
$result = mysql_num_rows($cek);
$data = mysql_fetch_array($cek);
if ($result > 0)
{
$faktur =$data['notransaksi'];
for ($i=1; $i<=$_POST['n']; $i++)
{
$idp = $_POST['id'.$i];
$cari2 = mysql_query("SELECT * FROM barangtbl WHERE id='$idp'") or die(mysql_error());
$row2 = mysql_fetch_array($cari2);
$har = $row2['harga'];
$stock = $row2['stock'];
if($_POST['n'] <= $row2['stock'])
{
echo "The stock is less than what you want";
}
if ($cari2)
{
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
}
}
}
header ("location:shopping_cart.php");
?>
If i understood you properly the
if($cari2){}
function is executing?
All you are checking there is if the $cari2 variable is true.
Simply make a else statement out of the if($cari2){} statement so that if the stock is less than you wan't the second if statement won't get executed.
So, like this:
if($_POST['n'] <= $row2['stock']){
echo "The stock is less than you want";
}
else {
if($scari2){
$jmlubah = $_POST['jumlah'.$i];
$beratnew = $jmlubah*$row2['berat'];
$totubah = $jmlubah*$har;
$query = mysql_query("UPDATE transaksirincitbl SET jumlah = $jmlubah, jumlah_berat = $beratnew, total_berat = $beratnew, subtotal=$totubah
WHERE id ='$idp' and username = '$user' And notransaksi =$faktur") or die(mysql_error());
} else {
die('Woop, there seems to be a problem with the $scari2 variable. The value is:' . $scari2);
} // END OF INNER ELSE
} // END OF ELSE
And one more thing NEVER forget to use the mysql_real_escape_string() function on a variable before submiting it's value to the database.
I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query
I'm still learning more interesting details about PHP. Example: Moving from MySQL to MySQLi. What I am currently doing is trying enter something like this: http://music.daum.net/artist/main?artist_id=2289
From what I learned from pagination by dicing the url:
main?
artist_id=
2289
How can I be able to make a page like that? I have 2 sections available and will make the others when figuring this out.
artist information (available as testhub-artist.php)
album (available as testhub-artistalbum.php)
music video
photo section
I want to make it easier when making pages instead of making separate folders for each person.
My url would be: "../artist/detail?artist_id=#"
This is at the top of the artist page.
<?php
//Connect to ...
include "testhub-artist.php";
include "testhub-artistalbum.php";
?>
testhub-artist.php
<?php
//Connect to database
include "mysqli_connect.php";
// Construct our join query
$sql = "SELECT * FROM individuals WHERE soloID = 1";
// Create results
$result = mysqli_query($link, $sql);
// Checking if query is successful
if($result){
// Print out the contents of each row into a table
while($row = mysqli_fetch_array($result, MYSQLI_BOTH)){
// If else states on each variable
if ($profilepic = $row['profilepic']){
$profilepic = $row['profilepic'];
}else{
$profilepic = "DamjuNoImage";
}
if ($engname = $row['engname']){
$engname = $row['engname'];
}else{
$engname = "Unknown";
}
if ($korname = $row['korname']){
$korname = $row['korname'];
}else{
$korname = "Unknown";
}
if ($engbn = $row['engbn']){
$engbn = $row['engbn'];
}else{
$engbn = "Unknown";
}
if ($korbn = $row['korbn']){
$korbn = $row['korbn'];
}else{
$korbn = "Unknown";
}
if ($dateofbirth = $row['dateofbirth']){
$dateofbirth = $row['dateofbirth'];
}else{
$dateofbirth = "Unknown";
}
if ($occupation = $row['occupation']){
$occupation = $row['occupation'];
}else{
$occupation = "Unknown";
}
if ($debut = $row['debut']){
$debut = $row['debut'];
}else{
$debut = "Unknown";
}
if ($recordlabel = $row['recordlabel']){
$recordlabel = $row['recordlabel'];
}else{
$recordlabel = "Unknown";
}
if ($officialsite = $row['officialsite']){
$officialsite = $row['officialsite'];
}else{
$officialsite = "#";
}
if ($sitename = $row['sitename']){
$sitename = $row['sitename'];
}else{
$sitename = "Unknown";
}
} // End of while statement
}else{
$engname = "Unknown";
$korname = "Unknown";
$engbn = "Unknown";
$korbn = "Unknown";
$dateofbirth = "Unknown";
$occupation = "Unknown";
$debut = "Unknown";
$recordlabel = "Unknown";
$officialsite = "#";
$sitename = "Unknown";
} // End of If statement
// Free result set
//mysqli_free_result($result);
?>
testhub-artistalbum.php
<?php
//connect to db
include "mysqli_connect.php";
//check for a page number. If not, set it to page 1
if (!(isset($_GET['albumpage']))){
$albumpage = 1;
}else{
$albumpage = $_GET['albumpage'];
}
//query for record count to setup pagination
$sqli = "SELECT * FROM albums WHERE soloID = 3";
$album_data = mysqli_query($link, $sqli);
$album_rows = mysqli_num_rows($album_data);
//number of photos per page
$album_pagerows = 4;
//get the last page number
$last_album = ceil($album_rows/$album_pagerows);
//make sure the page number isn't below one, or more than last page num
if ($albumpage < 1){
$albumpage = 1;
}elseif ($albumpage > $last_album){
$albumpage = $last_album;
}
//Set the range to display in query
$max_album = 'limit ' .($albumpage - 1) * $album_pagerows .',' .$album_pagerows;
//get all of the photos
$albumList = "";
$sqli2 = "SELECT * FROM albums WHERE soloID = 3 ORDER BY releasedate DESC $max_album";
$album_sql = mysqli_query($link, $sqli2);
//check for photos
$albumCount = mysqli_num_rows($album_sql);
if ($albumCount > 0){
while($album_rows = mysqli_fetch_array($album_sql)){
$albumID = $album_rows["albumID"];
$albumpic = $album_rows["albumpic"];
$title = $album_rows["albumTitle"];
$releasedate = $album_rows["releasedate"];
$page = $album_rows["page"];
$albumList .= '
<li class="albumthumb">
<img class="profile" src="../albums/album_th/' . $albumpic . '.jpg" alt="' . $albumpic . '" width="120" height="120" border="0" /><p class="datatitle">' . $title . '</p><p class="data-releasedate">' . $releasedate . '</p>
</li>
';
}
}else{
$albumList = "There are no available albums at this time!";
}
//mysql_close();
?>
Sorry for not explaining clearly. I want to be able to use pagination when making a profile page like the url. I want to use the number in the url to change the id (soloID) in the sql code.
Good idea in saving time, right? MySQLi getting easier every time I see it.
Thank you.
Changed 5/31/2012 5:44PM CT
$artist = $_GET['artist_id']
into
if(is_numeric($_GET['artist_id'])){
$artist = $_GET['artist_id'];
}else{
$artist = 1;
}
artist/detail?artist_id=#
You would use detail as the page, (probably have a detail folder with a index) and on the detail page, have a $_GET[] variable somewhere that gets the artist_id. So your code could look something like this:
$artist = $_GET['artist_id']; // Filter this variable
$sql = "SELECT * FROM individuals WHERE soloID = '{$artist}'";
/**
* Verify if the ID exists
* Display query results, etc.
*/
So everytime you change the artist_id variable in the URL, the page should change accordingly.
Welcome to my second favorite language! I love php.
Someone already answered your question, but I have some suggestions.
The code you have isn't vulnerable as is cause the user provided data is passed through math... but inlining variables is a good way to leave yourself open to SQL Injection attacks. Look up bind_param() and prepared statements and get in the habit of using them. Always. Well almost always..
Unfortunately SQL doesn't allow you to bind things like the values you use for LIMIT,ORDER BY,GROUP BY so you have to handle those yourself.
Never trust anything derived from a user, so do the work and check it.
Sort columns should always be column names. Check them.
if ( ! in_array($sort_column,array('column1','column2','column3') ) ) $sort_column = 'column1';
Limits should always be integers. Cast them as such.
$safe_limit = (int) $user_limit;
There is no need to copy the array values into another variable. Just use them directly.
You need to escape your values going into html. Lookup urlencode() and htmlentities().
My IE is up to a gig of memory so I'll have to finish this up later.