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.
Related
I am trying to get a table to generate based on the sql query in this page, and I have it working with one item in the dropdown menu.
However if I select two, nothing happens, probably because I am either storing the variable incorrectly in $forum or I am accessing it incorrectly in the if $row statement further down.
Please help me understand what to do.
Thanks!
<select name="forums" multiple>
<option disabled selected value> -- Select a forum -- </option>
<?php
$con = mysqli_connect("host","user","pass","db");
if (!$con) {
die('Connection failed: ' . mysqli_connect_error() . '<br>');
}
$productName='
SELECT p.name
FROM product as p
JOIN ownedproducts as o
on o.productID = p.productID
WHERE usersID = 2;
';
$result=mysqli_query($con, $productName);
while ($row = mysqli_fetch_assoc($result)) {
unset($id);
$id = $row['name'];
echo '<option value="'.$id.'">'.$id.'</option>';
}
if(isset($_GET["forums"])){
$forum=$_GET["forums"];
echo "selected forum => ".$forum;
}
?>
</select>
<input type="submit" class = "submit" value="submit" onclick="this.form.submit();" />
</form>
</div>
<hr>
<table class = "table">
<tr id=table-row>
<th id=table-header>Name</th>
<th id=table-header>Company</th>
<th id=table-header>Type</th>
</tr>
<?php
while ($row = $query1->fetch())
{
if ($row['name']== $forum) {
echo "<tr id=" . $row['productID'] . ">";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['company'] . "</td>";
echo "<td>" . $row['Type'] . "</td>";
echo "</tr>";
}
}
?>```
I cannot seem to get the value from my dropdown box which is using JQuery linked up to my database, into an SQL statement?
Where is the error?
Thanks
Here is my PHP:
<form action="" method="post">
<p class="timetable-p">Room code:
<select id="combobox" name="combobox">
<form action="" method="post"><?php
echo '<option class="option">Type/Select a room</option>';
while ($row = $res->fetchRow()) {
$code = $row['roomcode'];
$titles[] = $row['park'];
echo '<option class="option" name="codedrop">'.$code.'</option>';
}
?>
<input type="submit" value="subm" name="subm">
</form>
<?php
if( isset( $_POST['subm'] ) )
{
$codedropOption= $_POST['codedrop'];
$resql = "SELECT * FROM 'ROOMS' WHERE 'roomCode' LIKE '$codedrop%'";
$res1 = mysql_query($resql);
echo "<table>";
while($row = mysql_fetch_array($res1)){
echo "<tr><td>" . $row['roomCode'] . "</td>";
echo "<td>" . $row['Style'] . "</td><td>" . $row['dataProjector'] . "</td>";
echo "<td>" . $row['Whiteboard'] . "</td><td>" . $row['OHP'] . "</td>";
echo "<td>" . $row['wheelchairAccess'] . "</td>";
echo "<td>" . $row['lectureCapture'] . "</td>";
echo "<td><input type='radio' name='radioSelect' value= '". $row['roomCode']."'></td>";
}
echo "</table>";
}
?>
</form>
1) Remove name="codedrop" from <option> Like
echo '<option class="option">'.$code.'</option>';
N.B.: Only <select> bears the name attribute, not <option>.
2) Remove first <form>, it's of no use. And even, nested <form> are not allowed.
3) Change
$codedropOption= $_POST['codedrop'];
To
$codedropOption= $_POST['combobox'];
to not get
Undefined index: codedrop
4) Change
$resql = "SELECT * FROM 'ROOMS' WHERE 'roomCode' LIKE '$codedrop%'";
To
$resql = "SELECT * FROM ROOMS WHERE roomCode LIKE '$codedrop%'";
Use backtick in place of single quotes '.
5) Change
$resql = "SELECT * FROM 'ROOMS' WHERE 'roomCode' LIKE '$codedrop%'";
To
$resql = "SELECT * FROM ROOMS WHERE roomCode LIKE '$codedropOption%'";
Updated Code
<form action="" method="post">
<p class="timetable-p">Room code:
<select id="combobox" name="combobox">
<?php
echo '<option class="option">Type/Select a room</option>';
while ($row = $res->fetchRow()) {
$code = $row['roomcode'];
$titles[] = $row['park'];
echo '<option class="option">'.$code.'</option>';
}?>
</select>
<input type="submit" value="subm" name="subm">
</form>
<?php
if( isset( $_POST['subm'] ) )
{
$codedropOption= $_POST['combobox'];
$resql = "SELECT * FROM ROOMS WHERE roomCode LIKE '$codedropOption%'";
$res1 = mysql_query($resql);
echo "<table>";
while($row = mysql_fetch_array($res1)){
echo "<tr><td>" . $row['roomCode'] . "</td>";
echo "<td>" . $row['Style'] . "</td><td>" . $row['dataProjector'] . "</td>";
echo "<td>" . $row['Whiteboard'] . "</td><td>" . $row['OHP'] . "</td>";
echo "<td>" . $row['wheelchairAccess'] . "</td>";
echo "<td>" . $row['lectureCapture'] . "</td>";
echo "<td><input type='radio' name='radioSelect' value= '". $row['roomCode']."'></td>";
}
echo "</table>";
}
?>
How do I retrieve data from a SQL table, modify the data and store it in another database table with multiple rows & columns and with single submit button I want insert every rows at a time I don't know how to get that hidden value and work properly with that
<?php
include"connect_database.php";
if(isset($_POST['submit'])) {
$amt = $_POST['total'];
if($amt > 0) {
$qry = "INSERT INTO attendance(rollno, name, year, attendance, reason) VALUES "; // Split the mysql_query
for($i=1; $i<=$amt; $i++) {
$qry .= "('".$_POST["rollno$i"]."', '".$_POST["name$i"]."', '".$_POST["year$i"]."', '".$_POST["attendance$i"]."', '".$_POST["reason$i"]."' ),"; // loop the mysql_query values to avoid more server loding time
}
$qry = substr($qry, 0, strlen($qry)-2);
$insert = mysqli_query($dbcon, $qry); // Execute the mysql_query
}
// Redirect for each cases
if($insert) {
$msg = '<script type="text/javascript">alert("added");</script>';
}
else {
$msg = '<script type="text/javascript">alert("Server Error, Kindly Try Again");</script>';
}
};
if (isset($_POST['select']))
{
$sql = "SELECT * FROM data WHERE year='" . $_POST['yr'] . "'";
$myData = mysqli_query($dbcon, $sql);
$num = mysqli_num_rows($myData);
echo "<table border=1>
<tr>
<th>Rollno</th>
<th>Name</th>
<th>Year</th>
<th>Attendance</th>
<th>reason</th>
</tr>";
for ($i=0; $i <$num; $i++)
{
$record = mysqli_fetch_array($myData);
echo "<form action=smanage.php method=post>";
echo "<tr>";
echo "<td>" . "<input type=text name=rollno$i value=" . $record['rollno'] . " </td>";
echo "<td>" . "<input type=text name=name$i value=" . $record['name'] . " </td>";
echo "<td>" . "<input type=text name=year$i value=" . $record['year'] . " </td>";
echo "<td> "."<select name=attendance$i >
<option value=Present >present</option>
<option value=Absent >Absent</option>
</select>"."</td>";
echo "<td>". "<textarea cols=15 rows=2 name=reason$i placeholder=Enter reason ...></textarea>" . "</td>" ;
echo "<td>" . "<input type=hidden name=total value=" . $i-1 . "</td>";
echo "</tr>";
}
echo"</table>";
echo "<input type=submit name=submit value=save class=Button3>";
echo "</form>";
};
mysqli_close($dbcon);
?>
you are opening multiple forms, for each row in your table on.
This causes your html to be invalid, just start the form before displaying the table.
You could use this html
<table>
<?php
for ($i = 0; $i < $num; $i++) {
$record = mysqli_fetch_array($myData);
?>
<tr>
<td><input type="text" name="rollno[<?= $record['rollno'] ?>]" value="<?= $record['rollno'] ?>" </td>
<td><input type="text" name="name[<?= $record['rollno'] ?>]" value="<?= $record['name']?>" </td>
<td><input type="text" name="year[<?= $record['rollno'] ?>]" value="<?= $record['year'] ?>" </td>
<td><select name="attendance[<?= $record['rollno'] ?>]" >
<option value="Present" >present</option>
<option value="Absent" >Absent</option>
</select></td>
<td><textarea cols="15" rows="2" name="reason[<?= $record['rollno'] ?>]" placeholder="Enter reason ..."></textarea></td>
</tr>
<?php
}
?>
</table>
with this your values will every row will be put into the $_POST-Array, you can access the values via the indexes (I am guessing rollno represents the ID of the dataset).
When you really only want to insert all the values into a table, you can leave the index out. Meaning you could write
<td><input type="text" name="rollno[]" value="<?= $record['rollno'] ?>" </td>
Instead of
<td><input type="text" name="rollno[<?= $record['rollno'] ?>]" value="<?= $record['rollno'] ?>" </td>
You don't need the hidden field, you can just count the items in the array.
$total = count($_POST['rollno']);
<?php
include"connect_database.php";
if(isset($_POST['submit'])) {
$amt = $_POST['total'];
$rollnos= $_POST['rollno'];
if($amt > 0) {
$qry = "INSERT INTO attendance(rollno, name, year, attendance, reason) VALUES "; // Split the mysql_query
$i=0;
foreach($rollnos as $rollno) {
$qry .= "('".$rollno."', '".$_POST["name"][$i]."', '".$_POST["year"][$i]."', '".$_POST["attendance"][$i]."', '".$_POST["reason"][$i]."' ),"; // loop the mysql_query values to avoid more server loding time
$i=$i+1;
}
$qry = substr($qry, 0, strlen($qry)-2);
$insert = mysqli_query($dbcon, $qry); // Execute the mysql_query
}
// Redirect for each cases
if($insert) {
$msg = '<script type="text/javascript">alert("added");</script>';
}
else {
$msg = '<script type="text/javascript">alert("Server Error, Kindly Try Again");</script>';
}
};
if (isset($_POST['select']))
{
$sql = "SELECT * FROM data WHERE year='" . $_POST['yr'] . "'";
$myData = mysqli_query($dbcon, $sql);
$num = mysqli_num_rows($myData);
echo "<table border=1>
<tr>
<th>Rollno</th>
<th>Name</th>
<th>Year</th>
<th>Attendance</th>
<th>reason</th>
</tr>";
for ($i=0; $i <$num; $i++)
{
$record = mysqli_fetch_array($myData);
echo "<form action=smanage.php method=post>";
echo "<tr>";
echo "<td>" . "<input type='text' name='rollno[]' value='" . $record['rollno'] . "'> </td>";
echo "<td>" . "<input type='text' name='name[]' value='" . $record['name'] . "'> </td>";
echo "<td>" . "<input type='text' name='year[]' value='" . $record['year'] . "'> </td>";
echo "<td> "."<select name='attendance[]' >
<option value='Present' >present</option>
<option value='Absent' >Absent</option>
</select>"."</td>";
echo "<td>". "<textarea cols='15' rows='2' name='reason[]' placeholder='Enter reason ...'></textarea>" . "</td>" ;
echo "<td></td>";
echo "</tr>";
}
echo "<input type='hidden' name='total' value='" . $i-1 . "'>";
echo"</table>";
echo "<input type='submit' name='submit' value='save' class='Button3'>";
echo "</form>";
};
mysqli_close($dbcon);
?>
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";
I have been batting this around for a while and can not get the variables working for a search. Can connect fine and return results defined as a proper mssql_query and also am fine order by on variables etc but trying to get a text search implemented is not returning results not sure why.
<?php
$link = mssql_connect('SERV13\\RALSQL12', 'RA4joomla', 'Fenestron1');
if (!$link || !mssql_select_db('RALNHV', $link)) {
die('Unable to connect or select database!');
}else{
echo"";
}
if(isset($_REQUEST['submit'])){
$firstname=$_POST['FirstName'];
$surname=$_POST['Surname'];
$query = 'SELECT * FROM lEmployee WHERE FirstName LIKE '%".$firstname."%' OR Surname LIKE '%".$surname."%'';
$q=mssql_query($sql);
}
else{
$query = 'SELECT * FROM lEmployee';
$q = mssql_query($query);
}
?>
<form method="post">
<table width="200" border="1">
<tr>
<td>Name</td>
<td><input type="text" name="firstname" value="<?php echo $firstname;?>" /></td>
<td>Email</td>
<td><input type="text" name="surname" value="<?php echo $surname;?>" /></td>
<td><input type="submit" name="submit" value=" Find " /></td>
</tr>
</table>
</form>
<?php
// Check if there were any records
echo "<table class='table'>";
echo "<tr>";
echo "<th><a href='?orderBy=FirstName'>FirstName</a></th><th><a href='?orderBy=Surname'>Surname</a></th><th><a href='?orderBy=EmployeeNo'>Trigram</a></th><th>Office Phone</th><th>Mobile</th><th><a href='?orderBy=EmployeeJobTitle'>Job Title</a></th><th><a href='?orderBy=Name'>Base</a></th>";
echo "</tr>";
while ($row = mssql_fetch_array($query)) {
echo "<tr>";
echo "<td>" . '' . iconv("CP1252", "UTF-8", $row['FirstName']) . '' . "</td>";
echo "<td>" . '' . iconv("CP1252", "UTF-8", $row['Surname']) . '' . "</td>";
echo "<td>" . '' . $row['EmployeeNo'] . '' . "</td>";
echo "<td>" . '' . $row['Phone'] . '' . "</td>";
echo "<td>" . '' . $row['Mobile'] . '' . "</td>";
echo "<td>" . '' . $row['EmployeeJobTitle'] . '' . "</td>";
echo "<td>" . '' . $row['Name'] . '' . "</td>";
echo "</tr>";
}
echo "</table>";
?>
I am 100% agree with nickL you have some formating issue in your query try to replace your search query by this:
$firstname=$_POST['firstname'];
$surname=$_POST['surname'];
$query = "SELECT * FROM lEmployee WHERE FirstName LIKE '%".$firstname."%' OR Surname LIKE '%".$surname."%'";
$q=mssql_query($sql);
php is a case sensitive language your post variables name are wrong replace the code and try again, if not succeeded try echo $query and run it in query browser in sql server.
hope this will fix the issue.