I am trying to make vote up-down system using php ,mysql and jquery. It works perfectly on front-end but, at the back-end it does not add data in the database. Any help/suggestions will be appreciated..!! Following is the code..
<span id="links-<?php echo $rec1['que_id']; ?>">
<input type="hidden" id="votes-<?php echo $rec1['que_id']; ?>" value="<?php echo $rec1['votes']; ?>">
<?php
$vote_rank = 0;
$query ="SELECT SUM(vote_rank) as vote_rank FROM cvotes WHERE que_id = '".$rec1['que_id']."' and username = '$logged_user'";
$result2 = $conn->query($query);
foreach ($result2 as $roww) {
$up = "";
$down = "";
if(!empty($roww["vote_rank"])) {
$vote_rank = $roww["vote_rank"];
if($vote_rank == -1) {
$up = "enabled";
$down = "disabled";
}
if($vote_rank == 1) {
$up = "disabled";
$down = "enabled";
}
}
?>
<input type="hidden" id="vote_rank_status-<?php echo $rec1['que_id']; ?>" value="<?php echo $vote_rank; ?>">
<span class="btn-votes">
<input type="button" title="Up" class="up" onClick="addVote(<?php echo $rec1['que_id']; ?>,'1')" <?php echo $up; ?> />
<span class="label-votes"><?php echo $rec1['votes']; ?></span>
<input type="button" title="Down" class="down" onClick="addVote(<?php echo $rec1['que_id']; ?>,'-1')" <?php echo $down; ?> />
<p id='show'></p>
</span>
function addVote(que_id,vote_rank) {
$.ajax({
data:'que_id='+que_id+'&vote_rank='+vote_rank,
url: "add_vote.php",
type: "POST",
beforeSend: function(){
$('#links-'+que_id+' .btn-votes').html("<img src='LoaderIcon.gif' />");
},
success: function(vote_rank_status){
var votes = parseInt($('#votes-'+que_id).val());
var vote_rank_status;// = parseInt($('#vote_rank_status-'+que_id).val());
switch(vote_rank) {
case "1":
votes = votes+1;
vote_rank_status = vote_rank_status+1;
break;
case "-1":
votes = votes-1;
vote_rank_status = vote_rank_status-1;
break;
}
$('#votes-'+que_id).val(votes);
$('#vote_rank_status-'+que_id).val(vote_rank_status);
var up,down;
if(vote_rank_status == 1) {
up="disabled";
down="enabled";
}
if(vote_rank_status == -1) {
up="enabled";
down="disabled";
}
var vote_button_html = '<input type="button" title="Up" class="up" onClick="addVote('+que_id+',\'1\')" '+up+' /><span class="label-votes">'+votes+'</span><input type="button" title="Down" class="down" onClick="addVote('+que_id+',\'-1\')" '+down+' />';
$('#links-'+que_id+' .btn-votes').html(vote_button_html);
}
});
}
<?php
//-----add_vote.php-----
if(!empty($que_id)) {
if(isset($_SESSION['login_user']))
{
$logged_user = $_SESSION['login_user'];
}
$que_id=$_POST["que_id"];
$vote_rank = $_POST["vote_rank"];
require_once("dbcontroller.php");
$db_handle = new DBController();
$query = "INSERT INTO cvotes (que_id,username,vote_rank) VALUES ('$que_id','$logged_user','$vote_rank')";
$result = $db_handle->insertQuery($query);
if(!empty($result)) {
$query = "SELECT SUM(vote_rank) as vote_rank FROM cvotes WHERE que_id = '$que_id' and username = '$logged_user'";
$row = $db_handle->runQuery($query);
switch($vote_rank) {
case "1":
$update_query ="UPDATE questions SET votes = votes+1 WHERE que_id='" . $que_id . "'";
break;
case "-1":
$update_query ="UPDATE questions SET votes = votes-1 WHERE que_id='" . $que_id . "'";
break;
}
$result = $db_handle->updateQuery($update_query);
print $roww["vote_rank"];
}
}
?>
Seems to that your insert query is wrong "INSERT INTO cvotes (que_id,username,vote_rank) VALUES ('$que_id','$logged_user','$vote_rank')", try to use the quotes according to the data type.. you have gave quotes for all the values, i think except username rest are integer datatypes then change the query as
"INSERT INTO cvotes (que_id,username,vote_rank) VALUES ($que_id,"'"+$logged_user+"'",$vote_rank)";
Okay,so finally issue solved..!! Had just minor errors of variables and linking..below is the code..
Added hidden input :
">
Some changes in add_vote.php :
<?php
include('../connection.php');
session_start();
if(isset($_SESSION['login_user']))
{
$logged_u = $_SESSION['login_user'];
}
if(!empty($_POST["que_id"])) {
require_once("dbcontroller.php");
$db_handle = new DBController();
$query = "INSERT INTO cvotes (username,que_id,vote_rank) VALUES ('".$logged_u."','" . $_POST["que_id"] . "','" . $_POST["vote_rank"] . "')";
$result = $db_handle->insertQuery($query);
if(!empty($result)) {
$query = "SELECT SUM(vote_rank) as vote_rank FROM cvotes WHERE que_id = '" . $_POST["que_id"] . "' and username = '".$logged_u."' ";
$row = $db_handle->runQuery($query);
switch($_POST["vote_rank"]) {
case "1":
$update_query ="UPDATE questions SET votes = votes+1 WHERE que_id='" . $_POST["que_id"] . "'";
break;
case "-1":
$update_query ="UPDATE questions SET votes = votes-1 WHERE que_id='" . $_POST["que_id"] . "'";
break;
}
$result = $db_handle->updateQuery($update_query);
print $roww["vote_rank"];
}
}
?>
Related
Updating old code to php 7.3.5 and having trouble looping through a list of categories. Result should show each category available but only 1 is showing up. There are no errors.
Sample Data:
States are: South Carolina, Georgia, Illinois
Categories are: Commercial Community Development, Education, Infrastructure, Local Government, Public Buildings, Public Safety, Residential State, and Federal
Current output is:
<div style="display:inline;"> <img src="/gov_images/Residential.jpg" alt="news category Residential" border="0"> </div>
This is the old code that worked great on PHP 5...
<?php
$sql = 'SELECT * FROM state_to_category WHERE state_id="' . $state . '"';
// echo "<br> <br>Line #: " . __LINE__ . " - Select SQL: *$sql*<br>\n";
$sql_query = mysql_query($sql, $sql_link) or die("Could not select record: " . mysql_error() );
// $row_ct = mysql_num_rows($sql_query);
$state_id_list = "";
while ($row = mysql_fetch_array($sql_query))
{
$state_id_list[] = $row['cat_id'];
// echo "<br> state: " . $row['state_id'] . " cat: " . $row['cat_id'];
}
$sql = 'SELECT *
FROM news_category
WHERE type="base"
ORDER BY category';
// echo "<br> <br>Line #: " . __LINE__ . " - Select SQL: *$sql*<br>\n";
$sql_query = mysql_query($sql, $sql_link) or die("Could not select record: " . mysql_error() );
// $row_ct = mysql_num_rows($sql_query);
$category_name = "";
while ($row = mysql_fetch_array($sql_query))
{
if ($category_id == $row['id'])
{
$category_name = $row['category'];
}
$state_found = "N";
if (is_array($state_id_list))
{
foreach($state_id_list as $value)
{
if ($value == $row['id'])
{
$state_found = "Y";
}
}
}
if ($state_found == "Y")
{
?>
<div style="display:inline;">
<img src="<? echo $row['icon_small'];?>" alt="news category <? echo $row['category'];?>" border="0" />
</div>
<?php
}
}
?>
This is the same code that I'm working on updating to run on 7.3.5...
<?php
$sql = 'SELECT * FROM state_to_category WHERE state_id="' . $state . '"';
$sql_query = mysqli_query($sql_link, $sql) or die("Could not select record: " . mysqli_error() );
$state_id_list = "";
while ($row = mysqli_fetch_array($sql_query))
{
$state_id_list = array();
$state_id_list[] = $row['cat_id'];
}
$sql = 'SELECT *
FROM news_category
WHERE type="base"
ORDER BY category';
$sql_query = mysqli_query($sql_link, $sql) or die("Could not select record: " . mysqli_error() );
$category_name = "";
while ($row = mysqli_fetch_array($sql_query))
{
if ($category_id == $row['id'])
{
$category_name = $row['category'];
}
$state_found = "N";
if (is_array($state_id_list))
{
foreach($state_id_list as $value)
{
if ($value == $row['id'])
{
$state_found = "Y";
}
}
}
if ($state_found == "Y")
{
?>
<div style="display:inline;">
<img src="<? echo $row['icon_small'];?>" alt="news category <? echo $row['category'];?>" border="0" />
</div>
<?php
}
}
?>
Any help is greatly appreciated!
I had the same problem updating at the same time the sql injection came up so i updated all my querys and loops and worked great
using PDO conector:
$mysql_pdo = new PDO("mysql:host=localhost;dbname=DATABASE","user", "passwd");
$query_categories = 'SELECT *
FROM news_category
WHERE type=:type
ORDER BY category';
$Q_categories = $mysql_pdo->prepare($query_categories);
$Q_categories->bindParam(':type',"base");
$Q_categories->execute();
while($row = $Q_categories->fetch())
{
if ($category_id == $row['id']) **<--maybe you lost $category_id on the update?**
{
$category_name = $row['category'];
}
$state_found = "N";
if (is_array($state_id_list))
{
foreach($state_id_list as $value)
{
if ($value == $row['id'])
{
$state_found = "Y";
}
}
}
if ($state_found == "Y")
{
?>
<div style="display:inline;">
<img src="<? echo $row['icon_small'];?>" alt="news category <? echo $row['category'];?>" border="0" />
</div>
<?php
}
}
in this way you prepare your code for further updates and secure it against sql inyection mysqli_query is depecrated maybe thats why you are getting erratic behavior
So the issue i'm having is that when I click the post button nothing happens and a comment doesn't display or go to my database. I have checked for spelling mistakes and believe I have got them all.
This is my HTML form called community.php
<div class="page-container">
<?php
get_total();
require_once 'check_com.php';
?>
<form action="" method="post" class="main">
<label>Enter a Brief Comment</label>
<textarea class="form-text" name="comment" id="comment"></textarea>
<br />
<input type="submit" class="form-submit" name="new_comment" value="Post">
</form>
<?php get_comments(); ?>
</div>
This is my js script called global.js
$(document). ready(function() {
$(".child-comments").hide();
$("a#children").click(function() {
var section = $(this).attr("name");
$("#C-" + section).toggle();
});
$(".form-submit").click(function() {
var commentBox= $("#comment");
var commentCheck= commentBox.val();
if(commentCheck == '' || commentCheck == NULL) {
commentBox.addClass("form-text-error");
return false;
}
});
$(".form-reply").click(function() {
var replyBox= $("#new-reply);
var replyCheck= replyBox.val();
if(replyCheck == '' || replyCheck == NULL) {
replyBox.addClass("form-text-error");
return false;
}
});
$("a#reply").one("click", function() {
var comCode = $(this).attr("name");
var parent = $(this).parent();
parent.append("<br / ><form actions='' method='post'><textarea class='form-text' name='new-reply' id='new-reply' required='required'></textarea><input type='hidden' name='code' value='"+comCode"' /><input type='submit' class='form-submit' id='form-reply' name='new_reply' value='Reply'/></form>")
});
})
Check_com.php file
<?php
// new comment fucntion
if(isset($_POST['new_comment'])) {
$new_com_name = $_SESSION['user'];
$new_com_text = $_POST['comment'];
$new_com_date = date('Y-m-d H:i:s');
$new_com_code = generateRandomString();
if(isset($new_com_text)) {
mysqli_query($conn, "INSERT INTO `parents` (`user`, `text`, `date`, `code`) VALUES ('$new_com_name', '$new_com_text', '$new_com_date', '$new_com_code')");
}
header ("Location: ");
}
// new reply
if(isset($_POST['new_reply'])) {
$new_reply_name = $_SESSION['user'];
$new_reply_text = $_POST['new-reply'];
$new_reply_date = date('Y-m-d H:i:s');
$new_reply_code = $_POST('code');
if(isset($new_reply_text)) {
mysqli_query($conn, "INSERT INTO `children` (`user`, `text`, `date`, `par_code`) VALUES ('$new_reply_name', '$new_reply_text', '$new_reply_date', '$new_reply_code')");
}
header ("Location: ");
}
?>
Functions.php File
<?php
session_start();
$_SESSION['user'] = 'Admin';
function get_total() {
require 'includes/dbh.inc.php';
$result = mysqli_query($conn, "SELECT * FROM `parents` ORDER BY `date` DESC");
$row_cnt = mysqli_num_rows($result);
echo '<h1>All Comments ('.$row_cnt.')</h1';
}
function get_comments() {
require 'includes/dbh.inc.php';
$result = mysqli_query($conn, "SELECT * FROM `parents` ORDER BY `date` DESC");
$row_cnt = mysqli_num_rows($result);
foreach($result as $item) {
$date = new dateTime($item['date']);
$date = date_format($date, 'M j, Y | H:i:s');
$user = $item['user'];
$comment = $item['text'];
$par_code = $item['code'];
echo '<div class="comment" id="'.$par_code.'">'
.'<p class="user">'.$user.'</p> '
.'<p class="time">'.$date.'</p>'
.'<p class="comment-text">'.$comment.'</p>'
.'<a class="link-reply" id="reply" name="'.$par_code.'">Reply</a>';
$chi_result = mysqli_query($conn, "SELECT * FROM `children` WHERE `par_code`='$par_code' ORDER BY `date` DESC");
$chi_cnt = mysqli_num_rows($chi_result);
if($chi_cnt == 0){
}else {
echo '<a class="link-reply" id="children" name="'.$par_code.'"><span id="tog_text">replies</span> ('.$chi_cnt.')</a>'
.'<div class="child-comments" id="C-'.$par_code.'">';
foreach ($chi_result as $com) {
$chi_date = new dateTime($com['date']);
$chi_date = date_format($chi_date, 'M j, Y | H:i:s');
$chi_user = $com['user'];
$chi_com = $com['text'];
$chi_par = $com['par_code'];
echo '<div class="child" id="'.$par_code.'-C">'
.'<p class="user">'.$chi_user.'</p> '
.'<p class="time">'.$chi_date.'</p>'
.'<p class="comment-text">'.$chi_com.'</p>'
.'</div>';
}
echo '</div>';
}
echo '</div>';
}
}
function generateRandomString($length = 6) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$characterLength = strlen($characters);
$randomString = '';
for($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $characterLenght - 1)];
}
return $randomString;
}
?>
Either remove action="" or change it to action="community.php"
I have 6 input fields
<input type="text" class="form-control filter-width namef" placeholder="Product Name">
<input type="text" class="form-control filter-width brandf" placeholder="Brand Name">
<input type="text" class="form-control filter-width catf" placeholder="Category">
<input type="text" class="form-control filter-width sizef" placeholder="Size">
<input type="text" class="form-control filter-width pricef" placeholder="Price">
<input type="text" class="form-control filter-width invf" placeholder="Inventory">
each field is used to filter data. if all fields are filled then it is easy to querying data but I actually don't know using how many fields a user is going to filter. He may filter the data using only name, name and brand name, name and brand name and size, price and inventory. putting conditions using if, elseif and thinking of all possible combinations would be difficult and lengthy task.
is there any way to achieve this.
Here's my PHP:
$name = $_REQUEST['name'];
$brand = $_REQUEST['brand'];
$cat = $_REQUEST['cat'];
$size = $_REQUEST['size'];
$price = $_REQUEST['price'];
$inv = $_REQUEST['inv'];
if(!empty($name) AND !empty($brand) AND !empty($cat) AND !empty($size) AND !empty($price) AND !empty($inv) ||){
$sql = "SELECT * FROM products WHERE pname='$name' AND brand_name ='$brand' AND ptype = '$cat' AND psize= '$size' AND sprice = '$price' AND inventory='$inv'";
}
else{
}
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$pid = $row['pid'];
$pname = $row['pname'];
$pbrand = $row['brand_name'];
$pcat = $row['ptype'];
$pinv = $row['inventory'];
$pprice = $row['sprice'];
$psize = $row['psize']; ?>
<tr id="<?php echo $pid; ?>" class="prod-details"><?php echo "<td>".$pid."</td><td>".$pname."</td><td>".$pbrand."</td>"."<td>".$pcat."</td>"."<td>".$psize."</td>"."<td>".$pprice."</td>"."<td>".$pinv."</td>"; ?></tr> <?php
}
}
Now I don't know what conditions to think and write inside else body
Try following code
<?php
$sql = "SELECT * FROM products WHERE 1=1 AND ";
foreach ($_REQUEST as $key => $value) {
$columnName = '';
switch ($key) {
case 'name':
$columnName = 'pname';
break;
case 'brand':
$columnName = 'brand_name';
break;
case 'cat':
$columnName = 'ptype';
break;
case 'cat':
$columnName = 'psize';
break;
case 'size':
$columnName = 'ptype';
break;
case 'inv':
$columnName = 'inventory';
break;
}
if (!empty($columnName) && !empty($value)) {
$sql .= " $columnName='$value' AND";
}
}
$sql = rtrim($sql, 'AND');
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$pid = $row['pid'];
$pname = $row['pname'];
$pbrand = $row['brand_name'];
$pcat = $row['ptype'];
$pinv = $row['inventory'];
$pprice = $row['sprice'];
$psize = $row['psize']; ?>
<tr id="<?php echo $pid; ?>" class="prod-details"><?php echo "<td>".$pid."</td><td>".$pname."</td><td>".$pbrand."</td>"."<td>".$pcat."</td>"."<td>".$psize."</td>"."<td>".$pprice."</td>"."<td>".$pinv."</td>"; ?></tr> <?php
}
}
Also please correct me if I am wrong.
You could aggregate your query string. You may try the following-
$query = "";
if (!empty($name)) {
$query += " AND pname='$name'";
}
if (!empty($brand)) {
$query += " AND brand_name ='$brand'";
}
if (!empty($cat)) {
$query += " AND ptype = '$cat'";
}
if (!empty($size)) {
$query += " AND psize= '$size'";
}
if (!empty($price)) {
$query += " AND sprice = '$price'";
}
if (!empty($inv)) {
$query += " AND inventory='$inv'";
}
if($query != ""){
$sql = "SELECT * FROM products WHERE 1=1" . $query;
}else{
}
I have a simple upload script that has some validation on the form. The idea behind the upload form is to upload 2 images, one a thumbnail and one a larger image. Both need to be the correct dimensions and require an image to be selected in order for the form to validate and successfully upload the images.
However, I have been tasked to remove the first upload part, the thumbnail. We now only need the larger image. Though I'm unsure how to remove the validation part of the process. I have tried to remove the input field from the HTML, but obviously the upload script sees this as not upload the first image and throws an error.
Anyway the files:
Upload.php
<?php
// Edit upload location here
$thumb_destination_path = "../storyslide_thumbs/";
$large_destination_path = "../storyslide_large/";
$type = $_POST['type'];
if (isset($_POST['ID'])) {
$ID = $_POST['ID'];
}
$caption = mysql_real_escape_string($_POST['caption']);
$caption2 = mysql_real_escape_string($_POST['caption2']);
if ($type == "article" || $type == "editarticle") {
$sql="select a.title, a.category, c.title as cattitle, s.section as stitle, c.type from article a, category c, section s WHERE c.catID=a.category AND c.sectionid=s.sectionid AND a.articleID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
$stitle = html_entity_decode($stitle);
$stitle = punct_remove($stitle);
$linktitle = html_entity_decode($title);
$linktitle = punct_remove($linktitle);
$cattitle = html_entity_decode($cattitle);
$cattitle = punct_remove($cattitle);
if ($category=='43') {
$link = "/fans/obituaries/$ID-$linktitle..html";
} else {
if ($type=="Blog") {
$ID = "b$ID";
$cattitle = $cattitle . "-" . $category;
} else {
$cattitle = $category . "-" . $cattitle;
}
$link = "/$stitle/$cattitle/$ID-$linktitle.html";
}
} elseif ($type == "player") {
$sql = "SELECT name FROM player WHERE playerID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
$name = html_entity_decode($name);
$name = punct_remove($name);
$link = "/players/squad/$ID-$name.html";
} elseif ($type == "match") {
$sql="select r.versus, r.venue, s.year FROM regmatch r, season s WHERE r.matchID='$ID' AND r.season=s.seasonID";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
if ($venue=='Home') {
$teams = "Stanlow V $versus";
$teams2 = "Stanlow_vs_" . str_replace(" ", "_", strtolower($versus));
}
else {
$teams = "$versus V Stanlow";
$teams2 = str_replace(" ", "_", strtolower($versus)) . "_vs_Stanlow";
}
$year = str_replace("/", "-", $year);
$sql="select count(*) as num3 FROM loungeimages WHERE matchID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
if ($_POST['p']=="ao") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/awayteam.html";
} elseif ($_POST['p']=="bb") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/bookiekiller.html";
} elseif ($_POST['p']=="tn") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/teamnews.html";
} elseif ($_POST['p']=="s") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/scores.html";
} elseif ($_POST['p']=="l") {
if ($num3>0) {
$sql="select MIN(imgID) as minumumimage FROM loungeimages WHERE matchID='$ID' GROUP BY matchID";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/lounge/$minumumimage.html";
}
else {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/lounge.html";
}
} elseif ($_POST['p']=="fv") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/fansviews.html";
} elseif ($_POST['p']=="fr") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/fansmatchreport.html";
} elseif ($_POST['p']=="ob") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/offtheball.html";
} elseif ($_POST['p']=="mq") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/matchquotes.html";
} elseif ($_POST['p']=="mr") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/matchreport.html";
}
}
elseif ($type == "match2") {
$sql="select r.versus, r.venue FROM regmatch2 r WHERE r.matchID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
if ($venue=='Home') {
$teams = "Stanlow V $versus";
$teams2 = "Stanlow_vs_" . str_replace(" ", "_", strtolower($versus));
}
else {
$teams = "$versus V Stanlow";
$teams2 = str_replace(" ", "_", strtolower($versus)) . "_vs_Stanlow";
}
if ($_POST['p']=="ao") {
$link = "/match/perfectseason/$ID-$teams2/aboutoppo.html";
}
elseif ($_POST['p']=="bb") {
$link = "/match/perfectseason/$ID-$teams2/de_ja_lards_best_bet.html";
}
elseif ($_POST['p']=="tn") {
$link = "/match/perfectseason/$ID-$teams2/teamnews.html";
}
elseif ($_POST['p']=="mr") {
$link = "/match/perfectseason/$ID-$teams2/matchreport.html";
}
elseif ($_POST['p']=="rank") {
$link = "/match/perfectseason/$ID-$teams2/andys_old_rankin.html";
}
}
elseif ($type == "event") {
$link = "/fans/diary.html";
} elseif ($type == "picsubcat") {
$sql = "SELECT s.title as stitle, c.catID, c.title as ctitle, MIN(p.imgID) as imgID, se.section FROM picturesubcategory s, category c, picturetable p, section se WHERE c.sectionid=se.sectionid AND s.piccatID='$ID' AND s.catID=c.catID AND p.piccatID=s.piccatID";
$result = mysql_query($sql) or die ("<script language='javascript'>alert('" . $sql . "');</script>");
$row = mysql_fetch_array($result);
extract($row);
$ctitle = html_entity_decode($ctitle);
$ctitle = punct_remove($ctitle);
$stitle = html_entity_decode($stitle);
$stitle = punct_remove($stitle);
$section = strtolower($section);
$link = "/$section/$catID-$ctitle/$stitle/$imgID.html";
} elseif ($type == "paypal") {
$sql = "SELECT name FROM paypalitems WHERE itemID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
$name = str_replace(" ", "_", $name);
$name = urlencode($name);
$link = "/products/" . $ID . "-" . $name . ".html";
} elseif ($type == "lookalike") {
$link = "/funnies/lookalikes/1.html";
} elseif ($type == "wallpaper") {
$link = "/gear/wallpapers/1.html";
}
$result = 0;
$time = time();
while(file_exists($time.'-'.$_FILES['myfile']['name']))
{
$time++;
}
while (file_exists($time.'-'.$_FILES['myfile2']['name']))
{
$time++;
}
$thumb_target_path = $thumb_destination_path . $time.'-'.$_FILES['myfile']['name'];
$large_target_path = $large_destination_path . $time.'-'.$_FILES['myfile2']['name'];
$filename = $time.'-'.$_FILES['myfile']['name'];
$filename2 = $time.'-'.$_FILES['myfile2']['name'];
if ((!isset($_FILES['myfile']['tmp_name']) || $_FILES['myfile']['tmp_name'] == "") || (!isset($_FILES['myfile2']['tmp_name']) || $_FILES['myfile2']['tmp_name'] == "")) {
$result = 3;
} else {
if (is_uploaded_file($_FILES['myfile']['tmp_name']) && is_uploaded_file($_FILES['myfile2']['tmp_name'])) {
if (getimagesize($_FILES['myfile']['tmp_name']) && getimagesize($_FILES['myfile2']['tmp_name'])) {
if ((move_uploaded_file($_FILES['myfile']['tmp_name'], $thumb_target_path)) && (move_uploaded_file($_FILES['myfile2']['tmp_name'], $large_target_path))) {
$result = 1;
$image_dim = getimagesize($thumb_target_path);
$image_dim2 = getimagesize($large_target_path);
if (($image_dim[0] != 75 || $image_dim[1] != 100) || ($image_dim2[0] != 230 || $image_dim2[1] != 199)) {
$result = 4;
unlink($thumb_target_path);
unlink($large_target_path);
} else {
if (isset($_POST['f'])) {
$publishingdate = $_POST['date'];
$sql2 = "INSERT INTO storyslide_future (thumb, large, thumbcaption, largecaption, link, publishingdate) VALUES ('$filename', '$filename2', '$caption', '$caption2', '$link', '$publishingdate')";
$res2 = mysql_query($sql2) or die ('<script language="javascript" type="text/javascript">alert("Error! bad insert statement");</script>');
} else {
$sql = "DELETE FROM storyslide WHERE thumbID='16'";
$res = mysql_query($sql) or die ("Error! bad delete statement");
$sql1 = "UPDATE storyslide SET thumbID=thumbID+1";
$res1 = mysql_query($sql1) or die ('<script language="javascript" type="text/javascript">alert("Error! bad update statement");</script>');
$sql2 = "INSERT INTO storyslide (thumbID, thumb, large, thumbcaption, largecaption, link) VALUES ('1', '$filename', '$filename2', '$caption', '$caption2', '$link')";
$res2 = mysql_query($sql2) or die ('<script language="javascript" type="text/javascript">alert("Error! bad insert statement");</script>');
}
}
}
} else {
$result = 2;
}
} else {
$result = 5;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
<?php } ?>
And now the form:
<script src='upload_handler.js' language="javascript" type="text/javascript"></script>
</head>
<body>
<div id='wrapper'> <!-- start wrapper -->
<?php include("top.php"); ?>
<div id='pagetitle'> <!-- start pagetitle -->
<div id='pageimage'><img src='adminimages/note.jpg'/></div>
<div id='title'>Add to Thumbnails</div>
</div> <!-- end pagetitle -->
<div id='admincontrols'> <!-- start admincontrols -->
<center>
<div id='container' style='margin:0 0 0 240px;'>
<div id="content">
<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onSubmit='startUpload();'>
<input type='hidden' name='type' value='<?php echo $type; ?>' />
<?php
if (isset($_GET['ID'])) {
?>
<input type='hidden' name='ID' value='<?php echo $ID; ?>' />
<?php
}
?>
<?php
if (isset($_GET['p'])) {
?>
<input type='hidden' name='p' value='<?php echo $_GET['p']; ?>' />
<?php
}
?>
<?php
if (isset($_GET['f'])) {
?>
<input type='hidden' name='f' value='<?php echo $_GET['f']; ?>' />
<input type='hidden' name='date' value='<?php echo $_GET['date']; ?>' />
<?php
}
?>
<p id="f1_upload_process">Loading...<br/><img src="images/loader.gif" width="200" height="20" /><br/></p>
<div id='f1_upload_form'>
<div id='thumbnail_title' style='font-family:georgia;'>Thumbnail (This Image must be 75px in width and 100px in height):</div>
<div class='input_container'>
<div class='label_image'>File:</div>
<div class='input_image'><input name='myfile' type='file' size='70' class='inputbox'/></div>
</div>
<div class='input_container'>
<div class='label_image'>Caption:</div>
<div class='input_image'><input name='caption' type='text' maxlength='30' class='inputbox'/></div>
</div>
<div id='largerimage_title' style='font-family:georgia;'>Main Image (Only one image required. Minimum dimensions: 230px in width and 199px):</div>
<div class='input_container'>
<div class='label_image'>File:</div>
<div class='input_image'><input name='myfile2' type='file' size='70' class='inputbox'/></div>
</div>
<div class='input_container'>
<div class='label_image'>Caption:</div>
<div class='input_image'><input name='caption2' type='text' maxlength='200' class='inputbox'/></div>
</div>
<label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>
</div>
<iframe id='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px solid #fff;'></iframe>
</form>
</div>
</div>
</center>
</div>
<div id='controlbuttons'>
<a href='storyslide_write.php?type=<?php echo $type; if (isset($_GET['ID'])) { echo "&ID=" . $ID; } if (isset($_GET['n'])) { echo '&n=c'; } if (isset($_GET['revised'])) { echo '&revised=' . $_GET['revised']; } if (isset($_GET['c'])) { echo '&c=' . $_GET['c']; } ?>' id='savebutton' style='visibility:hidden;'><img src='adminimages/save.jpg' alt='Done' border='0' /></a>
<a href='admin.php'><img src='adminimages/home.jpg' border='0' alt='Main Menu'/></a></div>
</div> <!-- end wrapper -->
</body>
</html>
<?php } ?>
The input that I want to remove so we only have 1 image upload input is:
<input name='myfile' type='file' size='70' class='inputbox'/>
The validation needs to be removed from the first file in order to do this successfully.
I had a few stabs at this myself and noticed that the input field was being referenced in upload.php by the name of the input "myfile", so I searched the upload.php for anhything relating to this input name I found the following and tried to remove:
while(file_exists($time.'-'.$_FILES['myfile']['name']))
{
$time++;
}
$thumb_target_path = $thumb_destination_path . $time.'-'.$_FILES['myfile']['name'];
$filename = $time.'-'.$_FILES['myfile']['name'];
To no avail however...
Any pointers would be greatly appreciated :)
Try with the following code, it removes $_FILES['myfile'] from everywhere, including if statements, SQL queries, etc.:
Upload.php
// Edit upload location here
$thumb_destination_path = "../storyslide_thumbs/";
$large_destination_path = "../storyslide_large/";
$type = $_POST['type'];
if (isset($_POST['ID'])) {
$ID = (int) $_POST['ID'];
}
$caption = mysql_real_escape_string($_POST['caption']);
$caption2 = mysql_real_escape_string($_POST['caption2']);
if ($type == "article" || $type == "editarticle") {
$sql="select a.title, a.category, c.title as cattitle, s.section as stitle, c.type from article a, category c, section s WHERE c.catID=a.category AND c.sectionid=s.sectionid AND a.articleID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
$stitle = html_entity_decode($stitle);
$stitle = punct_remove($stitle);
$linktitle = html_entity_decode($title);
$linktitle = punct_remove($linktitle);
$cattitle = html_entity_decode($cattitle);
$cattitle = punct_remove($cattitle);
if ($category=='43') {
$link = "/fans/obituaries/$ID-$linktitle..html";
} else {
if ($type=="Blog") {
$ID = "b$ID";
$cattitle = $cattitle . "-" . $category;
} else {
$cattitle = $category . "-" . $cattitle;
}
$link = "/$stitle/$cattitle/$ID-$linktitle.html";
}
} elseif ($type == "player") {
$sql = "SELECT name FROM player WHERE playerID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
$name = html_entity_decode($name);
$name = punct_remove($name);
$link = "/players/squad/$ID-$name.html";
} elseif ($type == "match") {
$sql="select r.versus, r.venue, s.year FROM regmatch r, season s WHERE r.matchID='$ID' AND r.season=s.seasonID";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
if ($venue=='Home') {
$teams = "Stanlow V $versus";
$teams2 = "Stanlow_vs_" . str_replace(" ", "_", strtolower($versus));
}
else {
$teams = "$versus V Stanlow";
$teams2 = str_replace(" ", "_", strtolower($versus)) . "_vs_Stanlow";
}
$year = str_replace("/", "-", $year);
$sql="select count(*) as num3 FROM loungeimages WHERE matchID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
if ($_POST['p']=="ao") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/awayteam.html";
} elseif ($_POST['p']=="bb") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/bookiekiller.html";
} elseif ($_POST['p']=="tn") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/teamnews.html";
} elseif ($_POST['p']=="s") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/scores.html";
} elseif ($_POST['p']=="l") {
if ($num3>0) {
$sql="select MIN(imgID) as minumumimage FROM loungeimages WHERE matchID='$ID' GROUP BY matchID";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/lounge/$minumumimage.html";
}
else {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/lounge.html";
}
} elseif ($_POST['p']=="fv") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/fansviews.html";
} elseif ($_POST['p']=="fr") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/fansmatchreport.html";
} elseif ($_POST['p']=="ob") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/offtheball.html";
} elseif ($_POST['p']=="mq") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/matchquotes.html";
} elseif ($_POST['p']=="mr") {
$link = "/match/$year/$ID-$teams2/" . strtolower($venue) . "/matchreport.html";
}
}
elseif ($type == "match2") {
$sql="select r.versus, r.venue FROM regmatch2 r WHERE r.matchID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
if ($venue=='Home') {
$teams = "Stanlow V $versus";
$teams2 = "Stanlow_vs_" . str_replace(" ", "_", strtolower($versus));
}
else {
$teams = "$versus V Stanlow";
$teams2 = str_replace(" ", "_", strtolower($versus)) . "_vs_Stanlow";
}
if ($_POST['p']=="ao") {
$link = "/match/perfectseason/$ID-$teams2/aboutoppo.html";
}
elseif ($_POST['p']=="bb") {
$link = "/match/perfectseason/$ID-$teams2/de_ja_lards_best_bet.html";
}
elseif ($_POST['p']=="tn") {
$link = "/match/perfectseason/$ID-$teams2/teamnews.html";
}
elseif ($_POST['p']=="mr") {
$link = "/match/perfectseason/$ID-$teams2/matchreport.html";
}
elseif ($_POST['p']=="rank") {
$link = "/match/perfectseason/$ID-$teams2/andys_old_rankin.html";
}
}
elseif ($type == "event") {
$link = "/fans/diary.html";
} elseif ($type == "picsubcat") {
$sql = "SELECT s.title as stitle, c.catID, c.title as ctitle, MIN(p.imgID) as imgID, se.section FROM picturesubcategory s, category c, picturetable p, section se WHERE c.sectionid=se.sectionid AND s.piccatID='$ID' AND s.catID=c.catID AND p.piccatID=s.piccatID";
$result = mysql_query($sql) or die ("<script language='javascript'>alert('" . $sql . "');</script>");
$row = mysql_fetch_array($result);
extract($row);
$ctitle = html_entity_decode($ctitle);
$ctitle = punct_remove($ctitle);
$stitle = html_entity_decode($stitle);
$stitle = punct_remove($stitle);
$section = strtolower($section);
$link = "/$section/$catID-$ctitle/$stitle/$imgID.html";
} elseif ($type == "paypal") {
$sql = "SELECT name FROM paypalitems WHERE itemID='$ID'";
$result = mysql_query($sql) or die ("Error! bad select statement");
$row = mysql_fetch_array($result);
extract($row);
$name = str_replace(" ", "_", $name);
$name = urlencode($name);
$link = "/products/" . $ID . "-" . $name . ".html";
} elseif ($type == "lookalike") {
$link = "/funnies/lookalikes/1.html";
} elseif ($type == "wallpaper") {
$link = "/gear/wallpapers/1.html";
}
$result = 0;
$time = time();
while (file_exists($time.'-'.$_FILES['myfile2']['name']))
{
$time++;
}
$large_target_path = $large_destination_path . $time.'-'.$_FILES['myfile2']['name'];
$filename = '';
$filename2 = $time.'-'.$_FILES['myfile2']['name'];
if ((!isset($_FILES['myfile2']['tmp_name']) || $_FILES['myfile2']['tmp_name'] == "")) {
$result = 3;
} else {
if (is_uploaded_file($_FILES['myfile2']['tmp_name'])) {
if (getimagesize($_FILES['myfile2']['tmp_name'])) {
if (((move_uploaded_file($_FILES['myfile2']['tmp_name'], $large_target_path))) {
$result = 1;
$image_dim2 = getimagesize($large_target_path);
if (($image_dim2[0] != 230 || $image_dim2[1] != 199)) {
$result = 4;
unlink($large_target_path);
} else {
if (isset($_POST['f'])) {
$publishingdate = $_POST['date'];
$sql2 = "INSERT INTO storyslide_future (thumb, large, thumbcaption, largecaption, link, publishingdate) VALUES ('$filename', '$filename2', '$caption', '$caption2', '$link', '$publishingdate')";
$res2 = mysql_query($sql2) or die ('<script language="javascript" type="text/javascript">alert("Error! bad insert statement");</script>');
} else {
$sql = "DELETE FROM storyslide WHERE thumbID='16'";
$res = mysql_query($sql) or die ("Error! bad delete statement");
$sql1 = "UPDATE storyslide SET thumbID=thumbID+1";
$res1 = mysql_query($sql1) or die ('<script language="javascript" type="text/javascript">alert("Error! bad update statement");</script>');
$sql2 = "INSERT INTO storyslide (thumbID, thumb, large, thumbcaption, largecaption, link) VALUES ('1', '$filename', '$filename2', '$caption', '$caption2', '$link')";
$res2 = mysql_query($sql2) or die ('<script language="javascript" type="text/javascript">alert("Error! bad insert statement");</script>');
}
}
}
} else {
$result = 2;
}
} else {
$result = 5;
}
}
sleep(1);
?>
<script language="javascript" type="text/javascript">window.top.window.stopUpload(<?php echo $result; ?>);</script>
<?php } ?>
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]);.