I've searched and tried a couple of different ways but I always get a 0000-00-00 00:00:00
Here's my page:
<?php
require_once "../../maincore.php";
require_once THEMES."templates/header.php";
$earnedpoints = false;
$account = $_GET['account'];
$account = mysql_real_escape_string($account);
if ($account == "") {
echo 'Enter an account name!';
exit();
}
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$query = mysql_query("SELECT *, SUM(`times`) as amount FROM votingrecords WHERE account='$account' OR ip='$ip'");
$lasttime = mysql_fetch_array($query);
$amount = $lasttime['amount'];
$insertnew = false;
if ($amount == "") {
$insertnew = true;
}
$timecalc = $time - $lasttime['date'];
if (!$insertnew) {
if ($timecalc < 43200) {
require_once THEMES."templates/header.php";
add_to_title(" - Vote");
opentable("Error");
echo "<table class='tbl-border' width='100%' cellspacing='1' cellpadding='5'><td class='tbl2'>";
echo ' Hello '. $account .' you have already voted with this account ('. $account .') or IP ('. $ip .') in the last 12 hours!';
echo ' Last voted on: '. date('Y-m-d H:i:s', $lasttime['date']) .'';
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="10; url=\vote.php?account=' . $_GET['account'] . '">';
echo '</head>';
echo '<body>';
echo '<br /><br /><center>You will be redirected to the main website in 10 seconds.</center>';
echo '</body>';
echo '</html>';
echo "</td></table>";
closetable();
require_once THEMES."templates/footer.php";
exit();
} else {
$update = mysql_query("UPDATE votingrecords SET account='$account', date='NOW()', times=times+1 WHERE ip='$ip'");
if (!$update) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $update;
die($message);
} else {
$earnedpoints = true;
}
}
} else {
$success = mysql_query("INSERT INTO votingrecords (`account`, `ip`, `date`, `times`) VALUES ('$account', '$ip', 'NOW()', 1)");
if (!$success) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $success;
die($message);
} else {
$earnedpoints = true;
}
}
if ($earnedpoints) {
$points = mysql_query("UPDATE user SET votingpoints = votingpoints + 1 WHERE login='$account'");
if (!$points) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close();
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=vote here">';
echo '</head>';
echo '</html>';
} else {
echo 'There was an error processing your request.';
exit();
}
require_once THEMES."templates/footer.php";
?>
That solved my problem with it not inserting the date, that works fine now!! thanks alot!
I thought it would solve my issue with it not keeping track of when a user votes so they can only vote each 12 hours.It still lets people vote over and over again >.<
Is there anyway to bump this? Lmao.. Still could use some help
Don't put NOW() inside of single quotes...
I just checked the code and you have 'NOW()' in the insert take out quotes and use just now().
'NOW()' will be treated as string and while adding to mysql datetime field its invalid and thus will have 0000-00.....
Related
I am trying to build a simple Rock, Paper, Scissors game. I am using a XAMPP stack. I have successfully retrieved the user's choice of rock, paper, or scissors and inserted it into the table. I have also successfully generated a random "choice from the opponent" by using array_rand but i can't insert this variable/integer into the table ALSO at the same time. I was able at one time to insert the "opponents choice" but never also with the users choice, its always one or the other. And, i figure that i would convert both choices to integers and then use if/else statements to determine the winner of each game but as i've tested this, it doesn't always seem to produce the correct answer. I think there is probably some unnecessary code such as var_dump which i have in there so i can see that I have successfully converted the choices into integers so that i can compare the choices in order to logically determine a winner, for example. Thank you for any help.
<html>
<body>
<p> Make your move! Choose:</p>
<p> Paper, Rock, or Scissors</p>
<form action="rps.php" method="post" id="playform">
<select name="playermove" id="quantity">
<option value="1" selected="selected">Rock</option>
<option value="2">Paper</option>
<option value="3">Scissors</option>
</select>
</form>
<button type="submit" form="playform" value="submit">1, 2, 3....GO!
</button>
</body>
</html>
<?php
require 'connection.php';
$conn = Connect();
$pmove = $conn->real_escape_string($_POST['playermove']);
$omove = $conn->(['oppmove']);
$query = "INSERT into rpstwo.tb_rps2 (playermove) VALUES ('" . $pmove .
"')";
$success = $conn->query($query);
if (!$success) {
die("Couldn't enter data: ".$conn->error);
}
$yourvar = intval($pmove);
echo "You chose: " . $yourvar . "<br>";
var_dump($yourvar);
echo "<br>";
$oppdecision = array('rock', 'paper', 'scissors');
$oppresult = array_rand($oppdecision, 1);
echo "Your opponent chose: " . $oppresult . "<br>";
$oppsmove = $oppdecision[$oppresult];
echo $oppsmove . "<br>";
$oppvar = intval($oppresult);
var_dump($oppvar);
$sql = "INSERT into rpstwo.tb_rps2 (oppmove) VALUES ('" . $omove .
"')";
$success = $conn->query($sql);
if ($yourvar = 1 & $oppvar = 0) {
echo '<br>' . "you tie";
} elseif ($yourvar = 1 & $oppvar = 1) {
echo '<br>' . "you lose";
} elseif ($yourvar = 1 & $oppvar = 2) {
echo '<br>' . "you win";
} else {
echo '<br>' . "Good game!";
}
$conn->close();
?>
The code below fixes your posting to a DB. It does not fix the issues of WIN/LOSE/DRAW possibilities. You should also know that your code posts an integer for playermove and text (rock,paper,scissors) for opponent move. You having two Insert statements will cause 2 separate rows to be created per game.
$pmove = $_POST['playermove'];
$yourvar = intval($pmove);
echo "You chose: " . $yourvar . "<br>";
echo "<br>";
$oppdecision = array('rock', 'paper', 'scissors');
$oppresult = array_rand($oppdecision, 1);
echo "Your opponent chose: " . $oppresult . "<br>";
$oppsmove = $oppdecision[$oppresult];
echo $oppsmove . "<br>";
$oppvar = intval($oppresult);
$sql = "INSERT into tb_rps2 (oppmove,playermove) VALUES ('$oppresult','$pmove')";
$success = $conn->query($sql);
if ($yourvar = 1 & $oppvar = 0) {
echo '<br>' . "you tie";
} elseif ($yourvar = 1 & $oppvar = 1) {
echo '<br>' . "you lose";
} elseif ($yourvar = 1 & $oppvar = 2) {
echo '<br>' . "you win";
} else {
echo '<br>' . "Good game!";
}
$conn->close();
This question already has answers here:
How can I prevent SQL injection in PHP?
(27 answers)
Closed 5 years ago.
<?php
$conn = mysql_connect("localhost", "root", "") or die ('Error connecting to MySQL!');
mysql_select_db("aspire");
$earnedpoints = false;
$account = $_POST['name'];
$account = mysql_real_escape_string($account);
if ($account == "") {
echo 'Enter an account name!';
exit();
}
$ip = $_SERVER['REMOTE_ADDR'];
$time = time();
$query = mysql_query("SELECT *, SUM(`times`) as amount FROM votingrecords WHERE account='$account' OR ip='$ip'");
$lasttime = mysql_fetch_array($query);
$amount = $lasttime['amount'];
$insertnew = false;
if ($amount == "") {
$insertnew = true;
}
$timecalc = $time - $lasttime['date'];
if (!$insertnew) {
if ($timecalc < 21600) {
echo ' Hello '. $account .' you have already voted with this account ('. $account .') or IP ('. $ip .') in the last 6 hours!';
echo ' Last voted on: '. date('M d\, h:i:s A', $lasttime['date']) .'';
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="10; url=/">';
echo '</head>';
echo '<body>';
echo '<br><br>You will be redirected to the main website in 10 seconds.';
echo '</body>';
echo '</html>';
exit();
} else {
$update = mysql_query("UPDATE votingrecords SET account='$account', date='$time', times=times+1 WHERE ip='$ip'");
if (!$update) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $update;
die($message);
} else {
$earnedpoints = true;
}
}
} else {
$success = mysql_query("INSERT INTO votingrecords (`account`, `ip`, `date`, `times`) VALUES ('$account', '$ip', '$time', 1)");
if (!$success) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $success;
die($message);
} else {
$earnedpoints = true;
}
}
if ($earnedpoints) {
$points = mysql_query("UPDATE accounts SET votepoints = votepoints + 2 WHERE name='$account'");
if (!$points) {
$message = 'Invalid query: ' . mysql_error() . "\n";
$message .= 'Whole query: ' . $query;
die($message);
}
mysql_close($conn);
echo '<html>';
echo '<head>';
echo '<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.gtop100.com/in.php?site=80994">';
echo '</head>';
echo '</html>';
} else {
echo 'There was an error processing your request.';
exit();
}
?>
Hey everyone,
I'm very inexperienced with PHP scripting and I've been told that my script is vulnerable to SQL injection? But I'm not sure how I would make it to be SQL injection proof since I'm not much experienced in that field and i'm afraid I might mess up the code.
Could anyone help me with this? I would greatly appreciate it.
How can I prevent SQL injection in PHP?
Your code is really escaping the input values but mysql_connect is deprecated in PHP 5.5 and totally dropped in PHP 7.
Using parametric query is your best option:
You need to firstly open connection, instead of
$conn = mysql_connect("localhost", "root", "") or die ('Error connecting to MySQL!');
mysql_select_db("aspire");
You will open connection like this
$mysqli = new mysqli("localhost", "root", "", "aspire");
Then prepare your query, instead of putting query like this
$query = mysql_query("SELECT *, SUM(`times`) as amount FROM votingrecords WHERE account='$account' OR ip='$ip'");
You will put it like this
$stmt = $mysqli->prepare("SELECT *, SUM(`times`) as amount FROM votingrecords WHERE account='?' OR ip='?'");
This one is a prepared statement, it is not you that will put your query input, it is PHP that will do it for you, all you need to do is to bind your query input with that $stmt like this
$stmt->bind_param("s", $account);
$stmt->bind_param("s", $ip);
You are having two inputs which are $account and $ip, the account and ip are both string which happens to be what the s stands for... you will now execute the statement, like this
$stmt->execute();
And don't forget to close connection that you opened
$stmt->close();
see this link
http://php.net/manual/en/pdo.prepared-statements.php
use prepared statements and stored procedures
Guys I'm working on the developing an app and I have a very strange problem. I have a database and a web service, I wrote a number of procedures and functions in the database and all well work within the environment MySql, but when I use from URL Request, not show true query (Always run else condition and show me record 'xxxx' that record for response when I understand send data from isn't true and invalid and not show me blank json like '[ ]'), almost all things test, like character set,... (all things that been comments) please help me in the below you're showing my code in the web service and Mysql: php side and Web service:
<?php
if (isset($_REQUEST['action'])) {
$action = $_REQUEST['action'];
} else {
echo "invalid Data";
exit;
}
switch ($action) {
case "getRecord" :
getRecord($_REQUEST['ID'], $_REQUEST['email'], $_REQUEST['mobile']);
break;
.
.
.
.
default:
echo "Your action select is not true!";
}
FUNCTION getRecord($ID, $Email, $Mobile)
{
$con = mysqli_connect("localhost", "root", "root", "myDB");
/*mb_detect_encoding($ID,"ascii");
mb_detect_encoding($Mobile,"ascii");
mb_detect_encoding($Email,"ascii");*/
mb_convert_encoding($ID, 'ascii');
mb_convert_encoding($Email, 'ascii');
mb_convert_encoding($Mobile, 'ascii');
if (mb_check_encoding($ID, "UTF-8")) {
echo "UTF-8 Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Email, "UTF-8")) {
echo "UTF-8 Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Mobile, "UTF-8")) {
echo "UTF-8 Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($ID, "ascii")) {
echo "ascii Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Email, "ascii")) {
echo "ascii Yes!!!" . PHP_EOL;
}
if (mb_check_encoding($Mobile, "ascii")) {
echo "ascii Yes!!!" . PHP_EOL;
}
if (is_int($ID)) {
echo "ID is Integer Yes!!!" . PHP_EOL;
} else {
echo "ID is not Integer!!!" . PHP_EOL;
}
if (is_int($Email)) {
echo "Email is Integer Yes!!!" . PHP_EOL;
} else {
echo "Email is not Integer!!!" . PHP_EOL;
}
if (is_int($Mobile)) {
echo "Mobile is Integer Yes!!!" . PHP_EOL;
} else {
echo "Mobile is not Integer!!!" . PHP_EOL;
}
//////////////////////////////
if (is_string($ID)) {
echo "ID is String Yes!!!" . PHP_EOL;
} else {
echo "ID is not String!!!" . PHP_EOL;
}
if (is_string($Email)) {
echo "Email is String Yes!!!" . PHP_EOL;
} else {
echo "Email is not String!!!" . PHP_EOL;
}
if (is_string($Mobile)) {
echo "Mobile is String Yes!!!" . PHP_EOL;
} else {
echo "Mobile is not String!!!" . PHP_EOL;
}
//$sql = "SET #p0=''$ID''; SET #p1=''$Email''; SET #p2=''$Mobile''; CALL `getRecord`(#p0, #p1, #p2);";
//$sql = "CALL getRecord(''$ID'',''$Email'',''$Mobile'');";
//$sql = "CALL getRecord(" + "'$ID'" + "," + "'$Email'" + "," + "'$Mobile'" + ");";
//$sql = "CALL getRecord(" + "'$ID'" + "," + "'$Email'" + "," + "'$Mobile'" + ");";
//$sql = "CALL getRecord('2261','saleh#gmail.com','+989999999999');";//this state is good word too, and show me true query
$sql = "CALL getRecord('$ID','$Email','$Mobile');";
if (mysqli_connect_errno()) {
echo "Failed to connect MySQL server" . mysqli_connect_error();
}
mysqli_set_charset($con, "ascii");
$resualt = mysqli_query($con, $sql);
$records = array();
while ($row = mysqli_fetch_array($resualt)) {
$record = array();
$record['ID'] = $row['ID'];
$record['Name'] = $row['Name'];
$record['Family'] = $row['Family'];
$record['BirthDate'] = $row['BirthDate'];
$record['Email'] = $row['Email'];
$record['Mobile'] = $row['Mobile'];
$records[] = $record;
}
echo json_encode($records);
mysqli_close($con);
}
Sql side and procedure code :
DELIMITER $$
CREATE PROCEDURE `getRecord` (IN ID VARCHAR(166) CHARACTER SET ascii, IN EMail VARCHAR(166) CHARACTER SET ascii , IN Mobile VARCHAR(166) CHARACTER SET ascii)
BEGIN
DECLARE CheckMe VARCHAR(166);
DECLARE CountRecords INT;
SET CheckMe = ( SELECT Count(*) FROM persons WHERE persons.Email = Email AND persons.Mobile = Mobile);
IF CheckMe = 1 THEN
SELECT * FROM persons WHERE persons.ID = ID;
ELSE
SELECT * FROM persons WHERE persons.ID = 'xxxx';
END IF ;
END $$
DELIMITER ;
This code down here should search database. but I am getting error that my table doesnt exists. And also I want to ask why if I push second time submit button it just jumps to else so it echo choose at least.... and also all data from database. Thanks!
Here is php
if (isset($_POST['submit'])) {
$query = 'SELECT * FROM station_tab';
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone']))
{
$query .= 'WHERE station_name' .mysql_real_escape_string($_POST['station_name']) . 'AND city' . mysql_real_escape_string($_POST['city']) . 'AND zone' . mysql_real_escape_string($_POST['zone']);
} elseif (!empty($_POST['station_name'])) {
$query .= 'WHERE station_name' . mysql_real_escape_string($_POST['station_name']);
} elseif (!empty($_POST['city'])) {
$query .= 'WHERE city' . mysql_real_escape_string($_POST['city']);
} elseif (!empty($_POST['zone'])) {
$query .= 'WHERE zone' . mysql_real_escape_string($_POST['zone']);
} else {
echo "Choose at least one option for search";
}
$result = mysql_query($query, $db) or die(mysql_error($db));
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_array($result)){
echo '<br/><em>' .$row['station_name'] . '</em>';
echo '<br/>city: '. $row['city'];
echo '<br/> zone: ' .$row['zone'];
echo '<br/> Long: ' .$row['lon'];
echo '<br/> Lat: ' . $row['lat'];
}
}
}
here is error message when I add name of the city to city.
Table 'stanice_tab.station_tabwhere' doesn't exist
Here is your corrected code:
$query = 'SELECT * FROM station_tab '; // note the space at the end
if (!empty($_POST['station_name']) && !empty($_POST['city']) && !empty($_POST['zone'])) {
$query .= ' WHERE station_name = "' .mysql_real_escape_string($_POST['station_name']) . '" AND city = "' . mysql_real_escape_string($_POST['city']) . '" AND zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = signs and the space before each AND
} elseif (!empty($_POST['station_name'])) {
$query .= ' WHERE station_name = "' . mysql_real_escape_string($_POST['station_name']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['city'])) {
$query .= ' WHERE city = "' . mysql_real_escape_string($_POST['city']).'"'; // note the = sign and the space at the beginning
} elseif (!empty($_POST['zone'])) {
$query .= ' WHERE zone = "' . mysql_real_escape_string($_POST['zone']).'"'; // note the = sign and the space at the beginning
} else {
echo "Choose at least one option for search";
}
Take the habit of echoing your $query variable so concatenation does not add any typo mistakes.
in phpmyadmin select the database and then select your table
and in menu above there is a sql menu. you can use this functionality to construct sql queries or debug when there are errors like this
i have some code to check for duplicates in a db before submitting the data, but the statement i have does not work. if a duplicate is found a message is returned to the form. however, it is not working and i am sure it has to do with my else statements near the bottom of the file being incorrect. assume all connections are working. where is the error? many thanks
<?php
$array = split('[,]', $_POST['fileno']);
if (isset($_POST['submit'])) {
foreach ($array as $fileno) {
if ($fileno == '' && $box == '')
{
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . 'You must incude a box and a file' . '</div>';
}
elseif ($fileno == '')
{
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . 'You must enter a file reference' . '</div>';
}
elseif ($box == '')
{
//echo error;
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . 'You must enter a box' . '</div>';
}
else
{
$sql = "SELECT custref FROM files WHERE custref = '$fileno' ";
$result = runSQL($sql) or die(mysql_error());
if (mysql_num_rows($result)>0){
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . $fileno . ' is already in the database. No duplicates' . '</div>';
}
$sql = "SELECT custref FROM boxes WHERE custref = '$box' ";
$result = runSQL($sql) or die(mysql_error());
if (mysql_num_rows($result)>0){
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . $box . ' is already in the database. No duplicates' . '</div>';
}
else
{
//insert into db;
echo '<div style="background-color:#ffa; padding:2px; color:#33CC33;font-size:12px;font-weight:normal">' . $fileno . "Box: " . $box . $authorised . 'Successfull' . '</div>';
$sql = "INSERT INTO `files` (customer, authorisation, boxstatus, boxref, custref, filestatus) VALUES ('$customer', '$authorised', '$boxstatus', '$box', '$fileno', $filestatus)";
$result = runSQL($sql) or die(mysql_error());
//echo 'This record is valid';
//header("Location: http://localhost/sample/admin/files/index.php");
//exit();
}
}
}
}
?>
Please check whether it is coming in this section:-
// Some logic
if (...) {
// some more logic
}
...
elseif ($box == '') {
//echo error;
echo '<div style="background-color:#ffa; padding:2px; color:#ff0000;font-size:12px;font-weight:normal">' . 'You must enter a box' . '</div>';
}
else {
echo 'check it here please';
// some more logic
}
...
Hope it helps.
Put some echos to check the values:
foreach ($array as $fileno) {
echo "fileno='$fileno' , box='$box'<br>";
......
then in each block of if/elseif
echo "i'm running line : ",__LINE__,"<br>";
What do you obtain ?
You should try using exit();/die(); in your echoed errors(not the best way of error handling! - try exceptions out) instead of encapsulating dependent code in an else. I suspect this may fix your issue, as you're only checking to add the row against one of your error statements.