Removing form validation on an input field - php

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 } ?>

Related

Updating PHP and query for displaying catergories from database php mysqli

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

Pagination not showing results on next page

Looking for some help please. I am using the following code to filter and show results which works fine. My problem is the results aren't passing on to the second page so the page becomes blank no errors. very new to this so all help is welcome.
$num_rec_per_page=2;
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("searchresults") or die("ERROR");
if (!isset($_POST['submit'])) exit();
$vars = array('companyname','location');
$verified = TRUE;
foreach ($vars as $v) {
if (!isset($_POST[$v]) || empty($_POST[$v])) {
$verified = FALSE;
}
}
if (!$verified) {
echo "Sorry no results found, please enter your search";
exit();
}
// isset function is also used in checking for the existence of data in $_POST
if (isset($_POST["companyname"]) && $_POST["companyname"] != '') {
$companyname = mysql_real_escape_string($_POST["companyname"]);
$companyname = " AND (companyname LIKE '%$companyname%')";
}
if (isset($_POST["location"]) && $_POST["location"] != '') {
$location = mysql_real_escape_string($_POST["location"]);
$location = " AND (location LIKE '%$location%')";
}
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
$sql = "SELECT * FROM reviewsandtips WHERE member_id > 0". $companyname . $location . "LIMIT $start_from, $num_rec_per_page";
$sql_result = mysql_query($sql) or die (mysql_error());
// now echo the code for the table heading
if (mysql_num_rows($sql_result)>0) {
while ($row = mysql_fetch_assoc($sql_result)) {
}
$sql = "SELECT * FROM reviewsandtips WHERE member_id > 0". $companyname . $location;
$sql_result = mysql_query($sql); //run the query
$total_records = mysql_num_rows($sql_result); //count number of records
$total_pages = ceil($total_records / $num_rec_per_page);
echo "<a href='codetest.php?page=1'>".'|<'."</a> "; // Goto 1st page
for ($i=1; $i<=$total_pages; $i++) {
echo "<a href='codetest.php?page=".$i."'>".$i."</a> ";
}
echo "<a href='codetest.php?page=$total_pages'>".'>|'."</a> "; // Goto last page
} else {
echo '<tr><td colspan="5">No results found.</td></tr>';
}

Vote up-down using Mysql , Jquery and Php

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"];
}
}
?>

PHP - sort/order an array by timestamp

Why I am getting 0 instead values from the database? What I am doing wrong if I give $_POST['dataType'] === 'start'. I never call a multiple DB select request. What I am doing wrong?
UPDATED:
if(isset($_POST['dataType'])){
switch ($_POST['dataType']) {
case 'start':
$data_type = 'pictures, videos, audio, documents';
break;
case 'picture':
$data_type = 'pictures';
break;
case 'video':
$data_type = 'videos';
break;
case 'audio':
$data_type = 'audio';
break;
case 'document':
$data_type = 'documents';
break;
default:
$data_type = '';
}
if (!empty($data_type)) {
$userId = mysqli_real_escape_string($connect, $_SESSION['userId']);
if ($_POST['dataType'] !== 'start')
$sql = "SELECT * FROM " . $data_type . " WHERE user_id = " . $userId;
else {
$sql_picture = "SELECT * FROM pictures WHERE user_id = " . $userId . " ORDER BY upload_time";
$sql_videos = "SELECT * FROM videos WHERE user_id = " . $userId . " ORDER BY upload_time";
$sql_audio = "SELECT * FROM audio WHERE user_id = " . $userId . " ORDER BY upload_time";
$sql_documents = "SELECT * FROM documents WHERE user_id = " . $userId . " ORDER BY upload_time";
}
// Check connection
if ($connect->connect_error) {
mysqli_close($connect);
echo 1;
}
else {
if ($_POST['dataType'] !== 'start'){
$result = $connect->query($sql);
if ($result->num_rows > 0) {
$indexOfSuggests = 0;
$data = array();
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$user_id = $row['user_id'];
$name = $row['name'];
$public = $row['public'];
$link = $row['link'];
$upload_time = $row['upload_time'];
$data[$indexOfSuggests] = array($id, $user_id, $name, $public, $link, $upload_time);
$indexOfSuggests++;
}
$result->free();
echo json_encode($data);
}
else {
echo 0; // keine ergebnisse
}
}
else {
$indexOfSuggests = 0;
$new_index;
$collectData = array();
for($i = 0; $i < 4; $i++){
$indexOfSuggests = $new_index;
if($i == 0)
$sql = $sql_picture;
else
if($i == 1)
$sql = $sql_videos;
else
if($i == 2)
$sql = $sql_audio;
else
if($i == 3)
$sql = $sql_documents;
$result = $connect->query($sql);
if ($result->num_rows > 0) {
$data = array();
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$user_id = $row['user_id'];
$name = $row['name'];
$public = $row['public'];
$link = $row['link'];
$upload_time = $row['upload_time'];
$data[$indexOfSuggests] = array($id, $user_id, $name, $public, $link, $upload_time);
array_push($collectData, $data[$indexOfSuggests]);
$indexOfSuggests++;
}
$new_index = $indexOfSuggests;
}
else {
// keine ergebnisse
}
}
echo json_encode($collectData);
}
}
}
else {
header("Location: http://google.com");
}
}
So i got it but in a really uncool way. So the last thing I have to do is to order the array values by date.
here is new fix :)
<?php
if (isset($_POST['dataType'])) {
switch ($_POST['dataType']) {
case 'start':
$data_type = 'pictures,videos,audio,documents';
break;
case 'picture':
$data_type = 'pictures';
break;
case 'videos':
$data_type = 'videos';
break;
case 'audio':
$data_type = 'audio';
break;
case 'documents':
$data_type = 'documents';
break;
default:
$data_type = '';
}
function get_list ($sql,&$list) {
// Create connection
$connect = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($connect->connect_error) {
die(1);
} else {
$result = $connect->query($sql);
while ($row = $result->fetch_assoc()) {
$id = $row['id'];
$user_id = $row['user_id'];
$name = $row['name'];
$public = $row['public'];
$link = $row['link'];
$upload_time = $row['upload_time'];
$list[] = array($id, $user_id, $name, $public, $link, $upload_time);
}
}
}
if (!empty($data_type)) {
$list = array();
$userId = mysqli_real_escape_string($_SESSION['userId']);
if ($_POST['dataType'] !== 'start') {
$sql = "SELECT * FROM " . $data_type . " WHERE user_id = " . $userId;
get_list($sql,$list);
} else {
$data_types = explode(',',$data_type);
foreach($data_types as $type) {
$sql = "SELECT * FROM " . $type . " WHERE user_id = " . $userId;
get_list($sql,$list);
}
}
if(empty($list))
die(0);
else
echo json_encode($list);
} else {
header("Location: http://google.com");
}
}
?>

MySQL Error: Duplicate 'Candidate Name'

I have created a MySQL database along with a front-end to manipulate it using PHP. However, while I can add content to the database manually, I cannot utilize my front-end. When I try to submit the data in my front-end's form fields, I receive the prompt "Duplicate Candidate Name."
The following PHP file is my general script for displaying the front-end:
<?php
if(isset($_POST['sbmtbtn']) && ($_POST['sbmtbtn'] != ""))
{
$desc = strip_tags($_POST['txtdesc']);
$date = glb_func_chkvl($_POST['txtdate']);
$first = glb_func_chkvl($_POST['txtfirst']);
$last = glb_func_chkvl($_POST['txtlast']);
$skill = glb_func_chkvl($_POST['txtskill']);
$sub1 = glb_func_chkvl($_POST['txtsub1']);
$sub2 = glb_func_chkvl($_POST['txtsub2']);
$person = glb_func_chkvl($_POST['txtperson']);
$company = glb_func_chkvl($_POST['txtcompany']);
$location = glb_func_chkvl($_POST['txtlocation']);
$complex = glb_func_chkvl($_POST['complex']);
$sts = glb_func_chkvl($_POST['lststs']);
$dt = date('Y-m-d');
$emp = $_SESSION['sesadmin'];
$sqryquestion_info
= "SELECT candi_first
FROM question_info
WHERE candi_first='$first'";
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "add"))
{
$srsquestion_info =mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
$gmsg = "<font color=red size=2>Duplicate Candidate Name . Record not saved</font>";
}
else
{
$iqryquestion_info="insert into question_info(
candi_first,candi_last,date,
skill,subtype_1,
subtype_2,person_int,
comp_name,loc_int,complex_lvl,
type_int,question_candi,q_crton,
q_crtby)
values('$first','$last','$date','$skill','$sub1','$sub2','$person','$company',
'$location','$complex','$sts','$desc','$dt','$emp')";
$irsquestion_info = mysql_query($iqryquestion_info);
if($irsquestion_info==true)
{
$gmsg = "<font color=green size=2>Record saved successfully</font>";
}
else
{
$gmsg = "<font color=red size=2>Record not saved</font>";
}
}
}
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "edit"))
{
$id = $_REQUEST['hdnedit'];
$pg = $_REQUEST['hdnpg'];
$countstart = $_REQUEST['hdncntstrt'];
$sqryquestion_info .=" and ques_id !=$id";
$srsquestion_info = mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
?>
<script>location.href="view_all_questions.php?sts=d&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";</script>
<?php
}
else
{
$uqryquestion_info="update question_info set
date ='$date',
candi_first ='$first',
candi_last ='$last',
skill ='$skill',
subtype_1 ='$sub1',
subtype_2 ='$sub2',
person_int ='$person',
comp_name ='$company',
loc_int ='$location',
complex_lel ='$complex',
type_int ='$company',
question_candi ='$desc',
q_mdfdon ='$dt',
q_mdfdby ='$emp' ";
$uqryquestion_info .= " where ques_id=$id";
$ursquestion_info = mysql_query($uqryquestion_info);
if($ursquestion_info==true)
{
?>
<script>location.href="view_all_questions.php?sts=y&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
else
{
?>
<script>location.href="view_all_questions.php?sts=n&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
}
}
/*********************************** End Editing ******************************************************/
}
?>
Here begins my "main file" for editing:
<?php
if(isset($_POST['sbmtbtn']) && ($_POST['sbmtbtn'] != ""))
{
$desc = strip_tags($_POST['txtdesc']);
$date = glb_func_chkvl($_POST['txtdate']);
$first = glb_func_chkvl($_POST['txtfirst']);
$last = glb_func_chkvl($_POST['txtlast']);
$skill = glb_func_chkvl($_POST['txtskill']);
$sub1 = glb_func_chkvl($_POST['txtsub1']);
$sub2 = glb_func_chkvl($_POST['txtsub2']);
$person = glb_func_chkvl($_POST['txtperson']);
$company = glb_func_chkvl($_POST['txtcompany']);
$location = glb_func_chkvl($_POST['txtlocation']);
$complex = glb_func_chkvl($_POST['complex']);
$sts = glb_func_chkvl($_POST['lststs']);
$dt = date('Y-m-d');
$emp = $_SESSION['sesadmin'];
$sqryquestion_info="select candi_first
from question_info
where candi_first='$first'";
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "add"))
{
$srsquestion_info =mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
$gmsg = "<font color=red size=2>Duplicate Candidate Name . Record not saved</font>";
}
else
{
$iqryquestion_info="insert into question_info(
candi_first,candi_last,date,
skill,subtype_1,
subtype_2,person_int,
comp_name,loc_int,complex_lvl,
type_int,question_candi,q_crton,
q_crtby)
values('$first','$last','$date','$skill','$sub1','$sub2','$person','$company',
'$location','$complex','$sts','$desc','$dt','$emp')";
$irsquestion_info = mysql_query($iqryquestion_info);
if($irsquestion_info==true)
{
$gmsg = "<font color=green size=2>Record saved successfully</font>";
}
else
{
$gmsg = "<font color=red size=2>Record not saved</font>";
}
}
}
if(isset($_POST['frmtyp']) && ($_POST['frmtyp'] == "edit"))
{
$id = $_REQUEST['hdnedit'];
$pg = $_REQUEST['hdnpg'];
$countstart = $_REQUEST['hdncntstrt'];
$sqryquestion_info .=" and ques_id !=$id";
$srsquestion_info = mysql_query($sqryquestion_info);
$rows = mysql_num_rows($srsquestion_info);
if($rows > 0)
{
?>
<script>location.href="view_all_questions.php?sts=d&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";</script>
<?php
}
else
{
$uqryquestion_info="update question_info set
date ='$date',
candi_first ='$first',
candi_last ='$last',
skill ='$skill',
subtype_1 ='$sub1',
subtype_2 ='$sub2',
person_int ='$person',
comp_name ='$company',
loc_int ='$location',
complex_lel ='$complex',
type_int ='$company',
question_candi ='$desc',
q_mdfdon ='$dt',
q_mdfdby ='$emp' ";
$uqryquestion_info .= " where ques_id=$id";
$ursquestion_info = mysql_query($uqryquestion_info);
if($ursquestion_info==true)
{
?>
<script>location.href="view_all_questions.php?sts=y&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
else
{
?>
<script>location.href="view_all_questions.php?sts=n&pg=<?php echo $pg;?>&countstart=<?php echo $countstart;?><?php echo $srchval;?>";
</script>
<?php
}
}
}
/*********************************** End Editing ******************************************************/
}
?>

Categories