How to check each rows in PHP MySQL ? - php

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.

Related

How to execute a function inside of a "Do While" in php without losing the variable

This "do while" give me the results of a specific table.
do {
comprobe($row_DatosConsulta['strCod']);
?>
<tr class="edit">
<td class="text-center"> <?php echo $row_DatosConsulta['strCod']; ?> </td>
<td class="text-center"> <?php echo $row_DatosConsulta['strNombre'] ?> <?php echo $row_DatosConsulta['strApellido'] ?> </td>
<td class="text-center"> <?php echo $row_DatosConsulta['strMedidor'] ?> </td>
<td class="text-center"> <?php echo ObtenerDeuda($row_DatosConsulta['intDeuda']) ?></td>
<td class="text-center">
} while ($row_DatosConsulta = $Result->fetchArray(SQLITE3_ASSOC));
my problem is that when i try to use the function "comprobe" (a function that is in another page, but that page are included in the actual page) there is an error that appears, "Undefined variable" so i think that the "do while" is not sending the name to the function, and in that order, the function cant work.
I need to execute a function with all the data that generate the "do while"... for example, if there is 30 names generated by the "do while" of the table, I need to execute 30 times that function with one per one of the names.
so my question is, how could i do that?
actually I'm using SQLITE3, and my function is the next one
function actualizardeudasusu(){
$bd = new SQLite3('my_datebase.db');
$DatosConsulta = ("SELECT * FROM tblDeudas WHERE strCod='".$Codigo."' ");
$Result = $bd->query($DatosConsulta)or die("Error in query: <span
style='color:red;'>$query</span>");
$row_DatosConsulta = $Result->fetchArray(SQLITE3_ASSOC);
echo $DatosConsulta;
$CONTADOR = (" PRAGMA table_info(tblDeudas); ");
$ResultCont = $bd->query($CONTADOR)or die("Error in query: <span
style='color:red;'>$query</span>");
$conteoprevio = $ResultCont->fetchArray(SQLITE3_ASSOC);
$comprobaciondedeuda = 0;
$number = 0;
do {
$number++;
${"mes".$number} = $conteoprevio['name'];
if ($row_DatosConsulta[${"mes".$number}] != 'pagado'){
$comprobaciondedeuda = 1;
}
}
while ($conteoprevio = $ResultCont->fetchArray(SQLITE3_ASSOC));
if ($comprobaciondedeuda == 1){
$updateSQL = "UPDATE tblafiliacion SET
intDeuda='1'
WHERE strCod='".$codigo."' " ;
$Result = $bd->query($updateSQL)or die("Error in query: <span
style='color:red;'>$query</span>");
} else {
$updateSQL = "UPDATE tblafiliacion SET
intDeuda='0',
WHERE strCod='".$codigo."' " ;
$Result = $bd->query($updateSQL)or die("Error in query: <span
style='color:red;'>$query</span>");
}
}
Your problem is that do while loop is not a correct solution.
How does your do-while woork for the first time? You enter do body and try to use $row_DatosConsulta. But $row_DatosConsulta is not defined. Why? Because it will be defined later in while-check.
So, instead do-while use while:
while ($row_DatosConsulta = $Result->fetchArray(SQLITE3_ASSOC)) {
comprobe($row_DatosConsulta['strCod']);
// do other stuff here
}

Voting System using Radio Buttons & Checkboxes (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... }

Itemcode is not delete from database

So I am trying to get a row of information to delete from my database 'barcode' but it is not happening. I hit the submit button but it does not delete the 'itemcode' that I have typed in the input box. HELP??
following edit i have a new error
Error:You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1' at line 1
Delete.php
Testing to see if items deleted
<form action="delete.php" method="post">
<tr>
<td>Item Code: </td>
<td><input type="text" name="itemcode" autofocus></td>
<td><input type="submit" value="Delete"></td>
</tr>
</table> <br>
<?php
require_once('dbconnect.php');
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$result = mysqli_query($con, "SELECT * from barcode order by itemcode");
$delete = mysqli_query($con,"DELETE FROM barcode WHERE itemcode='itemcode'");
if(!mysqli_query($con, $delete))
{
echo('Error:'.mysqli_error($con));
}
echo "<center><table border=1>";
echo"<tr>
<th>ITEM CODE:</th>
<th>Company Shipping:</th>
</tr>";
while($row = mysqli_fetch_array ($result))
{
echo"<tr>
<td align= center>".$row['itemcode']."</td>
<td align=center>".$row['item']."</td>
</tr>";
}
echo "</table>";
mysqli_close($con);
dbconnect.php
$con = mysqli_connect("localhost","root","root","db1");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "Connected to Database. Please Continue.";
}
Add.php The add.php works but delete does not.
php
include('dbconnect.php');
function get_posts() {
global $con;
$txtitemcode = (!empty($_POST['itemcode']) ? $_POST['itemcode'] : null);
$txtitem = (!empty($_POST['item']) ? $_POST['item'] : null);
$sql1 = "INSERT INTO barcode (itemcode, item) VALUES ('".$txtitemcode."','".$txtitem."')";
if(!mysqli_query($con, $sql1))
{
die('Error:'.mysqli_error());
}
echo "<script> alert('1 record added');
window.location.href='index.php';
</script>";
}
get_posts(); //Must have to show posts in table
mysqli_close($con);
?
You are executing the stuff twice:
This line executes the query and puts the result in to $delete:
$delete = mysqli_query($con,"DELETE FROM barcode WHERE itemcode='itemcode'");
Now you are issuing another query with the result from above:
if(!mysqli_query($con, $delete))
{
echo('Error:'.mysqli_error($con));
}
And this is issuing an error as posted: the result in $delete is "1" and "1" isn't a statement.
Change:
$delete = mysqli_query($con,"DELETE FROM barcode WHERE itemcode='itemcode'");
if(!$delete) // or if ( $delete === false )
{
echo('Error:'.mysqli_error($con));
}
Furthermore, following the logic of these few lines, I assume it should be:
if ( isset($txtitemcode) )
{
$delete = mysqli_query($con,"DELETE FROM barcode WHERE itemcode='" . $txtitemcode . "'");
if(!$delete) // or if ( $delete === false )
{
echo('Error:'.mysqli_error($con));
}
}

PHP Form won't let me add a New Row to MySQL Database

I am trying to add in a new row to a MySQL table. It is reading me the error Could not enter data: Column count doesn't match value count at row 1 . So far, I am using the code
if(! get_magic_quotes_gpc() )
{
$job_pos = addslashes ($_POST['job_pos']);
}
else
{
$job_pos = $_POST['job_pos'];
}
$job_pos_sort = "SELECT LAST(job_pos_sort) FROM careers;" + 1;
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())";
to insert a new row into the table.
Here is my entire code for the page, my page can be seen at http://thetotempole.ca/phptester/upanddowntest.php :
<?php
// connect to db
$conn = mysql_connect("xxxx","x","x","x") or die(mysql_error());
$db = mysql_select_db('x',$conn) or die(mysql_error());
// if an arrow link was clicked...
if ($_GET['dir'] && $_GET['id']) {
// make GET vars easier to handle
$dir = $_GET['dir'];
// cast as int and couple with switch for sql injection prevention for $id
$id = (int) $_GET['id'];
// decide what row we're swapping based on $dir
switch ($dir) {
// if we're going up, swap is 1 less than id
case 'up':
// make sure that there's a row above to swap
$swap = ($id > 1)? $id-- : 1;
break;
// if we're going down, swap is 1 more than id
case 'down':
// find out what the highest row is
$sql = "SELECT count(*) FROM careers";
$result = mysql_query($sql, $conn) or die(mysql_error());
$r = mysql_fetch_row($result);
$max = $r[0];
// make sure that there's a row below to swap with
$swap = ($id < $max)? $id++ : $max;
break;
// default value (sql injection prevention for $dir)
default:
$swap = $id;
} // end switch $dir
// swap the rows. Basic idea is to make $id=$swap and $swap=$id
$sql = "UPDATE careers SET job_pos_sort = CASE job_pos_sort WHEN $id THEN $swap WHEN $swap THEN $id END WHERE job_pos_sort IN ($id, $swap)";
$result = mysql_query($sql, $conn) or die(mysql_error());
} // end if GET
// set a result order with a default (sql infection prevention for $sortby)
$sortby = ($_GET['sortby'] == 'job_pos')? $_GET['sortby'] : 'job_pos_sort';
// pull the info from the table
$sql = "SELECT job_pos_sort, job_pos FROM careers ORDER BY $sortby";
$result = mysql_query($sql, $conn) or die(mysql_error());
// display table
echo "<table border = '1'>";
echo "<tr>";
// make column names links, passing sortby
echo "<td><a href='{$_SERVER['PHP_SELF']}?sortby=job_pos_sort'>job_pos_sort</a></td>";
echo "<td><a href='{$_SERVER['PHP_SELF']}?sortby=job_pos'>job_pos</a></td>";
echo "</tr>";
// display data 1 row at a time
while ($r = mysql_fetch_assoc($result)) {
echo "<tr>";
// make the links to change custom order, passing direction and the custom sort id
echo "<td align = 'center'><a href='{$_SERVER['PHP_SELF']}?dir=up&id={$r['job_pos_sort']}'>/\</a> ";
echo "<a href='{$_SERVER['PHP_SELF']}?dir=down&id={$r['job_pos_sort']}'>\/</a></td>";
echo "<td>{$r['job_pos']}</td>";
echo "</tr>";
} // end while $r
echo "</table>";
// end display table
?>
<html>
<head>
<title>Manage Careers</title>
</head>
<body>
<?php
if(isset($_POST['add']))
{
$dbhost = 'x';
$dbuser = 'xx';
$dbpass = 'xx';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn )
{
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() )
{
$job_pos = addslashes ($_POST['job_pos']);
}
else
{
$job_pos = $_POST['job_pos'];
}
$job_pos_sort = "SELECT LAST(job_pos_sort) FROM careers;" + 1;
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())";
mysql_select_db('x');
$retval = mysql_query( $sql, $conn );
if(! $retval )
{
die('Could not enter data: ' . mysql_error());
}
echo "Entered data successfully\n";
mysql_close($conn);
}
else
{
?>
<form method="post" action="<?php $_PHP_SELF ?>">
<table width="400" border="0" cellspacing="1" cellpadding="2">
<tr>
<td width="100">Job Position</td>
<td><input name="job_pos" type="text" id="job_pos"></td>
</tr>
<tr>
<td width="100"> </td>
<td> </td>
</tr>
<tr>
<td width="100"> </td>
<td>
<input name="add" type="submit" id="add" value="Add Job Position">
</td>
</tr>
</table>
</form>
<?php
}
?>
</body>
</html>
Any help is appreciated.
Regards,
Kelsey
I don't know what you are expecting to happen when specifying 2 columns, and trying to add 3
"INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())
Googling the error would help you. It exactly tells what you are getting wrong.
columns job_pos, job_pos_sort, but values - job_pos, job_post_sort and NOW(). You might have to specify the last column, which seems to be a datetime one
I hope you also are aware the $job_pos_sort is just a string, and want evaluate to anything, especially with adding 1 to the string (it may rise an error too)
And, you'd better switch to one of the modern DB API's regarding mysql - mysqli or PDO.
http://www.php.net/manual/en/mysqlinfo.api.choosing.php
you should run this :
SHOW COLUMNS FROM careers;
then maybe we know the name of the field missing here xxxxxx
it must be a sort of date.
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort, xxxxxx) ".
"VALUES('$job_pos', '$job_pos_sort', NOW())";
or simply try this:
$sql = "INSERT INTO careers ".
"(job_pos, job_pos_sort) ".
"VALUES('$job_pos', '$job_pos_sort')";
this should work

Parse error: syntax error, unexpected T_ELSE in /home3/mafiasec/public_html/logincheck.php on line 311 [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Here's my code, it's irritating as I can't find the problem.. I have been looking into this for the past two days and can't work it out myself, I am relatively new to coding so please explain clearly what is going on because I clearly won't understand what you are saying. please give me a hand here - here's the code.
<?php
session_start();
include_once("includes/db_connect.php");
if (isset($_SESSION['real_name'])){
include "mainmenu.php";
die("-");
exit();
}
error_reporting(0);
//This of course tells the website that what follows
$realip=$_SERVER['REMOTE_ADDR'];
if ($_POST['Submit'] && mysql_real_escape_string($_POST['username'])){
function change($msg){
$post = $msg;
$post = str_replace(" ", "", $post);
return $post;
}
$username = $_POST['username'];
$password = $_POST['password'];
$password = mysql_real_escape_string(strip_tags($password));
$ip = $_SERVER['REMOTE_ADDR'];
$date = gmdate('Y-m-d h:i:s');
$tquery = "SELECT nextlogin FROM users WHERE username='$username'";
$tresult = mysql_query($tquery) or die(mysql_error());
$trow = mysql_fetch_array($tresult);
if((time() < $trow['nextlogin']) ) {
$waittime=$trow['nextlogin'] - time();
die("This user has allready tried to login in the past 30 seconds! please wait $waittime seconds before you can login!");
}
$result = mysql_query("SELECT * FROM loginip") or die("Hack protection error Please contact admin#mafiasecrets.com and tell him about this!");
// keeps getting the next row until there are no more to get
while($row = mysql_fetch_array( $result )) {
$id = $row['id'];
$timeleft = $row['time'] - time();
if ($timeleft <0){mysql_query("DELETE FROM loginip WHERE id='$id'");}
}// while loop
$select = mysql_query("SELECT * FROM loginip WHERE ip='$realip'");
$num = mysql_num_rows($select);
if($num>"0"){
die("Your ip has allready tried to login in the past 30 seconds, Please wait $timeleft seconds before you can login again!");
}
///check INFO
$sql = mysql_query("SELECT * FROM users WHERE username='$username' AND password='$password' LIMIT 1");
$login_check = mysql_num_rows($sql);
$inf = mysql_fetch_object($sql);
if ($login_check > "0"){
session_register('username');
$_SESSION['real_name'] = $username;
//This of course tells the website that what follows
$realip=$_SERVER['REMOTE_ADDR'];
$time2 = time();
$timestamp = time()+60;
$sql = "UPDATE users SET nextlogin='".strtotime ("+30 seconds")."' WHERE username='".mysql_real_escape_string($username)."'";
mysql_query($sql);
$sql = "INSERT INTO loginip SET id = '', ip = '$realip', time = '".strtotime ("+20 seconds")."'";
$res = mysql_query($sql);
mysql_query("UPDATE lastloginname SET username='$username' WHERE ip='$realip'");
mysql_query("UPDATE users SET online='Online', onlinetime2='$time2' WHERE username='$username'");
mysql_query("UPDATE users SET apperoffline='1' WHERE username='$username'")or die("Error aper oflin");
$time1=time()+500;
mysql_query("INSERT INTO `loggedin` (`id`, `ip`, `username`, `time`) VALUES ('', '$realip', '$username', '$time1')");
$sql = mysql_query("SELECT * FROM facebookshare WHERE username='$username'");
$fb_check = mysql_num_rows($sql);
if ($fb_check == "0"){
$timef = gmdate('Y-m-d h:i:s');
?>
<?php
mysql_query("INSERT INTO `facebookshare` (`id`, `username`, `time`) VALUES ('', '$username', '$timef')");
}//not shared
?><?php
$sql="SELECT * FROM users WHERE username='$username' LIMIT 1";
$result=mysql_query($sql);
while($rows=mysql_fetch_array($result)){ // Start looping table row
$rank = mysql_real_escape_string(strip_tags($rows['rank']));
$health = mysql_real_escape_string(strip_tags($rows['health']));
$country = mysql_real_escape_string(strip_tags($rows['country']));
$rankpoints = mysql_real_escape_string(strip_tags($rows['rankpoints']));
$rankbar = mysql_real_escape_string(strip_tags($rows['rankbar']));
$firstlogin = mysql_real_escape_string(strip_tags($rows['firstlogin']));
}
?>
<?
if($_POST['a']){
mysql_query("UPDATE users SET `firstlogin`=`firstlogin`+'1' WHERE username='$username'");
echo "<meta http-equiv='refresh' content='1;URL=veri.php'>";
}
?>
<style type="text/css">
<!--
.textbox {background-color: 222222; border-bottom: 1px solid #626262; border-left: 1px solid #040404; border-right: 1px solid #626262; border-top: 1px solid #040404; color: white; font-family: verdana; font-size: 18px;}
-->
</style>
<body bgcolor="#222222">
<META HTTP-EQUIV="Refresh" CONTENT="4; URL=play.php">
<table cellpadding="0" width="100%" height="100%">
<td width="100%" height = "100%"><center>
<font color="white" face="verdana" size="3">Welcome: </font><b><font color=khaki size=3 face=verdana><? echo $username ?></font></b><br>
<table width=300 cellpadding=0 cellspacing=0 align=center>
<tr>
<td height=5></td>
</tr>
<tr>
<td height=1 bgcolor=#444444></td>
</tr>
<tr>
<td height=5></td>
</tr>
</table>
<?php
$rank_1 = "Hobo";
$rank_2 = "Citizen";
$rank_3 = "Vandal";
$rank_4 = "Thug";
$rank_5 = "Respected Thug";
$rank_6 = "Mobster";
$rank_7 = "Respected Mobster";
$rank_8 = "Assassin";
$rank_9 = "Respected Assassin";
$rank_10 = "Mafioso";
$rank_11 = "Respected Mafioso";
$rank_12 = "Underboss";
$rank_13 = "Respected Underboss";
$rank_14 = "Boss";
$rank_15 = "Respected Boss";
$rank_16 = "Godfather";
$rank_17 = "Respected Godfather";
$rank_18 = "Gangster";
$rank_19 = "Immaculate Gangster";
$rank_2_exp = "50";
$rank_3_exp = "120";
$rank_4_exp = "350";
$rank_5_exp = "1100";
$rank_6_exp = "3200";
$rank_7_exp = "6100";
$rank_8_exp = "11300";
$rank_9_exp = "15000";
$rank_10_exp = "21000";
$rank_11_exp = "30000";
$rank_12_exp = "41000";
$rank_13_exp = "52000";
$rank_14_exp = "66500";
$rank_15_exp = "82500";
$rank_16_exp = "98000";
$rank_17_exp = "128000";
$rank_18_exp = "147000";
$rank_19_exp = "170000";
?>
<?php
$newmail = mysql_query("SELECT * FROM messages WHERE t='$username' AND r='0'");
$notoriouslegendskk = mysql_num_rows($newmail);?>
<?
if ($rankbar>=1){
if ($rankpoints > "$rank_19_exp"){
$nextrank = 0;
}else{
if ($rankpoints < "$rank_2_exp"){ $amount="$rank_2_exp"; $check="0";}
elseif ($rankpoints < "$rank_3_exp"){ $amount="$rank_3_exp"; $check="$rank_2_exp";}
elseif ($rankpoints < "$rank_4_exp"){ $amount="$rank_4_exp"; $check="$rank_3_exp";}
elseif ($rankpoints < "$rank_5_exp"){ $amount="$rank_5_exp"; $check="$rank_4_exp";}
elseif ($rankpoints < "$rank_6_exp"){ $amount="$rank_6_exp"; $check="$rank_5_exp";}
elseif ($rankpoints < "$rank_7_exp"){ $amount="$rank_7_exp"; $check="$rank_6_exp";}
elseif ($rankpoints < "$rank_8_exp"){ $amount="$rank_8_exp"; $check="$rank_7_exp";}
elseif ($rankpoints < "$rank_9_exp"){ $amount="$rank_9_exp"; $check="$rank_8_exp";}
elseif ($rankpoints < "$rank_10_exp"){ $amount="$rank_10_exp"; $check="$rank_9_exp";}
elseif ($rankpoints < "$rank_11_exp"){ $amount="$rank_11_exp"; $check="$rank_10_exp";}
elseif ($rankpoints < "$rank_12_exp"){ $amount="$rank_12_exp"; $check="$rank_11_exp";}
elseif ($rankpoints < "$rank_13_exp"){ $amount="$rank_13_exp"; $check="$rank_12_exp";}
elseif ($rankpoints < "$rank_14_exp"){ $amount="$rank_14_exp"; $check="$rank_13_exp";}
elseif ($rankpoints < "$rank_15_exp"){ $amount="$rank_15_exp"; $check="$rank_14_exp";}
elseif ($rankpoints < "$rank_16_exp"){ $amount="$rank_16_exp"; $check="$rank_15_exp";}
elseif ($rankpoints < "$rank_17_exp"){ $amount="$rank_17_exp"; $check="$rank_16_exp";}
elseif ($rankpoints < "$rank_18_exp"){ $amount="$rank_18_exp"; $check="$rank_17_exp";}
elseif ($rankpoints < "$rank_19_exp"){ $amount="$rank_19_exp"; $check="$rank_18_exp";}
/// total rankpoints - rankpoints required for current rank / rank points needed for next rank * 100
$end = $amount - $check;
$percent = $rankpoints - $check;
$percent = $percent / $end;
$add = $percent * 100;
if($rankbar==2){
$nextrank = sprintf ("%0.1f",$add);
}else{
$nextrank = round($add);
}
}//not undercover gangster
?>
<font color=white face=verdana size=2>You have <b style=color:khaki;><?php echo $notoriouslegendskk ?></b> new messages!</font><br>
<table width=300 cellpadding=0 cellspacing=0 align=center>
<tr>
<td height=5></td>
</tr>
<tr>
<td height=1 bgcolor=#444444></td>
</tr>
<tr>
<td height=5></td>
</tr>
</table>
<font color=silver face=verdana size=1>Rank: </font><font color=white face=verdana size=1><?php echo $rank ?></font><font color=silver face=verdana size=1> | </font> <font color=silver face=verdana size=1>Rank Up: </font><font color=white face=verdana size=1><?php echo $nextrank ?>%</font><font color=silver face=verdana size=1> | </font> <font color=silver face=verdana size=1>Health: </font><font color=white face=verdana size=1><?php echo $health ?>%</font><font color=silver face=verdana size=1> | </font> <font color=silver face=verdana size=1>Location: </font><font color=white face=verdana size=1><?php echo $country ?></font><br>
</center>
</td>
</table>
</body>
<?php } ?>
<?php
} else {
$sql = "UPDATE users SET nextlogin='".strtotime ("+20 seconds")."' WHERE username='".mysql_real_escape_string($username)."'";
mysql_query($sql);
$failtime = date('d-m-Y H:i:s', strtotime('+5 hours'));
mysql_query("INSERT INTO loginfails SET id = '', ip = '$realip', time = '$failtime', username = '$username', password = '$password'");
$sql = "INSERT INTO loginip SET id = '', ip = '$realip', time = '".strtotime ("+30 seconds")."'";
$res = mysql_query($sql);
echo"<b>Invalid Username/Password, Please go back and <a href=index.php>try again!</a></b>";
}else{
die("You did not attempt to login, <a href=index.php>Click</a> here to go to the login page!");
}
?>
You already have an else statement on line 298. You cannot have another else following that.
I think this might be because you are missing a matching } from your code at line 22 (The if() statement does not have closing }). I am guessing your else statement should match that if(), in which case you need to add one } before the else on line 311.
Also, I agree with the others that you need to clean up your code and use proper spacing. It makes debugging much easier.
Edit: Here's the relevant part for your fixed code:
</body>
<?php } ?>
<?php
} else {
$sql = "UPDATE users SET nextlogin='".strtotime ("+20 seconds")."' WHERE username='".mysql_real_escape_string($username)."'";
mysql_query($sql);
$failtime = date('d-m-Y H:i:s', strtotime('+5 hours'));
mysql_query("INSERT INTO loginfails SET id = '', ip = '$realip', time = '$failtime', username = '$username', password = '$password'");
$sql = "INSERT INTO loginip SET id = '', ip = '$realip', time = '".strtotime ("+30 seconds")."'";
$res = mysql_query($sql);
echo"<b>Invalid Username/Password, Please go back and <a href=index.php>try again!</a></b>";
} // Here is the extra } you need to add
} else {
die("You did not attempt to login, <a href=index.php>Click</a> here to go to the login page!");
}
?>
You don't have a "line 311" in the code you gave, but it is ugly as all hell.
I notice that in the final <?php ... ?> block, you have a close brace with no corresponding opening brace - this is most likely the cause of the error. You then go on to have an else that has no corresponding if, followed immediately by another else. Two elses? What does that even mean?
I strongly recommend re-writing this code from scratch, taking care to organise and format it correctly. That way, you will be able to find and fix errors like this yourself.
There is no if clause: I think that is the cause of the error.
$res = mysql_query($sql);
echo"<b>Invalid Username/Password, Please go back and <a href=index.php>try again!</a></b>";
}else{
die("You did not attempt to login, <a href=index.php>Click</a> here to go to the login page!");
}

Categories