I have a game where you can submit your score to a database, but for some reason the submission keeps getting triggered twice. Every entry is doubled. I've seen similar problems posted here, and the solution had to do with the if/else check at the end, but I don't see a problem.
Is it my PHP code that's duplicating the entries or my game application?
<?php
$servername = "xxx";
$username = "xxx";
$password = "xxx";
$dbname = "xxx";
$port = "xxx";
$link = mysqli_connect($servername, $username, $password, $dbname, $port);
// Security
$playerInitials = mysqli_real_escape_string($link,$_REQUEST['initials']);
$playerEmail = mysqli_real_escape_string($link,$_REQUEST['email']);
$playerScore = mysqli_real_escape_string($link,$_REQUEST['score']);
// Convert Initials to Upper Case
$playerInitialsUC = strtoupper($playerInitials);
$sql = "INSERT INTO xmas (initials, email, score)
VALUES ('$playerInitialsUC', '$playerEmail', '$playerScore')";
if(mysqli_query($link, $sql)){
echo "Records added successfully.";
} else{
echo "ERROR: " . mysqli_error($link);
}
mysqli_close($link);
?>
You can try this in your sql query:
REPLACE does exactly what INSERT does but it won't let sql query double a record.
REPLACE into xmas (initials, email, score) values('$playerInitialsUC', '$playerEmail', '$playerScore')
You can tell me if it didn't work or it's not what you want :)
Or you can add this query to the end of your code to make the rows unique:(not sure about this one):
ALTER TABLE xmas ADD UNIQUE( `initials`, `email`, `score`)
Yeah, turns out the my submit button was a little too sensitive and clicks were registering multiple times. Thanks everybody.
Related
Problem:
I want to get the MAX "SID" from my Database and add one. I handle the input via an Form that i submit through the HTTP Post Method. I get the current MAX "SID" from my database, then i put the value into an HTML input field and add one. For some reason this just works every other time. So the output i get is:
Try = 1
Try = 1
Try = 2
Try = 2
and so on. Would be nice if someone could point me in the right direction.
PHP get MAX(ID):
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
$sql = "SELECT MAX(SID) FROM spieler";
$result = mysqli_query($conn, $sql);
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$lastID = $row["MAX(SID)"];
}
}
mysqli_close($conn);
PHP insert in database:
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "soccer";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully";
?><br><?php
$sql = "INSERT INTO spieler VALUES ('$sid', '$name', '$verein',
'$position', '$einsaetze', '$startelf', '$tore',
'$torschuesse', '$eigentore', '$vorlagen', '$elfmeter',
'$verwandelt', '$gegentore', '$gelb',
'$rot', '$fouls', '$zweikampf', '$pass', '$note')";
if(mysqli_query($conn, $sql)){
echo "Success";
}else{
echo "Failed" . mysqli_error($conn);
}
mysqli_close($conn);
HTML & PHP Input Field:
<tr>
<td><input id="SID" name="SID" readonly value="<?php echo $lastID += 1;
?>"></td>
</tr>
Screenshot of the page:
The paragraph "Spieler ID:" is where I put the "SID" so that everytime the page loads the next free ID gets automatically loaded into the input field.
I want to get the MAX "SID" from my Database and add one
No. You don't. You really, really don't.
This is the XY Problem.
You can do it by running a system wide lock and a autonomous transaction. It would be a bit safer and a lot more efficient to maintain the last assigned value (or the next) as a state variable in a table rather than polling the assigned values. But this still ignores the fact that you going to great efforts to assign rules to what is a surrogate identifier and hence contains no meaningful data. It also massively limits the capacity and poses significant risks of both accidental and deliberate denial of service.
To further compound the error here, MySQL provides a mechanism to avoid all this pain out of the box using auto-increment ids.
While someone might argue that these are not portable, hence there may be merit in pursuing another solution, that clearly does not apply here, where your code has no other abstraction from the underlying DBMS.
I am trying to design a scoreboard for a project for my local youth club and would like to be able to click a button onto a wordpress page that will run a PHP script to update a value by 1 in a sql db table, then i can grab the value and display it else where.
Not too worried about passwords being used in scripts at this will only be used within the local network that nobody else has access to, have looked around and found a few bits of code but im not able to actually get it working, here's what i've got so far.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "sot";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The database name is 'sot' the table i want to update is called 'wp_sotstats' and the field within the table is 'CaptainChest' i only need this to really work with just the one entry which the id is '1'
Any thoughts?
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
Is not creating record, it updating it. For me, I will take current value from database as Select, then do ++ to it and do Update query.
$sql = UPDATE wp_sotstats SET CaptainChest=CaptainChest+1 WHERE id=1
Please wrap it in quotes and finish statement with semicolon
Sometimes it sucks when you have these ; " ' (semicolon, single and double quotation marks) everything in a string.
Question is simple what is the easiest way to send those sting into the database.
base64_encode();
base64_decode();
// Is not an option. I need to keep those data just same as it is.
You need
addslashes('your text') // in your php page
PDO statements is the best solution to your problem of executing SQL queries to your database with values that have single/double quotation marks... but more importantly PDO statements help prevent SQL injection.
To show you how this works, this very simple example gives you a basic understanding of how PDO statements work. All this example does is make the connection to the database and insert the username, email and password to the users table.
<?php
// START ESTABLISHING CONNECTION...
$dsn = 'mysql:host=host_name_here;dbname=db_name_here';
//DB username
$uname = 'username_here';
//DB password
$pass = 'password_here';
try
{
$db = new PDO($dsn, $uname, $pass);
$db->setAttribute(PDO::ERRMODE_SILENT, PDO::ATTR_EMULATE_PREPARES);
error_reporting(0);
} catch (PDOException $ex)
{
echo "Database error:" . $ex->getMessage();
}
// END ESTABLISHING CONNECTION - CONNECTION IS MADE.
$username = $_POST['username'];
$email = $_POST['email'];
$password = $_POST['password'];
$hashed_password = password_hash($password, DEFAULT_BCRYPT);
//Validation on inputs here...
// Your SQL query... here is a sample one.
$query = "INSERT INTO users (userName, email, password) VALUES (:userName, :email, :password)";
$statement = $db->prepare($query);
// The values you wish to put in.
$statementInputs = array("userName" => $username, "email" => $email, "password" => $hashed_password);
$statement->execute($statementInputs);
$statement->closeCursor();
?>
You could put the establishing connection part in a separate file and require_once that file to avoid having to write the same code, again and again to establish a connection to your database.
Use mysqli_real_escape_string
$someText = mysqli_real_escape_string($con,"It's a test.");
where $con is your database connection variable.
I'll be honest in saying I'm a rookie coder who knows the basics but is trying to learn more, this issue is also the reason I made an account as well as it's really stumped me. Lots of my code is temporary and I'm planning to streamline it later as well as adding features such as asterisks replacing the password input.
The desired outcome of my code is that the value of the variables below should be compared against those in my database table depending on the value of $type. The problem I'm encountering is that no entries are added to my database table. I'm unsure of where the problem lies within my code and I could do with a point in the right direction, this is my first application of prepared statements so I might be using them incorrectly
Main script:
<?php
include connect.db;
//These are normally user inputs from a form in another file.
$type = "students";
$username = "usernametest";
$password = "passwordtest";
$email = "emailtest";
//the connect global initilizes a connection between my database.
$query = $GLOBALS["conn"]->query("SELECT * FROM '$type' WHERE (username = '$username') OR (password = '$password') OR (email = '$email')");
if (mysqli_num_rows($query) == false) {
$stmt = $GLOBALS["conn"]->prepare("INSERT INTO ? (username, password, email) VALUES (?,?,?)");
$stmt->bind_param("ssss", $type, $username, $password, $email);
$stmt->execute();
$stmt->close();
echo "User Registered";
}
else {
echo "Username, password or email are already used";
}
?>
Connection Script:
<?php
//Identifies the databases details.
//Identifies the servername the database is created in
$servername = "localhost";
//Identifies the databases username
$username = "htmltes7";
//Identifies the database password
$password = "(mypassword)";
//Identified the afformentioned databasename
$dbname = "htmltes7_dbname";
/*Creates a new global variable which opens a connection between my database
using the variables above */
$GLOBALS["conn"] = new mysqli($servername, $username, $password, $dbname);
/*IF the connection cannot be made then the equilivent of exit() occours
in the form of die(). An error message is displayed containing information
on the error that occoured using mysqli_connect_error.*/
if (!$GLOBALS["conn"]) {
die("Connection failed: " . mysqli_connect_error());
}
?>
edit: Sorry about my poor formatting and incorrect tag usage first time round, like I said I'm new to both sql and stack overflow and kinda jumped the gun to ask my question. I've made changes based on the feedback and won't reproduce the same mistake in future.
Try to see the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($dbh->errorInfo());
}
I've spent most of the day trying to get data from a form into a MySQL Database, everything I have tried so far has not worked, can anyone figure out what is wrong? The database is connecting fine, it just cannot add any data into the mysql database (current errors are at the bottom)
EDIT: Updated Code Below (Still not working!)
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "report"; // Database name
$tbl_name = "tbl_nonconformance"; // Table name
// Connect to server and select database.
mysql_connect($host, $username, $password) or die("cannot connect");
mysql_select_db("$db_name") or die("cannot select DB");
echo "Database Connected ";
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$tsf = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$sql="INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)
VALUES
('$sno', '$date', '$name', '$email', '$supplier', '$PONum', '$Part', '$Serial', '$TSF', '$Quantity', '$probclass', '$desc')";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
header('Location: ../thankyou.php');
}
else {
echo "ERROR";
}
// close mysql
mysql_close();
?>
First you should change
mysql_connect("$host", "$username", "$password") or die("cannot connect");
to:
$con = mysql_connect($host, $username, $password) or die("cannot connect");
You are calling $con but you never defined it. You want to save your MySQL connection (con) as $con for what you are trying to do here.
You should also really consider upgrading to MySQLi as MySQL is deprecated from PHP and will likely be removed from future versions. Here's a resource to get you started. http://www.php.net/manual/en/book.mysqli.php
Edit July 9 2014: You updated your code, and I do not recall what your original code was. Still, if it's not "working", it's best to describe how it's not working. After you call $result, do this:
if( !$result || !mysql_affected_rows() )
die( mysql_error() );
header('Location: ../thankyou.php'); //this will only occur if there are no SQL errors and the result actually inserted something
mysql_close();
echo "We couldn't forward you automatically. Click here to proceed {insert HTML/JS here}";
This will return the MySQL error message which will help you in your debugging.
You got your argument parsing wrong.
$name = mysql_real_escape_string($con, $_POST['name']);
$con is not defined first of all.
Secondly you are trying to escape $_POST['name'].
mysql_real_escape_string expects 2 arguments, 1st one is mandatory and second one is optional. First argument is the string you want to escape, the second specifies a mysql connection (optional as you may have one open already).
So your statement needs to look like
$name = mysql_real_escape_string($_POST['name']);
Perhaps $con is your mysql connection? Which if it is the case you may want to
$con = mysql_connect ........ and so on
you're using un-secure depreciating methods too. You should research PDO object. It separates variables from your query so they aren't sent at the same time. It also cleans code considerably. I see a few problem areas in his code... You pass in $sno, $date, but they don't exist in your code. $tsf has a different case in instantiation then what you're using in your query. You're using single quotes which can't interpolate data (place values where variable names are). Double quotes do that...
hmmm...
check this out.
<?php
$host = "localhost"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_port = "3306" // Mysql port
$db_name = "report"; // Database name
$dsn = "mysql:dbhost=$host;dbport=$db_port;dbname=$db_name";
//add sno variable declaration here.
$name = $_POST['name'];
$email = $_POST['email'];
$supplier = $_POST['supplier'];
$PONum = $_POST['PONum'];
$Part = $_POST['Part'];
$Serial = $_POST['Serial'];
$TSF = $_POST['tsf'];
$Quantity = $_POST['Quantity'];
$probclass = $_POST['probclass'];
$desc = $_POST['desc'];
$date = date('d-m-Y');
// Connect to server and select database.
$dbConnect = new PDO($dsn, $username, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
$sqlStatement = $dbConnect->prepare("INSERT INTO tbl_nonconformance (sno, Date, Name, Email, Supplier, PONum, Part, Serial, TSF, Quantity, probclass, desc)VALUES('?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?')");
try{
$sqlStatement->execute(array($sno, $date, $name, $email, $supplier, $PONum, $Part, $Serial, $TSF, $Quantity, $probclass, $desc));
header('Location: ../thankyou.php');
}catch(\PDOException $e){
echo 'Error: Could not connect to db.';
}
?>
PDO object is really easy. create $dbConnect = new PDO(). You see the arguments there. dsn, username, password. The last argument is just an associative array setting PDO's error mode with constants. This allows us to use the try catch block to do error handling. IF PDO can't connect we get the catch block to fire...otherwise the try block which is where our data is sent to the db... You see we have a variable called $sqlStatement.. this is made through $dbConnect->prepare(). This function takes the statement... notice variables are excluded for question marks. Inside the try block we call execute from the statement...this takes and array of values that will replace the question marks in order.
remember to create sno variable. I added date for you. also be sure all cases and spellings are right. One letter in your query string, whether spelled wrong, or even just cased wrong will cause a failure.
let me know if there's any errors or questions. jeremybenson11#gmail.com