Voting System using Radio Buttons & Checkboxes (PHP) - php

I have three PHP pages. Login, Vote, and Vote Process. In the vote page, the user may vote for the candidates. There are radio buttons and checkboxes. Here are the codes for the Vote page:
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['uname'])) {
$username = $_SESSION['uname'];
}
else {
header('Location: login_user.php');
die();
}
?>
<html>
<head>
<title>Trinity University of Asia Voting System</title>
</head>
<body>
<img src="images/tua_logo.jpg"><marquee>Practice your right to vote.</marquee><br>
<center>
Home | Results | Logout<br>
<h3>Cast Your Vote</h3>
<form action="processvoting.php" method="post">
<table cellpadding="4" border="1">
<tr>
<th>Position</th>
<th>Choice 1</th>
<th>Choice 2</th>
</tr>
<tr>
<th>President</th>
<td><input type="radio" name="president" value="pres1"> JOHN MICHAEL KALEMBE<br>College of Business Administration</td>
<td><input type="radio" name="president" value="pres2"> SUZAN JOHN<br>College of Education</td>
</tr>
<tr>
<th>Vice President</th>
<td><input type="radio" name="vice_president" value="vicepres1"> JULIUS SAMWEL<br>College of Medical Technology</td>
<td><input type="radio" name="vice_president" value="vicepres2"> JEUNICE MARIANO<br>College of Business Administration</td>
</tr>
<tr>
<th>Secretary</th>
<td><input type="radio" name="secretary" value="sec1"> ANGELO CHRSTIAN DE GUZMAN<br>College of Medical Technology</td>
<td><input type="radio" name="secretary" value="sec1"> MICHAEL SANGA<br>College of Hospitality and Tourism Management</td>
</tr>
<tr>
<th>Treasurer</th>
<td><input type="radio" name="treasurer" value="treas1"> MARIE DANIELLE THEREZE VALDEZ<br>College of Hospitality and Tourism Management</td>
<td><input type="radio" name="treasurer" value="treas1"> JEUNICE MARIANO<br>College of Business Administration</td>
</tr>
<tr>
<th>Auditor</th>
<td><input type="radio" name="auditor" value="aud1"> KOBI TSARLZ GONZALES<br>College of Computing and Information Sciences</td>
<td><input type="radio" name="auditor" value="aud1"> MARIAN ENTERO<br>College of Business Administration</td>
</tr>
<tr>
<th>Business Manager</th>
<td><input type="checkbox" name="bus_manager" value="bus1"> MICAH EDILYN TAN<br>College of Arts and Sciences</td>
<td>N/A</td>
</tr>
<tr>
<th>Public Relations Officer (PRO)</th>
<td><input type="checkbox" name="pro" value="pro1"> MARIBETH LIAMZON<br>College of Education</td>
<td>N/A</td>
</tr>
</table>
<input type="submit" name="submit" value="Cast Your Vote"> <input type="reset" value="Reset">
</form>
</center>
</body>
</html>
Once the user votes, he will be redirected to the Vote Process page and this is the code:
<?php
error_reporting(E_ALL & ~E_NOTICE);
session_start();
if (isset($_SESSION['uname'])) {
$username = $_SESSION['uname'];
}
else {
header('Location: login_user.php');
die();
}
include 'connection.php';
if(isset($_POST['submit'])) {
$president = $_POST['president'];
$vicepres = $_POST['vice_president'];
$secretary = $_POST['secretary'];
$treasurer = $_POST['treasurer'];
$auditor = $_POST['auditor'];
$businessmanager = $_POST['bus_manager'];
$pro = $_POST['pro'];
$conn = mysqli_connect('localhost', 'root', '', 'electiondb');
if (!$conn) {
die("Connecton failed: " . mysqli_connect_error());
}
$votesql = "SELECT voted FROM student_log WHERE username = '$username'";
$query = mysqli_query($conn, $votesql);
while($record = mysqli_fetch_array($query)) {
$hasvoted = $record['voted'];
}
if ($hasvoted == 0) {
if ($president == '') {
echo "You cannot leave $president blank. Please go back and try again.";;
}
elseif ($vicepres == '') {
echo "You cannot leave $vicepres blank. Please go back and try again.";
}
elseif ($secretary == '') {
echo "You cannot leave $secretary blank. Please go back and try again.";
}
elseif ($treasurer == '') {
echo "You cannot leave $treasurer blank. Please go back and try again.";
}
elseif ($auditor == '') {
echo "You cannot leave $auditor blank. Please go back and try again.";
}
elseif ($businessmanager == ''){
echo "You cannot leave $businessmanager blank. Please go back and try again.";
}
elseif ($pro == '') {
echo "You cannot leave $pro blank. Please go back and try again.";
}
else {
switch ($president) {
case 'pres1':
$votepres1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'president'";
$runpres1 = mysqli_query($conn, $votepres1);
break;
case 'pres2':
$votepres2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'president'";
$runpres2 = mysqli_query($conn, $votepres2);
break;
}
switch ($vicepres) {
case 'vicepres1':
$votevicepres1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'vice_president'";
$runvicepres1 = mysqli_query($conn, $votevicepres1);
break;
case 'vicepres2':
$votevicepres2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'vice_president'";
$runvicepres2 = mysqli_query($conn, $votevicepres2);
break;
}
switch ($secretary) {
case 'sec1':
$votesec1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'secretary'";
$runsec1 = mysqli_query($conn, $votesec1);
break;
case 'sec2':
$votesec2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'secretary'";
$runsec2 = mysqli_query($conn, $votesec1);
break;
}
switch ($treasurer) {
case 'treas1':
$votetreas1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'treasurer'";
$runtreas1 = mysqli_query($conn, $votetreas1);
break;
case 'treas2':
$votetreas2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'treasurer'";
$runtreas2 = mysqli_query($conn, $votetreas2);
break;
}
switch ($auditor) {
case 'aud1':
$voteaud1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'auditor'";
$runaud1 = mysqli_query($conn, $voteaud1);
break;
case 'aud2':
$voteaud2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'auditor'";
$runaud2 = mysqli_query($conn, $voteaud2);
break;
}
switch ($businessmanager) {
case 'bus1':
$votebus1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'business_manager'";
$runbus1 = mysqli_query($conn, $votebus1);
break;
}
switch ($pro) {
case 'pro1':
$votepro1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'pro'";
$runpro1 = mysqli_query($conn, $votepro1);
break;
}
$sqlforvoted = "UPDATE student_log SET voted = 1 WHERE username = '$username'";
$processsql = mysqli_query($conn, $sqlforvoted) or die (mysqli_error($conn));
echo "Thank you for voting. You may now logout of the system.<br><a href='logout.php'>Logout</a>";
}
}
else {
echo "You cannot vote more than once. <br><a href='logout.php'>Logout</a>";
}
}
?>
<html>
<head>
<title>Voting Process</title>
</head>
<body>
</body>
</html>
The votes do not increment but the user is deemed as 'voted' therefore the user cannot vote again once logged in. My only concern is that the votes are not counting. Is there something wrong with my codes or is my understanding of vote counts not that great? Thank you!

I think you have some typos in your HTML. Here, the options are pres1 and pres2:
<td><input type="radio" name="president" value="pres1"> ... </td>
<td><input type="radio" name="president" value="pres2"> ... </td>
but here, both options are sec1:
<td><input type="radio" name="secretary" value="sec1"> ... </td>
<td><input type="radio" name="secretary" value="sec1"> ... </td>
Regarding the database interactions, it would be better to use PDO and prepared statements - it's safer than most string concatenation schemes. Check the "related" column to the right on this page - the top question is most likely this one that explains this topic well.
Anyway, here's a different take on your submit section that simply removes all the repetition. It doesn't use PDO (I didn't add any database code) but at least there's no unfiltered user input in the final query - only predefined values:
if(isset($_POST['submit']) && !empty($_POST["submit"])) {
if($hasvoted != 0){
echo "You cannot vote more than once. <br><a href='logout.php'>Logout</a>";
exit;
}
$positions = array(
"president" => null,
"vice_president" => null,
"secretary" => null,
"treasurer" => null,
"auditor" => null,
"bus_manager" => null,
"pro" => null
);
foreach (array_keys($positions) as $position)
{
if (!isset($_POST[$position]) || empty($_POST[$position])) {
echo "All positions must be filled. Please try again.<br>";
exit;
}
else{
$choice = "";
$choice_num = substr($_POST[$position], -1);
if($choice_num == 1 || $choice_num == 2){
$choice = "choice" . $choice_num;
}
else{
echo "Error - invalid option";
exit;
}
$positions[$position] = $choice;
}
}
foreach (array_keys($positions) as $position)
{
$choice = $positions[$position];
$sql_str = "UPDATE vote_log SET " . $choice ." = " . $choice . "+1 WHERE position = '" . $position . "'";
// $sql_insert = mysqli_query($conn, $sql_str);
echo $sql_str . "<br>";
}
echo "Thank you for voting. You may now logout of the system.<br><a href='logout.php'>Logout</a>";
}

You could replace this:
switch ($president) {
case 'pres1':
$votepres1 = "UPDATE vote_log SET choice1 = choice1+1 WHERE position = 'president'";
$runpres1 = mysqli_query($conn, $votepres1);
break;
case 'pres2':
$votepres2 = "UPDATE vote_log SET choice2 = choice2+1 WHERE position = 'president'";
$runpres2 = mysqli_query($conn, $votepres2);
break;
}
With this:
// here you take the last char of $president (value 1 or 2) and concatenate it to "choice"
$choice = "choice".substr($president, -1);
$votepres = "UPDATE vote_log SET $choice = $choice + 1 WHERE position = 'president'";
$runpres = mysqli_query($conn, $votepres);
Note spacing in SQL statement.
To prevent SQL Injection you have to modify the statements where a variable is called. In this case the statements where you call $username (you should call the user ID, instead the username).
Calling the user ID you can simply check if it's an integer value before do the query as follow: if (is_int($userID)) { ...do query... } else { ...do not... }

Related

How to check each rows in PHP MySQL ?

i have three row of data mysql database and create column timeout and timein . it's VARCHAR type
row 1 :
timeout : 0830 , timein : 1030
row 2 :
timeout : 1230 , timein : 1730
row 3 :
timeout : 1800 , timein : 1900
i want the code check each row in database before display an error "Duplicate" or adding the data into database table
But the problem is, it only read first row in query. second row and third row doesn't work
<?php
$connect = mysqli_connect("localhost", "root", "", "database");
global $connect;
if(isset($_POST['Submit'])){
$timeout = $_POST['timeout'];
$timein = $_POST['timein'];
$sql = "SELECT * FROM table";
$get = mysqli_query($connect, $sql);
$run = mysqli_fetch_array($get);
$timeout_new = $run['timeout'];
$timein_new = $run['timein'];
if(($timeout >= $timeout_new) && ($timeout <= $timein_new))
{
echo "Duplicate !";
}
else
{
$add = "INSERT INTO movement (timeout, timein)
VALUES ('$timeout', '$timein')";
$addDateTime = mysqli_query($connect,$add);
echo "Time added !";
}
}
?>
<form action="dd.php" method="post">
<table>
<tr>
<td><i class="fa fa-unlock-alt"></i> </td>
<td>Time out : </td>
<td><input type ="text" name="timeout" size="30"></td>
</tr>
<tr>
<td><i class="fa fa-unlock-alt"></i> </td>
<td>Time in : </td>
<td><input type ="text" name="timein" size="30"></td>
</tr>
</table>
<p><input class="btnSuccess" type ="submit" name="Submit" value="Submit"> </p>
</form>
Thanks.
I think this line is wrong, isn't it?
if(($timeout >= $timeout_new) && ($timeout <= $timein_new))
Shouldn't it be
if(($timeout >= $timeout_new) && ($timein <= $timein_new))
You can do the control in question
if(isset($_POST['Submit'])){
$timeout = $_POST['timeout'];
$timein = $_POST['timein'];
$sql = "SELECT * FROM table WHERE timeout >= '{$_POST['timeout']}' AND timeout <= '{$_POST['timein']}'";
$get = mysqli_query($connect, $sql);
if(mysql_num_rows($get))
{
echo "Duplicate !";
}
else
{
$add = "INSERT INTO movement (timeout, timein)
VALUES ('$timeout', '$timein')";
$addDateTime = mysqli_query($connect,$add);
echo "Time added !";
}
}
foreach( $run as $row )
{
$timeout_new = $row[ 'timeout' ];
$timein_new = $row[ 'timein' ];
if( ( $timeout >= $timeout_new ) && ( $timein <= $timein_new ) )
{
echo "Duplicate !";
}
else
{
$add = "INSERT INTO movement (timeout, timein) VALUES ('$timeout', '$timein')";
$addDateTime = mysqli_query($connect,$add);
echo "Time added !";
}
}
This is not tested so I can not say for sure it will work first time but it will give you an idea of what you need to look at. You are currently only looking at the first result. You need to loop through the results and check them.

Why wont my PHP MYSQL comparison work

Im messing around, trying to see if i can make one of those clickable pet sites that were all the rage a couple years ago and i run into a problem with trying to use if, else, elseif stuff in PHP.
Heres what I have:
<?php
include_once "mysql_connect.php";
$newip = $_SERVER['REMOTE_ADDR'];
$oldip = mysql_query("SELECT lastip FROM sitefunctions WHERE name='index'");
if ($newip == $oldip) {
$message = "You were the last one to click this pet, please wait until someone else has clicked it before trying again.";
}
else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='index'");
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='index'");
$tempclicks = mysql_query("SELECT `clicks` FROM sitefunctions WHERE name='index'");
$message = "You gave this pet a click!";
};
if ($tempclicks == 150) {
mysql_query("UPDATE sitefunctions SET `level` = 2 WHERE name='index'");
$message = "Your click leveled the pet up!";
}
elseif ($tempclicks == 600) {
mysql_query("UPDATE sitefunctions SET `level` = 3 WHERE name='index'");
$message = "Your click leveled the pet up!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='index'");
while($row = mysql_fetch_array($sql)){
$clicks = $row["clicks"];
$level = $row["level"];
$name = $row["name"];
$image1 = $row["image1"];
$image2 = $row["image2"];
$image3 = $row["image3"];
};
if ($level == 1) {
$imageu = $image1;
}
elseif ($level == 2) {
$imageu = $image2;
}
elseif ($level == 3) {
$imageu = $image3;
}
?>
<html>
<head>
</head>
<body>
<p>
<?php print $oldip; ?> <br>
<?php print $newip; ?> <br>
Name: <?php print $name; ?> <br>
<img src=<?php print $imageu; ?> /> <br>
Clicks: <?php print $clicks; ?> <br>
Level: <?php print $level; ?> <br>
<?php print $message; ?>
</p>
</body>
</html>
Now the first problem i'm having is with comparing the users ip with the last ip that was on the page.
$newip = $_SERVER['REMOTE_ADDR'];
$oldip = mysql_query("SELECT lastip FROM sitefunctions WHERE name='index'");
if ($newip == $oldip) {
$message = "You were the last one to click this pet, please wait until someone else has clicked it before trying again.";
}
else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='index'");
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='index'");
$tempclicks = mysql_query("SELECT `clicks` FROM sitefunctions WHERE name='index'");
$message = "You gave this pet a click!";
};
No matter what i have tried it doesnt really compare the values. If i put a "=" it says theyre the same no matter what and if i do "==" it says theyre different even though they shouldn't be.
I dont even know where to start with this, no errors come up and i'm fairly new to PHP and MYSQL. Nothing else can be really tested until this, but im sure that the rest of the comparisons dont work either.
im using 000webhost for my site, if thats known to have problems lol
This is what my code looks like now, it works too so im done here:
<?php error_reporting(E_ALL); ini_set('display_errors', 1);
$name = $_POST['name'];
if (empty($name) == true){
$name = "index";
};
include_once "mysql_connect.php";
$newip = $_SERVER['REMOTE_ADDR'];
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$lastip = $row["lastip"];
}
if ($lastip == $newip) {
$message = "You were the last one to click this pet! You have to wait until someone else clicks it!";
} else {
mysql_query("UPDATE sitefunctions SET `clicks` = `clicks`+1 WHERE name='$name'") or die(mysql_error());
mysql_query("UPDATE sitefunctions SET `lastip` = '$newip' WHERE name='$name'") or die(mysql_error());
$message = "You clicked the pet!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$clicks = $row["clicks"];
$level = $row["level"];
}
if ($clicks > 50*$level) {
mysql_query("UPDATE sitefunctions SET `level` = `level`+1 WHERE name='$name'") or die(mysql_error());
$message = "Your click leveled up the pet!";
}
$sql = mysql_query("SELECT * FROM sitefunctions WHERE name='$name'") or die(mysql_error());
while($row = mysql_fetch_array($sql)) {
$clicks = $row["clicks"];
$level = $row["level"];
$name = $row["name"];
$image1 = $row["image1"];
$image2 = $row["image2"];
$image3 = $row["image3"];
$lastip = $row["lastip"];
};
if ($level > 35) {
$imageu = $image3;
} elseif ($level > 15) {
$imageu = $image2;
} elseif ($level > 0) {
$imageu = $image1;
};
?>
<html>
<head>
</head>
<body>
<center>
<p>
Name: <?php print $name; ?> <br>
<img src=<?php print $imageu; ?> /> <br>
Clicks: <?php print $clicks; ?> <br>
Level: <?php print $level; ?> <br>
Last User: <?php print $lastip; ?> <br>
<?php print $message; ?>
</p>
</center>
</body>
</html>

Show Online Members and Auto Logout

I am trying to display the current users and if they don't logout I would like it to time out like 20 seconds after they close the browser.
Login Code:
<?
$username = $_SESSION['membersusername'];
if(isset($username)){
mysql_query("UPDATE users SET seen=NOW() WHERE username='$username'");
}
?>
Display Online User:
<?
$check_query_all = mysql_query("SELECT * FROM users WHERE hiddenauth='no' AND seen='Y-m-d H:i:s' ORDER BY id DESC");
while ($display = mysql_fetch_array($check_query_all)) {
$allmembers = $display['name'];
$allusername = $display['username'];
$allbio = $display['bio'];
$allage = $display['age'];
$allseen = $display['seen'];
// get more stuff above if u need
$check_query_all2 = mysql_query("SELECT * FROM profiles WHERE username='$allusername'");
while ($display = mysql_fetch_array($check_query_all2)) {
$allimage = $display['image'];
$alllocation = $display['location'];
// Check Album Photo's
$check_amount = mysql_query("SELECT * FROM users WHERE hiddenauth='no' AND seen='Y-m-d H:i:s'");
$num_djs_total = mysql_num_rows($check_amount);
// CHECK IF IMAGE OR NOT
if ($allimage == "") {
$allcheckedimage = "nopic.gif"; }
// CHECK IF IMAGE OR NOT
if ($allimage != "") {
$allcheckedimage = "$allusername/$allimage"; }
// CHECK IF location OR NOT
if ($alllocation == "") {
$allcheckedlocation = "No Idea"; }
// CHECK IF location OR NOT
if ($alllocation != "") {
$allcheckedlocation = "$alllocation"; }
// CHECK IF mini bio OR NOT
if ($allbio == "") {
$allcheckedbio = "Something about your show."; }
// CHECK IF mini bio OR NOT
if ($allbio != "") {
$allcheckedbio = "$allbio"; }
$listalldjs2 .= "<table class='inlineTable' width='170' height='140' border='0'>
<tr>
<td width='20%' align='center'><a href='$domain/$allusername' /><img src='$domain/profile/$allcheckedimage' width='160' height='120' title='$allusername' /></a> </td>
</tr>
</table> ";
}}
?>
<h2>Online Users</h2>
<? echo $listalldjs2 ?>
Logout Code:
<?
$username = $_SESSION['membersusername'];
if(isset($username)){
mysql_query("UPDATE users SET seen='' WHERE username='$username'");
}
?>
I don't have iSQL or PDO as the server people won't update it yet, can anyone help me?

PHP Form for required Fields

I have a basic Form that submits data into a database and I want it to require certain fields to be submitted, so far it recongizes that the fields are empty, but it still submits regardless. I can't seem to find a solution..
Code
<?
// define variables and set to empty values
$asinErr = $qtyErr = $floorErr = $locErr;
$asin = $quantity = $floor = $location;
# this is processed when the form is submitted
# back on to this page (POST METHOD)
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST["asin"]))
{$asinErr = "ASIN is required";}
else
{$asin = addslashes($_POST["asin"]);}
if (empty($_POST["quantity"]))
{$qtyErr = "Quantity is required";}
else
{$quantity = addslashes($_POST["quantity"]);}
if (empty($_POST["floor"]))
{$floorErr = "Floor is required";}
else
{$floor = addslashes($_POST["floor"]);}
if (empty($_POST["location"]))
{$locErr = "Location is required";}
else
{$location = addslashes($_POST["location"]);}
# setup SQL statement
$sql = " INSERT INTO kiva_amnesty_log ";
$sql .= " (asin, quantity, floor, location, date) VALUES ";
$sql .= " ('$asin','$quantity','$floor','$location', now()) ";
#execute SQL statement
$result = mysql_query($sql, $cid);
# check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
print "<h3><font color=red>New Amnesty Added - View it <a href=amnesty_log_summary.php>HERE</a></font></h3>";
}
?>
<form name="fa" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<table>
<tr><td>ASIN:</td><td><input type="text" name="asin" id="asin"><span class="error">* <?php echo $asinErr;?></span></td></tr>
<tr><td>Quantity:</td><td><input type="text" name="quantity" id="quantity"><span class="error">* <?php echo $qtyErr;?></span></td></tr>
<tr><td>Floor:</td><td><select name="floor"><option value="1">Floor 1</option><option value="2">Floor 2</option></select><span class="error">* <?php echo $floorErr;?></span></td></tr>
<tr><td>KIVA Floor:</td><td><input type="radio" value="Yes" name="location">Yes<input type="radio" value="No" name="location">No</select><span class="error">* <?php echo $locErr;?></span></td></tr>
<tr><td><input type="submit" name="submit" id="submit" value="Submit Amnesty!"></td></tr>
</table>
</form>
Updated:
<?
// define variables and set to empty values
$asinErr = $qtyErr = $floorErr = $locErr = "";
$asin = $quantity = $floor = $location = "";
$lb_error = 0;
if ($_SERVER['REQUEST_METHOD'] == "POST")
{
if (empty($_POST["asin"])) {
$asinErr = "ASIN is required";
$lb_error = 1;
} else {
$asin = addslashes($_POST["asin"]);
}
if (empty($_POST["quantity"])) {
$qtyErr = "Quantity is required";
$lb_error = 1;
} else {
$quantity = addslashes($_POST["quantity"]);
}
if (empty($_POST["floor"])) {
$floorErr = "Floor is required";
$lb_error = 1;
} else {
$floor = addslashes($_POST["floor"]);
}
if (empty($_POST["location"])) {
$locErr = "Location is required";
$lb_error = 1;
} else {
$location = addslashes($_POST["location"]);
}
if($lb_error) {
continue;
}
# setup SQL statement
$sql = " INSERT INTO kiva_amnesty_log ";
$sql .= " (asin, quantity, floor, location, date) VALUES ";
$sql .= " ('$asin','$quantity','$floor','$location', curdate()) ";
#execute SQL statement
$result = mysql_query($sql, $cid);
# check for error
if (mysql_error()) { print "Database ERROR: " . mysql_error(); }
You want to check if you error variables are empty. If they are not, then break the script
ie
if(!empty($asinErr) || !empty($qtyErr) || !empty($floorErr) || !empty($locErr) ) {
break;
}
Something along these lines.
Check for the errors before you get to the point where you are writing to the database
Define at the top
$lb_error = 0;
Throughout your if/else checks for errors, if there is an error, assign the variable a 1
if (empty($_POST["asin"])) {
$asinErr = "ASIN is required";
$lb_error = 1;
} else {
$asin = addslashes($_POST["asin"]);
}
Then after you have completed all of these, do a check for errors and break if there are any
if($lb_error) {
break;
}

PHP Validating Submit

I'm working on a project where a user can click on an item. If the user clicked at it before , then when he tries to click at it again it shouldn't work or INSERT value on the DB. When I click the first item(I'm displaying the items straight from database by id) it inserts into DB and then when I click at it again it works(gives me the error code) doesn't insert into DB. All other items when I click at them , even if I click for the second, third, fourth time all of it inserts into DB. Please help guys. Thanks
<?php
session_start();
$date = date("Y-m-d H:i:s");
include("php/connect.php");
$query = "SELECT * FROM test ORDER BY `id` ASC LIMIT 3";
$result = mysql_query($query);
if (isset($_SESSION['username'])) {
$username = $_SESSION['username'];
$submit = mysql_real_escape_string($_POST["submit"]);
$tests = $_POST["test"];
// If the user submitted the form.
// Do the updating on the database.
if (!empty($submit)) {
if (count($tests) > 0) {
foreach ($tests as $test_id => $test_value) {
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
if ($match == $test_id) {
echo "You have already bet.";
} else {
switch ($test_value) {
case 1:
mysql_query("UPDATE test SET win = win + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 'X':
mysql_query("UPDATE test SET draw = draw + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
case 2:
mysql_query("UPDATE test SET lose = lose + 1 WHERE id = '$test_id'");
mysql_query("INSERT INTO match_select (user_id, match_id) VALUES ('1','$test_id')");
break;
default:
}
}
}
}
}
echo "<h2>Seria A</h2><hr/>
<br/>Welcome,".$username."! <a href='php/logout.php'><b>LogOut</b></a><br/>";
while ($row = mysql_fetch_array($result)) {
$id = $row['id'];
$home = $row['home'];
$away = $row['away'];
$win = $row['win'];
$draw = $row['draw'];
$lose = $row['lose'];
echo "<br/>",$id,") " ,$home, " - ", $away;
echo "
<form action='seria.php' method='post'>
<select name='test[$id]'>
<option value=\"\">Parashiko</option>
<option value='1'>1</option>
<option value='X'>X</option>
<option value='2'>2</option>
</select>
<input type='submit' name='submit' value='Submit'/>
<br/>
</form>
<br/>";
echo "Totali ", $sum = $win+$lose+$draw, "<br/><hr/>";
}
} else {
$error = "<div id='hello'>Duhet te besh Log In qe te vendosesh parashikime ndeshjesh<br/><a href='php/login.php'>Kycu Ketu</a></div>";
}
?>
Your problem is here :
$match = "SELECT user_id, match_id FROM match_select";
$row1 = mysql_query($match)or die(mysql_error());
while ($row2 = mysql_fetch_assoc($row1)) {
$user_match = $row2["user_id"];
$match = $row2['match_id'];
}
You are not checking it correctly. You have to check if the entry in match_select exists for the user_id and the match_id concerned. Otherwise, $match would always be equal to the match_id field of the last inserted row in your database :
$match = "SELECT *
FROM `match_select`
WHERE `user_id` = '<your_id>'
AND `match_id` = '$test_id'";
$matchResult = mysql_query($match)or die(mysql_error());
if(mysql_num_rows($matchResult)) {
echo "You have already bet.";
}
By the way, consider using PDO or mysqli for manipulating database. mysql_ functions are deprecated :
http://www.php.net/manual/fr/function.mysql-query.php
validate insertion of record by looking up on the table if the data already exists.
Simplest way for example is to
$query = "SELECT * FROM match_select WHERE user_id = '$user_id'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
// do not insert
}
else
{
// do something here..
}
In your form you have <select name='test[$id]'> (one for each item), then when you submit the form you are getting $tests = $_POST["test"]; You don't need to specify the index in the form and can simply do <select name='test[]'>, you can eventually add a hidden field with the id with <input type="hidden" value="$id"/>. The second part is the verification wich is not good at the moment; you can simply check if the itemalready exist in the database with a query

Categories