I have a website that currently shows data from my database. I also have some checkboxes. Now I want it to show only the rows that correspond with these checkboxes when the user checks them. This is what I have so far:
Checkboxes:
<form>
Actie<input type="checkbox" name="genre" value="actie">
Sport<input type="checkbox" name="genre" value="sport">
<input type="submit" name="formSubmit" value="Submit">
</form>
How I show stuff from the database:
$con->set_charset("utf8");
$result = mysqli_query($con,"SELECT Product,Prijs,Beschrijving FROM Producten order by Product ASC LIMIT 0, 5");
echo '<table border="1px solid black" cellspacing="0" style="margin-top:47px"><tbody>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td rowspan='2' width= '200'>" . $row['Product'] . "</td>";
echo "<td><b>" . $row['Product'] . "</b></td>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['Beschrijving'] . " <i>Prijs: € " . $row['Prijs'] . " </i><br/><br/></td>";
echo "</tr>";
}
I know I can use WHERE to show only the data I want, I just don't know how to do this only when a checkbox is checked.
Try this:
if($_POST['genre']!=""){
$query="SELECT Product,Prijs,Beschrijving FROM Producten order by WHERE genre=".$_POST['genre']." Product ASC LIMIT 0,5";
}
else{
$query="SELECT Product,Prijs,Beschrijving FROM Producten order by Product ASC LIMIT 0,5";
}
$con->set_charset("utf8");
$result = mysqli_query($con,$query);
echo '<table border="1px solid black" cellspacing="0" style="margin-top:47px"><tbody>';
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td rowspan='2' width= '200'>" . $row['Product'] . "</td>";
echo "<td><b>" . $row['Product'] . "</b></td>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['Beschrijving'] . " <i>Prijs: € " . $row['Prijs']."</i><br/><br/></td>";
echo "</tr>";
}
You can check if genre has a value or is set.
if ($_POST['genre'] != "")
{
...
}
or
if(isset($_POST['genre']))
{
...
}
You need something like this:
$sql = "SELECT Product,Prijs,Beschrijving FROM Producten";
if(isset($_POST['genre'])){
$sql .= " WHERE Producten.`genre` IN (";
$genres = implode(',', $POST['genre']);
$genres = "'" . str_replace(",", "','", $genres) . "'";
$sql .= $genres;
$sql .= ")";
}
$sql .= " order by Product ASC LIMIT 0, 5";
$result = mysqli_query($con, $sql);
Secondly, you need to replace
Actie<input type="checkbox" name="genre" value="actie">
Sport<input type="checkbox" name="genre" value="sport">
with
Actie<input type="checkbox" name="genre[]" value="actie">
Sport<input type="checkbox" name="genre[]" value="sport">
Related
I am working with three database tables.
users
class
user_class
I'm making a page so that student can be assigned to classes using a checkbox. How do I get it so that if the value of a student being in a class is currently in the database, the checkbox for that class will already have the student value checked.
<?php
$showAllStudents = "SELECT * FROM users";
mysqli_query($mysqli, $showAllStudents) or die ('Error finding Students');
$result = mysqli_query($mysqli, $showAllStudents);
echo"<table border='1' cellspacing='10' align='center'>";
echo "<tr><th></th><th>User ID</th><th>User Name</th><th>First Name</th>
<th>Second Name</th></tr>";
while ($row = $result->fetch_object()){
echo "<tr>";
echo "<td><input type='checkbox' id='" .$row->userID . "'
name='check_box[]' value='" .$row->userID . "' /></td>";
echo "<td>" .$row->userID . "</td>";
echo "<td>" .$row->username . "</td>";
echo "<td>" .$row->forename . "</td>";
echo "<td>" .$row->surname . "</td>";
echo "</tr>";
}
if (isset($_POST['submitClassStudent'])) {
//get ID from header
$classID = $_GET['id'];
//print_r ($_POST);
//for each ticked checkbox convert to a UserID variable
foreach ($_POST['check_box'] as $userID) {
$editClassStudentQuery = "INSERT INTO `user_class`(userID, classID)
VALUES('$userID', '$classID')";
$insert_row = $mysqli->query($editClassStudentQuery) or die($mysqli->error . __LINE__);
if ($insert_row) {
header('Location: classeditor.php');
} else {
echo "Error: " . $editClassStudentQuery . "<br>" . $mysqli->error;
}
}
}
?>
To mark a checkbox as already checked you just need to add checked as one of its attributes.
<input type="checkbox" id="already-checked" checked> Already checked
W3 Schools
if the user exists then echo 'checked' in tag
Example: echo "<input type ='checkbox'";if(YourConditionHere)echo "checked>";else echo ">";
I'm trying to use form processing to make a specific database query. I set the form to $name and am trying to process $sql = "SELECT * FROM quotes WHERE qSymbol = $name ORDER BY qQuoteDateTime DESC"
What is the best way to do this?
<form action="post.php" method="post">
<span></span><input type = "text" value=" " name="boxy" />
<br/><input type="submit" name="submit" value="Enter" />
</form>
<?php
$name = $_POST['boxy'];
if(isset($_POST['boxy'])){
error_reporting(E_ALL ^ E_DEPRECATED);
$con = mysql_connect('...');
if (!$con){
die("Cannot connect : " . mysql_error());
}
mysql_select_db('quotesdb',$con);
$sql = "SELECT * FROM quotes WHERE qSymbol = '$name' ORDER BY qQuoteDateTime DESC";
$myData = mysql_query($sql,$con);
echo "<table border = 1>
<tr>
<th>Data</th>
<th>Last</th>
<th>Change</th>
<th>% Chg</th>
<th>Volume</th>
</tr>";
while ($record = mysql_fetch_array($myData)){
echo "<tr>";
echo "<td>" . $record['qQuoteDateTime'] . "</td>";
echo "<td>" . $record['qLastSalePrice'] . "</td>";
echo "<td>" . $record['qNetChangePrice'] . "</td>";
echo "<td>" . $record['qNetChangePct'] . "</td>";
echo "<td>" . $record['qShareVolumeQty'] . "</td>";
echo "</tr>";
echo "</table>";
mysql_close($con);
}
You will still need single quotes around the variable unless it's a number
$sql = "SELECT * FROM quotes WHERE qSymbol = '$name' ORDER BY qQuoteDateTime DESC";
I am trying to send the same email only to selected users. I am printing values from table and want to select specific users to send an email.
<form name="unos" action="mail-proizvodi.php" method="post">
<?
echo "<table border='5'>
<tr>
<th> </th>
<th>ID</th>
<th>NAZIV</th>
<th>ADRESA</th>
<th>DRZAVA</th>
<th>GRAD</th>
<th>EMAIL</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo '<td><input type="checkbox" name="email[]" value="' . $row['ID'] . '"></td>';
echo "<td>" . $row['ID'] . "</td>";
echo "<td>" . $row['NAZIV'] . "</td>";
echo "<td>" . $row['ADRESA'] . "</td>";
echo "<td>" . $row['DRZAVA'] . "</td>";
echo "<td>" . $row['GRAD'] . "</td>";
echo "<td>" . $row['EMAIL'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
<input type="submit" name="submit" value="submit">
</form>
my mail-proizvodi.php code
$mail=$_POST['email'];
echo "Dzenad catic";
$query= "SELECT `EMAIL` FROM `clanovi` WHERE ID='$mail[0]'";
if(sizeof($mail)>1)
{
for($i=1; $i<sizeof($mail); $i++)
{
$query.=" OR ID = '$mail[$i]' ";
}
}
$result=mysqli_query($con,$query);
while(FALSE!==($row=mysqli_fetch_row($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:test#test.ba?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
echo "Send" ;
Post I am receiving is an array. And when I do var_dump($mail) I get
array
0 => string '20' (length=2)
1 => string '30' (length=2)
Any help or advice is appreciated. Thanks in advance.
I am posting solution for the problem I had in case someone else face similar mistake.
$mail=$_POST['email'];
$query= "SELECT `EMAIL` FROM `clanovi` WHERE ID ='$mail[0]'";
if(sizeof($mail)>1)
{
for($i=1; $i<sizeof($mail); $i++)
{
$query.=" OR ID = '$mail[$i]' ";
}
}
$result=mysql_query($query);
if (!$result) {
echo "Could not successfully run query ($query) from DB: " . mysql_error();
exit;
}
if (mysql_num_rows($result) == 0) {
echo "No rows found, nothing to print so am exiting";
exit;
}
while(FALSE!==($row=mysql_fetch_assoc($result))) {
$bccfields[] = $row['EMAIL'];
}
echo sprintf("<a href=mailto:prodaja#alternativa.ba?bcc=%s />\n",
urlencode(implode(',',$bccfields)));
echo "Send" ;
mysql_free_result($result);
I am trying to filter my results using a series of dropdown boxes which are populated from other tables within the database, except for a primary option which is returned from the form as *
Currently the form submits the data as expected, but no results are returned. I suspect it is because the query is searching for * in the respective columns.
So the question is, can an asterisk be used as a wildcard in a WHERE statement?
And if not, how would I go about this instead?
offending code is included, i understand that using a $variable in a query is bad practice, but at this stage i'm searching for a functional solution, rather than production code.
cheers.
echo " <form method=\"post\" action=\"$self\">
<table>
<tr>
<th>ID</th>
<th>REGISTER</th>
<th>LOCATION</th>
<th>TYPE</th>
<th>CAPACITY</th>
<th>LENGTH</th>
<th>QTY</th>
<th>SERIAL#</th>
<th>CERT#</th>
<th>LAST INSPECTION</th>
<th>BY</th>
<th>DATE IN</th>
<th>DATE OUT</th>
<th>STATUS</th>
<th>NOTES</th>
</tr>";
?>
<!-- START OF FILTER ROW -->
<tr>
<td></td>
<td> <select name="register" id="register">
<option value="*">---</option>
<?php
$sql = "SELECT * FROM valid_registers";
foreach ($dbh->query($sql) as $row)
{
echo "<option value\"" . $row['register'] . "\">" . $row['register'] . "</option>";
}
?>
</select></td>
<td> <select name="location" id="location">
<option value="*">---</option>
<?php
$sql = "SELECT * FROM valid_locations";
foreach ($dbh->query($sql) as $row)
{
echo "<option value\"" . $row['location'] . "\">" . $row['location'] . "</option>";
}
?>
</select></td>
<td> <select name="type" id="type">
<option value="*">---</option>
<?php
$sql = "SELECT * FROM valid_types";
foreach ($dbh->query($sql) as $row)
{
echo "<option value\"" . $row['type'] . "\">" . $row['type'] . "</option>";
}
?>
</select> </td>
<td><input type="radio" name="capacity" id="cap_asc" value="cap_asc">
<
<input type="radio" name="capacity" id="cap_dec" value="cap_dec">
></td>
<td><input type="radio" name="length" id="length_asc" value="length_asc">
<
<input type="radio" name="length" id="length_des" value="length_des">
></td>
<td> </td>
<td> </td>
<td> </td>
<td><input type="radio" name="lastinsp" id="lastinsp_asc" value="lastinsp_asc">
<
<input type="radio" name="lastinsp" id="lastinsp_dec" value="lastinsp_dec">
></td>
<td> </td>
<td><input type="radio" name="datein" id="datein_asc" value="datein_asc">
<
<input type="radio" name="datein" id="datein_dec" value="datein_dec">
></td>
<td><input type="radio" name="dateout" id="dateout_asc" value="dateout_asc">
<
<input type="radio" name="dateout" id="dateout_dec" value="dateout_dec">
></td>
<td> <select name="status" id="status">
<option value="*">---</option>
<?php
$sql = "SELECT * FROM valid_status";
foreach ($dbh->query($sql) as $row)
{
echo "<option value\"" . $row['status'] . "\">" . $row['status'] . "</option>";
}
?>
</select> </td>
<td> </td>
<td><input type="submit" name="submit_filter" id="submit_filter" value="Filter"></td>
</tr>
<!--END OF FILTER ROW -->
<?
//get data from the db
if(isset($_POST['submit_filter'])) {
//fetch filter options
$register = $_POST['register'];
$location = $_POST['location'];
$type = $_POST['type'];
$status = $_POST['status'];
//prepare and execute the query
$sql = "SELECT * FROM register WHERE register=$reigster AND location=$location AND type=$type AND status=$status ";
}
else { $sql = "SELECT * FROM register"; }
foreach ($dbh->query($sql) as $row)
{
echo "<tr>";
echo "<td>" . $row['id'] . "</td>";
echo "<td>" . $row['register'] . "</td>";
echo "<td>" . $row['location'] . "</td>";
echo "<td>" . $row['type'] . "</td>";
echo "<td>" . $row['capacity'] . "</td>";
echo "<td>" . $row['length'] . "</td>";
echo "<td>" . $row['qty'] . "</td>";
echo "<td>" . $row['serial'] . "</td>";
echo "<td>" . $row['cert'] . "</td>";
echo "<td>" . $row['lastinsp'] . "</td>";
echo "<td>" . $row['inspby'] . "</td>";
echo "<td>" . $row['datein'] . "</td>";
echo "<td>" . $row['dateout'] . "</td>";
echo "<td>" . $row['status'] . "</td>";
echo "<td>" . $row['notes'] . "</td>";
echo "<td><a href='" . $self . "?edit=" . $row['id'] . "'>Edit</a></td>";
//echo "<td><input type=\"submit\" name=\"edit\" id=\"edit\" value=\"Edit\" /></td>";
echo "<td><a href='" . $self . "?delete=" . $row['id'] . "'>Delete</a></td>";
//echo "<td><input type=\"submit\" name=\"delete\" id=\"delete\" value=\"Delete\" /></td>";
echo "</tr>";
}
echo "</table></form>";
}
No, the * is really only valid in the columns you select, not in the where clause.
The usual way to do this is to catch the * from the form and use that to modify the actual SQL statement by removing that part of the where clause altogether, something like (pseudo-code):
if param['userid'] == '*':
query = 'select name from users'
else:
query = 'select name from users where id = ?'
Although I have seen cases where parameterised queries needed a consistent number of parameters regardless of wild-carding (in some BIRT reports I've looked at where the query is modified dynamically but the parameter count is harder to change), so you would get something like:
if param['userid'] == '*':
query = 'select name from users where (id = ? or 1 = 1)'
else:
query = 'select name from users where id = ?'
That's a bit of a kludge but it's sometimes used to ease the developers workload. I'd rather do it the first way where possible.
To do that for multiple conditions, you can do something like:
joiner = " where "
query = "select something from mytable"
if param['userid'] != '*':
query = query + joiner + "user_id = '" + param['id'] + "'"
joiner = " and "
if param['age'] != '*':
query = query + joiner + "user_age = " + param['age']
joiner = " and "
if param['gender'] != '*':
query = query + joiner + "user_sex = '" + param['gender'] + "'"
joiner = " and "
keeping in mind that, unless you have already sanitised your param[] array values, you risk SQL injection attacks). I leave out the solution for that since it's irrelevant to the question at hand.
I am having problem in getting values from db. Iam new in php
I am using checkboxes to get values from database. Only checked values should be printed.
<form method="POST" action="gradoviexport.php" id="searchform">
<div id="GRADOVI BIH">
<h3>GRADOVI BOSNE I HERCEGOVINE</h3><hr/>
<input type="checkbox" name="gradovi[]" value="sarajevo"> Sarajevo
<input type="checkbox" name="gradovi[]" value="banovici"> Banovići
<input type="checkbox" name="gradovi[]" value="banjaluka"> Banja Luka
<input type="checkbox" name="gradovi[]" value="bihac"> Bihać
<input type="checkbox" name="gradovi[]" value="bileca"> Bileća
</div>
<div id="snimi">
<input type="submit" name="submit" value="EXPORT">
</div>
</form>
If Sarajevo is checked I want to print values from database. It does not have to be only one value checked If all values are checked it should print all values.
$con=mysqli_connect("$host","$username","$password", "$database");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
//connecting to db
$variable=$_POST['grad'];
foreach ($variable as $variablename)
{
$sql_select="SELECT * FROM `clanovi` WHERE `GRAD` = $variablename " ;
$queryRes = mysql_query($sql_select);
print"$sql_select";
}
echo "<table border='5'>
<tr>
<th>IME</th>
<th>PREZIME</th>
<th>FIRMA</th>
<th>ADRESA</th>
<th>TELEFON</th>
<th>FAX</th>
<th>MOBITEL</th>
<th>EMAIL </th>
<th>WEB_STRANICA </th>
<th>GRAD </th>
<th>KATEGORIJA </th>
</tr>";
while($row = mysqli_fetch_array($queryRes))
{
echo "<tr>";
echo "<td>" . $row['IME'] . "</td>";
echo "<td>" . $row['PREZIME'] . "</td>";
echo "<td>" . $row['FIRMA'] . "</td>";
echo "<td>" . $row['ADRESA'] . "</td>";
echo "<td>" . $row['TELEFON'] . "</td>";
echo "<td>" . $row['FAX'] . "</td>";
echo "<td>" . $row['MOBITEL'] . "</td>";
echo "<td>" . $row['EMAIL'] . "</td>";
echo "<td>" . $row['WEB_STRANICA'] . "</td>";
echo "<td>" . $row['GRAD'] . "</td>";
echo "<td>" . $row['KATEGORIJA'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
Assume you posted gradovi[] array values to submitted page.
Submit page:
$grad = array();
$grad = $_POST['gradovi']; //get array value
$grad = implode(',',$grad); //convert it into comma separated string
//Insert it into data base
Getting from database:
//fetch the gradovi field from the db like below
echo $row['gradovi']; // print all values
or
$grad = explode(',',$row['gradovi']);
foreach($grad as $check) {
echo $check; //print one by one
}
There is few errors in your code.
There is no escaping of the string from POST data. Use mysqli_real_escape_string
There is an error in your while loop. You redefining mysql query result.
Fixed code:
//connecting to db
$variable=$_POST['grad'];
foreach($variable as $key => $val) {
$variable[$key] = mysql_escape_string($val);
}
$sql_select="SELECT * FROM `clanovi` WHERE `GRAD` IN ('" . implode("','", $variable) . "')" ;
$queryRes = mysql_query($sql_select);
print"$sql_select";