Select with multiple conditions - php

In form user need to check options who will receive newsletter, for example:
<input type="checkbox" name="male" value="1" />
<input type="checkbox" name="female" value="1" />
<input type="checkbox" name="person" value="1" />
<input type="checkbox" name="company" value="1" />
But I have problem how to create query for db with checked options
I have this code so far, but it is not good, because newsletter need to be 1 all the time and after that I have OR, because when I put AND I don't get the results that I need:
if($options['male']) {
$sqlAddMale = " OR gender = 2 ";
}
if($options['female']) {
$sqlAddFemale = " OR gender = 1 ";
}
if($options['person']) {
$sqlAddPerson = " OR VAT = '' ";
}
if($options['company']) {
$sqlAddCompany = " OR VAT <> '' ";
}
$query = "
SELECT email FROM users WHERE newsletter=1
".$sqlAddMale."
".$sqlAddFemale."
".$sqlAddPerson."
".$sqlAddCompany."
";

I think You need something like this:
$placeOr = false;
if($options['male']) {
$placeOr = true;
$sqlAddMale = " (newsletter=1 AND gender = 2) ";
}
if($options['female']) {
$sqlAddFemale = (($placeOr)?" Or ":"");
$sqlAddFemale .= " (newsletter=1 AND gender = 1) ";
$placeOr = true;
}
if($options['person']) {
$sqlAddPerson = (($placeOr)?" Or ":"");
$sqlAddPerson .= " (newsletter=1 AND VAT = '') ";
$placeOr = true;
}
if($options['company']) {
$sqlAddCompany = (($placeOr)?" Or ":"");
$sqlAddCompany .= " (newsletter=1 AND VAT <> '') ";
$placeOr = true;
}
$query = "
SELECT email FROM users WHERE
".$sqlAddMale."
".$sqlAddFemale."
".$sqlAddPerson."
".$sqlAddCompany."
";

Here is how you can solve your issue, use one variable to build up your where clause, use AND operater when you are adding the first condition, else use OR
$sqlString = '';
if($options['male']) {
$sqlString = " AND gender = 2 ";
}
if($options['female']) {
if(!$sqlString) $sqlString = " AND gender = 1 ";
else
$sqlString .= " OR gender = 1 ";
}
if($options['person']) {
if(!$sqlString) $sqlString = " AND VAT = '' ";
else
$sqlString .= " OR VAT = '' ";
}
if($options['company']) {
if(!$sqlString) $sqlString = " AND VAT <> '' ";
else
$sqlString .= " OR VAT <> '' ";
}
$query = "SELECT email FROM users WHERE newsletter=1'".$sqlString."'";

Related

sql search with 2 or more fields

Created an sql search query with having multiple fields I created using if else condition it is working fine but if 1 and 2nd field is emty and 3rd field is not then it dies not work just because of OR keyword please advise how I would be able to correct this
<form method="POST" action="search.php?action=go">
<li>
<h3>Player</h3>
<input type="text" class="form-control" placeholder="Dylan Scout" name="playername" value="<?php if(isset($_POST["playername"])) {echo $_POST["playername"];} ?>">
</li>
<li>
<h3>Age</h3>
<input type="text" class="form-control" placeholder="25" name="age" value="<?php if(isset($_POST["age"])) {echo $_POST["age"];} ?>">
</li>
<li>
<h3>Country</h3>
<input type="text" class="form-control" placeholder="Wallabies" name="country" value="<?php if(isset($_POST["country"])) {echo $_POST["country"];} ?>">
</li>
<li>
<h3>Club</h3>
<input type="text" class="form-control" placeholder="Eagle" name="club" value="<?php if(isset($_POST["club"])) {echo $_POST["club"];} ?>">
</li>
<li>
<button type="submit" name="search">Search</button>
</li>
</form>
And here is my sql php query
<?php
if(isset($_GET["action"]) == 'go') {
$stmt = "SELECT * FROM users WHERE";
if($_POST["playername"]) {
$stmt .= " OR fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%'";
}
if($_POST["age"]) {
$stmt .= " OR age LIKE '%".$_POST["age"]."%' ";
}
if($_POST["country"]) {
$stmt .= " OR country LIKE '%".$_POST["country"]."%' ";
}
if($_POST["club"]) {
$stmt .= " OR club LIKE '%".$_POST["club"]."%' ";
}
} else {
$stmt = "SELECT * FROM users ";
}
echo $stmt . "<br />";
$sql = mysqli_query($connection, $stmt);
?>
Please let me know how would I be able to make it work properly as if i write on 3rd fields and leave other fields empty then it will become asWHERE OR which will become obviously wrong query and won't work
Thank You
The function implode will help you.
Add them into an array and connect them after.
<?php
$array = array();
if (isset($_POST["playername"]))
$array[] = "fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%";
if (isset($_POST["age"]))
...
$stmt = "SELECT * FROM users";
if (count($array) > 0)
$stmt .= " WHERE " . implode(" OR ",$array);
$sql = mysqli_query($connection, $stmt);
?>
Try this. Using implode() you can achieve this.
<?php
if(isset($_GET["action"]) == 'go') {
$where = array();
if($_POST["playername"]) {
$where[] = " OR fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%'";
}
if($_POST["age"]) {
$where[] = " OR age LIKE '%".$_POST["age"]."%' ";
}
if($_POST["country"]) {
$where[] = " OR country LIKE '%".$_POST["country"]."%' ";
}
if($_POST["club"]) {
$where[] = " OR club LIKE '%".$_POST["club"]."%' ";
}
if(!empty($where))
{
$stmt = "SELECT * FROM users WHERE " . implode(" AND ", $where) ." ";
}
else
{
$stmt = "SELECT * FROM users ";
}
} else {
$stmt = "SELECT * FROM users ";
}
echo $stmt . "<br />";
$sql = mysqli_query($connection, $stmt);
?>
add where condition to an array, and next use implode function, for example:
<?php
if(isset($_GET["action"]) == 'go') {
$stmt = "SELECT * FROM users";
if($_POST["playername"]) {
$where[] = "fname LIKE '%".$_POST["playername"]."%' OR lname LIKE '%".$_POST["playername"]."%'";
}
if($_POST["age"]) {
$where[] = "age LIKE '%".$_POST["age"]."%' ";
}
if($_POST["country"]) {
$where[] = "country LIKE '%".$_POST["country"]."%' ";
}
if($_POST["club"]) {
$where[] = "club LIKE '%".$_POST["club"]."%' ";
}
if(count($where))
$stmt .= " WHERE " . implode(" OR ", $where);
echo $stmt . "<br />";
$sql = mysqli_query($connection, $stmt);
?>

PHP Multiple input search

I'm currently working on a bit of PHP and I've 3 text inputs. The values are searched in the MySQL database and should return whatever amount of results correspond with the entered criteria.
here is the search form:
<form id='SearchPersonal' method='post' action='businessUsersSearch.php' accept-charset='UTF-8'>
<fieldset >
<legend>Search</legend>
<div class='container'>
<label for='C_Name' >Business Name: </label><br/>
<input type='text' name='C_Name' id='C_Name' maxlength="50" /><br/>
<label for='C_County' >City: </label><br/>
<input type='text' name='C_County' id='C_County' maxlength="50" /><br/>
<label for='Job_Type' >Job Type: </label><br/>
<input type='text' name='Job_Type' id='Job_Type' maxlength="50" /><br/>
</div>
<div class='container'>
<input type='submit' name='Submit' value='Search' />
</div>
</fieldset>
</form>
Here is the PHP script it links too in the action:
<?php
$mysqli_link = mysqli_connect("server", "database", "pass", "user");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_County', 'Job_Type');
$conditions = array();
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && $_POST[$field] != '') {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "'$field' LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// builds the query
$query = "SELECT C_Name, C_StreetNumber, C_StreetName, C_Postcode, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Jobs.Job_Type, Jobs.Job_Price FROM Company INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID";
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
$result = mysqli_query($mysqli_link, $query) or die(mysql_error());
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_assoc($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<hr><br>";
}
}
}
?>
For some reason it is returning that there is "
unexpected end of file
" however I've checked the code and all the codes is closed off correctly (from what I can see) when I add another '}' in at the end the script doesn't return anything at all. Anyone know why this would be happening?
Source:
Search MySQL Database with Multiple Fields in a Form
Because you forget to close
if(isset($_POST['submit'])) {// you not close the condition
At the end of your file
Just add } at end of your file
Fixed:
if(isset($_POST['submit'])) {
// define the list of fields
$fields = array('C_Name', 'C_City', 'Job_Type', 'Review_Rate');
$conditions = array();
}
// builds the query
$query = "SELECT Company.C_Name, Company.C_StreetNumber, C_StreetName, C_Postcode, C_City, C_County, C_Tele, C_Website, Contact_Forename, Contact_Surname, Contact_Email, Job_Type, Job_Price, Review_Rate, Review_Comment
FROM Company
INNER JOIN Jobs ON Company.Company_ID = Jobs.Company_ID
INNER JOIN Review ON Jobs.Job_ID = Review.Job_ID";
// loop through the defined fields
foreach($fields as $field){
// if the field is set and not empty
if(isset($_POST[$field]) && !empty($_POST[$field])) {
// create a new condition while escaping the value inputed by the user (SQL Injection)
$conditions[] = "$field LIKE '%" . mysqli_real_escape_string($mysqli_link, $_POST[$field]) . "%'";
}
}
// if there are conditions defined
if(count($conditions) > 0) {
// append the conditions
$query .= " WHERE " . implode (' AND ', $conditions); // you can change to 'OR', but I suggest to apply the filters cumulative
}
echo "$query";
$result = mysqli_query($mysqli_link, $query);
mysqli_close($mysqli_link);
if(isset($_POST['submit'])) {
while($row = mysqli_fetch_array($result)) {
$C_Name = $row['C_Name'];
$C_StreetNumber = $row['C_StreetNumber'];
$C_StreetName = $row['C_StreetName'];
$C_Postcode = $row['C_Postcode'];
$C_City = $row['C_City'];
$C_County = $row['C_County'];
$C_Tele = $row['C_Tele'];
$C_Website = $row['C_Website'];
$Contact_Forename = $row['Contact_Forename'];
$Contact_Surname = $row['Contact_Surname'];
$Contact_Email = $row['Contact_Email'];
$Job_Type = $row['Job_Type'];
$Job_Price = $row['Job_Price'];
$Rating = $row['Review_Rate'];
$Comment = $row['Review_Comment'];
echo "<b>Name: $C_Name</b><br>Street Number: $C_StreetNumber<br>Street Name: $C_StreetName<br>City: $C_City<br>Postcode: $C_Postcode<br>County: $C_County<br>Telephone: $C_Tele<br>Website: $C_Website<br>Contact Name: $Contact_Forename $Contact_Surname<br>Email: $Contact_Email<br>Job Type: $Job_Type<br>Job Price: $Job_Price<br>Rating: $Rating<br>Comment: $Comment<hr><br>";
}
}
?>

PHP MySQL create query to search multiple tables

I have form like this:
<form method="POST" action="<?php echo base_url() ?>admin/admin_search">
<fieldset>
<label for="nalozi">Nalozi</label><input type="checkbox" name="nalozi" />
<label for="malio_glasi">Mali oglasi</label><input type="checkbox" name="mali_oglasi" />
<label for="zute_strane">Zute strane</label><input type="checkbox" name="zute_strane" />
<label for="berza_rada">Berza rada</label><input type="checkbox" name="berza_rada" />
<label for="vesti">Vesti</label><input type="checkbox" name="vesti" />
<label for="event">Dogadjaji</label><input type="checkbox" name="event" />
</fieldset>
<input type="search" name="keyword" id="keyword" />
<input type="submit" value="Trazi"/>
</form>
and PHP code for searching:
function admin_search(){
$keyword = trim($_POST['keyword']);
$search_explode = explode(" ", $keyword);
$x = 0;
$mgs = isset($_POST['mali_oglasi']) ? 1 : "";
$jbs = isset($_POST['berza_rada']) ? 2 : "";
$nws = isset($_POST['vesti']) ? 3 : "";
$ypg = isset($_POST['zute_strane']) ? 4 : "";
if($mgs != "" || $jbs != "" || $nws != "" || $ypg != ""){$or = " OR ";}else{$or = "";}
if($jbs != "" || $nws != "" || $ypg != "" ){$or1 = " OR ";}else{$or1 = "";}
if($nws != "" || $ypg != "" ){$or2 = " OR ";}else{$or2 = "";}
if($ypg != "" ){$or3 = " OR ";}else{$or3 = "";}
$nlz = isset($_POST['nalozi']) ? "person" : "";
$dgj = isset($_POST['event']) ? "event" : "";
if($nlz != "" || $dgj != ""){$z = ", "; $or_like = " OR "; }else{$z = " "; $or_like = "";}
if($dgj != ""){$z1 = ", ";$or_like1 = " OR ";}else{$z1 = " ";$or_like1 = "";}
if($mgs != "" || $ypg != "" || $jbs != "" || $nws != ""){$gi = "global_info";}else{$gi = "";}
$sql = "SELECT * FROM ";
if($gi != ""){$sql .= " $gi $z";}
if($nlz != ""){$sql .= " $nlz $z1";}
if($dgj != ""){$sql .= " $dgj";}
$sql .= " WHERE ";
if($mgs != ""){$sql .= " global_info.info_type_id = {$mgs} $or1 ";}
if($jbs != ""){$sql .= " global_info.info_type_id = {$jbs} $or2 ";}
if($nws != ""){$sql .= " global_info.info_type_id = {$nws} $or3 ";}
if($ypg != ""){$sql .= " global_info.info_type_id = {$ypg} ";}
$sql .= " AND ";
foreach($search_explode as $each){
$x++;
if($x == 1){
if($gi != ""){$sql .= " global_info.name LIKE '%$each%' $or_like ";}
if($nlz != ""){$sql .= " $nlz.name LIKE '%$each%'$or_like1 ";}
if($dgj != ""){$sql .= " $dgj.name LIKE '%$each%' ";}
} else {
$sql .= " AND global_info.name LIKE '%$each%' ";
}
}
echo $sql;
$q = $this->db->query($sql);
echo $q->num_rows();
return $q = $q->num_rows() == 0 ? FALSE : $q->result_array();
}
Idea behind this search - I must be able to choose witch tables I want to search and the search by the keyword(s) need to work for any table choosen.
When one of the checkboxes is checked, it is working fine, but if two or more are checked, and if there is more than one keyword (for the moment I am trying just global_info table with two or more keywords), function is working fuzzy. Sometimes it does not work, or if it is working it is giving same results multiple times, or everything except the keyword. At the moment I don't quite understand why it is giving results that it is giving. How to make this work?
Try changing it to read like this:
$tables = array();
if(isset($_POST['mali_oglasi'])){
$tables['mgs'] = 1;
}
/*
repeat for the other tables
*/
/* Where you're building your WHERE clause, use this instead of the 'OR' logic */
if(!empty($tables)){
$sql .= 'global_info.info_type_id IN (' . implode(',',$tables) . ')';
}

Can't figure out duplicate entries for data in SQL field, and random cell deletion (PHP/MYSQL)

I have an attendance page which outputs a list of students in a class through the following loop:
$sql10 = "SELECT class.name, student_to_class.class_id, student_to_class.student_id
FROM
student_to_class
INNER JOIN
class
ON class.id=student_to_class.class_id
WHERE
class.name = '$classid'";
$result10 = mysql_query($sql10) or die(mysql_error());
while ($row = mysql_fetch_array($result10)) {
$student = $row['student_id'];
$classid = $row['class_id'];
$sql3 = "select * from student where id = '$student'";
$result3 = mysql_query($sql3) or die(mysql_error());
$row3 = mysql_fetch_assoc($result3);
$studentfname = $row3['first_name'];
$studentlname = $row3['last_name'];
$sql4 = "select * from student where first_name = '$studentfname' AND last_name = '$studentlname'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
$studentrfid = $row4['rfid'];
$sql5 = "select * from class where id = '$classid'";
$result5 = mysql_query($sql5) or die(mysql_error());
$row5 = mysql_fetch_assoc($result5);
$class_name = $row5['name'];
//Define the default variables assuming attendance hasn't been taken.
$david = "select * from student where rfid='$studentrfid'";
$davidresult = mysql_query($david) or die(mysql_error());
$drow = mysql_fetch_assoc($davidresult);
if (($drow['excused'] == '1') && ($drow['excuseddate'] == $date)) {
//if($drow['excuseddate'] == $date;
$excusedabsense = '<option value="Excused Absense" label="Excused Absense" selected="selected">Excused Absense</option>';
} else {
$excusedabsense = '';
}
$presentpunctual = '<option value="Present" label="Present">Present</option>';
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
if (isset($_POST['editdate'])) {
$date = $_POST['date'];
}
$realfname = $studentfname;
$reallname = $studentlname;
$sql4 = "select * from attendance_main where StudentID = '$studentrfid' AND date = '$date' AND classID = '$class_name'";
$result4 = mysql_query($sql4) or die(mysql_error());
$row4 = mysql_fetch_assoc($result4);
if ($row4['status'] == "Present") {
$presentpunctual = '<option value="Present" label="Present" selected="selected">Present</option>';
} else {
$presentpunctual = '<option value="Present" label="Present">Present</option>';
}
if ($row4['status'] == "Tardy") {
$presenttardy = '<option value="Tardy" label="Tardy" selected="selected">Tardy</option>';
} else {
$presenttardy = '<option value="Tardy" label="Tardy">Tardy</option>';
}
if ($row4['status'] == "Absent") {
$unexcusedabsense = '<option value="Absent" label="Absent" selected="selected">Absent</option>';
} else {
$unexcusedabsense = '<option value="Absent" label="Absent">Absent</option>';
}
$b++;
echo "<tr>";
if (!isset($dateform)) {
$dateform = date('m/d/Y');
}
$date = date('m/d/Y');
echo '<td><iframe src="flag.php?&flagdate=' . $dateform . '&curdate=' . $date . '&class=' . $classid . '&flag=1&user=' . $studentrfid . '&curflag=' . $realrfid['flag'] . '&flagclass=' . $classname . '" width="50" height="30" frameborder="0" scrolling="no"> </iframe></td>';
//Yesterday
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$yesterdaysql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_yesterday = "N/A";
} else {
$tooltipresult_yesterday = $tooltiprow['status'];
}
//2 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days2sql' AND classID = '$classid'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_2days = "N/A";
} else {
$tooltipresult_2days = $tooltiprow['status'];
}
//3 days
$sql8 = "select * from attendance_main where StudentID = '$studentrfid' AND date='$days3sql' AND classID = '$class_name'";
$result8 = mysql_query($sql8) or die(mysql_error());
$tooltiprow = mysql_fetch_assoc($result8);
if (mysql_num_rows($result8) == 0) {
$tooltipresult_3days = "N/A";
} else {
$tooltipresult_3days = $tooltiprow['status'];
}
$tooltip = "<b>" . $yesterday . ":</b> " . $tooltipresult_yesterday . " - <b>" . $days2 . ":</b> " . $tooltipresult_2days . " - <b>" . $days3 . ":</b> " . $tooltipresult_3days;
echo "
<!-- Loop #" . $b . " --> <td><a href='#'";
?> onMouseover="ddrivetip('<?php
echo $tooltip;
?>')"; onMouseout="hideddrivetip()"> <?php
echo $realfname . " " . $reallname . "</a></td>";
echo '<td>
<select name="status' . $b . '">
' . $presentpunctual . '
' . $presenttardy . '
' . $excusedabsense . '
' . $unexcusedabsense . '
</select>
' . $hiddenfield . '
<input type="hidden" name="i" value="' . $b . '" />
<input type="hidden" name="studentid' . $b . '" value="' . $studentrfid . '">
<input type="hidden" name="classid" value="' . $class_name . '"></td>
<td><input type="text" name="comments' . $b . '" size="40" /></td></tr>
<!-- End Loop -->';
}
}
}
It essentially prints out student name and a drop down of statuses (if attendance was taken that day, the status will be whatever is set in the database). The date, flag, and tooltip functions are extra additions. (Date is for previous days, tooltip shows previous attendance on hover)
This data is being executed through the following loop:
if (isset($_GET['update'])) {
mysql_query("UPDATE teacher_accounts SET attendance = '1' WHERE username = '$username'") or die(mysql_error());
$error = 0;
$limit = $_GET['i'];
$starter = 0;
$num = 0;
while ($starter < $limit) {
$num++;
$statusinc = "status" . $num;
$studentinc = "studentid" . $num;
$commentsinc = "comments" . $num;
$starter++;
$studentID = $_GET[$studentinc];
$status = $_GET[$statusinc];
$comments = $_GET[$commentsinc];
$date = date("m/d/Y");
$sql = "select * from student where id = '$studentID'";
$result = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($result);
$classid = $_GET['classid'];
if (isset($_GET['dateedit'])) {
$date = $_GET['dateedit'];
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
}
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance.</h3>";
}
} else {
$count = "select * from attendance_main where StudentID = '$studentID' AND date = '$date' AND classID='$classid'";
$cresult = mysql_query($count) or die(mysql_error());
if (mysql_num_rows($cresult) > 0) {
$sql = "UPDATE attendance_main SET status='$status',comments='$comments',date='$date',classID='$classid' where StudentID = '$studentID'";
if (mysql_query($sql)) {
$return = "<h3>Successfully updated the attendance for " . $num . " students.</h3>";
}
} else {
$sql = "INSERT INTO attendance_main (StudentID,status,comments,date,classID) VALUES ('$studentID','$status','$comments','$date','$classid')";
if (mysql_query($sql)) {
$return = "<h3>Successfully inserted today's attendance for " . $num . " students.";
}
}
}
}
echo $return;
For some reason, data is sometimes not being inserted properly. For example, a teacher might submit attendance on 02/08/2011, for a specific class, and certain students might appear twice under that attendance. This shouldn't be the case according to the code, because it should first check if they exist and, if they do, update the record rather than insert.
I've also seen cases where records are randomly deleted altogether. When a teacher takes attendance, all statuses are automatically set to Present. However, when I searched records on a certain date in the database, 2 students were missing records (which isn't even possible unless its being deleted)
Anyone have any idea why this might happen? I've tried replicating it myself (by repeatedly submitting the form, refreshing the page after it's processed, etc, to no avail.)
Thank you for the help!
Your query that check if a record exists is looking for all 3. 1) $studentID, 2) $classid and 3) $classid However the UPDATE statement is just looking for $studentID.
I would suggest you create a PRIMARY KEY (or UNIQUE INDEX) on StudentID,date,classID, then use the MySql INSERT ON DUPLICATE KEY UPDATE...
INSERT INTO attendance_main (StudentID,status,comments,date,classID)
VALUES ('$studentID','$status','$comments','$date','$classid')
ON DUPLICATE KEY UPDATE
status = VALUES(status),
comments = VALUES(comments)
Don't forget to sanitize the database input by using mysql_real_escape_string for example $status = mysql_real_escape_string($_GET[$statusinc]);.

Forming a query string from multiple checkboxes

I'm trying to form a query string from multiple checkboxes that will be used to query my database.
I have the following form:
<fieldset data-role="controlgroup">
<input type="checkbox" name="wheat" id="checkbox-1a" class="custom" />
<label for="checkbox-1a">Wheat Allergy</label>
<input type="checkbox" name="yeast" id="checkbox-2a" class="custom" />
<label for="checkbox-2a">Yeast Allergy</label>
<input type="checkbox" name="sugar" id="checkbox-3a" class="custom" />
<label for="checkbox-3a">Sugar Allergy</label>
<input type="checkbox" name="dairy" id="checkbox-4a" class="custom" />
<label for="checkbox-4a">Dairy Allergy</label>
My PHP code is as follows:
if(isset($_POST['wheat']))
{
$str1 = 'wheatfree = 1';
}
if(isset($_POST['yeast']))
{
$str2 = 'yeastfree = 1';
}
if(isset($_POST['sugar']))
{
$str3 = 'sugarfree = 1';
}
if(isset($_POST['dairy']))
{
$str4 = 'dairyfree = 1';
}
$fullsearch = $str1.$str2.$str3.$str4;
$str_SQL = "SELECT * FROM recipes WHERE ".$fullsearch;
echo $str_SQL;
This is sort of doing what I require, but it's not very graceful.
For one, the sql query looks like this:
SELECT * FROM recipes WHERE sugarfree = 1dairyfree = 1
and if users choose not to select one I of course get an Undefined variable error for the str that hasn't been selected.
Not really sure how to fix this or where to go next. I'd like some logic in here that just amended the string based on what is checked on the form which then forms a nice clean SQL query I can run against my DB. But alas i'm lost :(
Help?
Further to Dave's answer:
$options = Array();
$ingredients = Array('wheat', 'yeast', 'sugar', 'dairy');
foreach ($ingredients as $i)
if (isset($_POST[$i]))
$options[] = $i . 'free = 1';
$sql = "SELECT * FROM recipes";
if (count($options))
$sql .= " WHERE " . implode(' AND ', $options);
echo $sql;
But why aren't you using the value property of checkboxes?
<input type="checkbox" name="ingredients[]" value="wheat" />
<input type="checkbox" name="ingredients[]" value="sugar" />
etc.
Then:
$options = Array();
foreach ($_POST['ingredients'] as $i)
$options[] = $i . 'free = 1'; // don't forget to escape $i somehow!
$sql = "SELECT * FROM recipes";
if (count($options))
$sql .= " WHERE " . implode(' AND ', $options);
echo $sql;
How about this:
$options = array();
if(isset($_POST['wheat']))
{
$options[] = 'wheatfree = 1';
}
if(isset($_POST['yeast']))
{
$options[] = 'yeastfree = 1';
}
if(isset($_POST['sugar']))
{
$options[] = 'sugarfree = 1';
}
if(isset($_POST['dairy']))
{
$options[] = 'dairyfree = 1';
}
$fullsearch = implode(' AND ', $options);
$str_SQL = "SELECT * FROM recipes";
if ($fullsearch <> '') {
$str_SQL .= " WHERE " . $fullsearch;
}
echo $str_SQL;

Categories