Why My PHP code INSERT Command is inserting duplicate data sometimes? - php

Here is My Code. Its all working fine. But Some Times it inserting Duplicate Data. Why? I mean i placed the code so that same quize_no and phone combination should not submitted. But Some time its Inserting the Same quize_no and phone combination. Why is this Happening?
$sql = mysqli_query($con,"SELECT * FROM user_mm WHERE phone='$phone'");
while($row = mysqli_fetch_array($sql)) {
$name = $row['name'];
}
date_default_timezone_set("Asia/Dhaka");
$date = date('Y-m-d');
$time = date('h:i:s a', time());
$result = mysqli_query($con,"SELECT id FROM score_mm WHERE phone='$phone' AND quize_no='$quize_no' ");
$count=mysqli_num_rows($result);
if($count>0)
{
echo "1";
}
else
{
// Here I am Inserting Value in to Database
$query = mysqli_query($con,"insert into score_mm(name, phone, quize_no, score, date, time) values ('$name', '$phone','$quize_no', '$score', '$date', '$time')");
echo "Score Submitted Succesfully";
mysqli_close($con);
}

If there should truly never be a situation where you end up with duplicate quize_no and phone combinations in that table, then the first thing you should do is change your table structure to add a unique key to those columns.
For example:
ALTER TABLE score_mm ADD UNIQUE (quize_no, phone);
This won't fix whatever is causing multiple insert requests to be called, but it would at least protect your data integrity by not allowing any rows with duplicate value combinations.

Related

SQL Slow connection, insert respect select

I have a table with a user id and a date, several users connect at the same time and only one user a day can do insert in the database.
I have a slow connection to the server and what it takes to do the select of the last entry, whether it has been today or not, since it can not be a primary key because the date can vary, sometimes it makes double registrations for the same day.
How can I do this so that this does not happen and I only insure an insert a day?
Thank you
Code:
<?php
$sql = "SELECT MAX(timestamp_pole) as last_pole FROM pole WHERE id_group = ". $id_grup;
$resultado = $mysqli->query($sql);
$resultado = $resultado->fetch_assoc();
$las_00 = date('Y-m-d');
$las_00 = strtotime($las_00);
if ($resultado['last_pole'] >= $las_00){
} else {
$sql = "INSERT INTO pole (timestamp_pole, id_user, id_group) VALUES (". $timestamp .",". $user['id'] .",". $id_group .")";
$mysqli->query($sql);
//return addslashes($sql);
if (isset($user['username']))
return "#". $user['username'] ." pole!";
else
return $user['name'] ." pole!";
}
?>
you can create unique index using (date, id_group) as key, by that way you can make sure that there isn't any duplicated date in same group. Also remember to implement try/ catch as running insert query.

SQL Select/ Insert / Update query PHP MySQL

I have a table with columns userID(int),timeIN(date),timeOUT(date)
I am inserting a record in mysql database. First I check if the userID is correct from the other table and if its correct it will add a new record of the userID and timeIN(date) whereas the timeOUT will be NULL, else it will display error if the userID is not correct. I want my code to be able to check if the user is currently timeIN so it will prevent a double entry. I would also like to insert or update timeOUT(date) if the values of userID is equals to the user input and timeIN is not null and timeOUT is null.
Please kindly help...thanks.
Here is my code for inserting userID and timeIN: IT WORKS when inserting into mysql database.
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
require_once('dbConnect.php');
$userID = $_POST['userID'];
$sql = "SELECT * FROM employee WHERE userID='$userID'";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check)){
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
echo 'Time IN Successful!';
}else{
echo 'Invalid USER ID. Please try again!';
}
mysqli_close($con);
}
?>
You should handle these checks inside the database. The current check you are doing in the database can be handled by a foreign key constraint:
alter table dtr add constraint fk_dtr_userId
foreign key (userId) references employee(userId);
The second means that you want only one row with a NULl value. Ideally, this could be handled with a unique constraint:
alter table dtr add constraint unq_dtr_userId_timeOut
unique (userId, timeOut);
Unfortunately (for this case), MySQL allows duplicate NULL values for unique constraints. So, you can do one of two things:
Use a default value, such as '2099-12-31' for time out.
Use a trigger to enforce uniqueness
In either case, the database itself will be validating the data, so you can be confident of data integrity regardless of how the data is inserted or updated.
I did it from my mobile not tested but you will get the idea of what is going on
if(isset($check))
{
$sql="SELECT * FROM dtr WHERE userID = $userID";
$result = mysqli_query($con,$sql);
$check = mysqli_fetch_array($result);
if(isset($check))
{
echo "Already in";
if(isset($check['timeIN']) && !isset($check['timeOUT']))
{
$sql = "UPDATE dtr SET timeOUT= now() WHERE userID=$userID";
mysqli_query($con, $sql);
mysqli_close($con);
}
}
else
{
$sql = "INSERT INTO dtr (userID,timeIN) VALUES ('$userID', now())";
mysqli_query($con, $sql);
mysqli_close($con);
echo 'Time IN Successful!';
}
}
else
{
echo 'Invalid USER ID. Please try again!';
mysqli_close($con);
}

insert images in another table with foreign key

I have two tables in my db, telephones(id, title, price) and images(id, tp_id, photos) I went in the images table and put a foreign key on the tp_id column to match the id in the telephones table so that every image is linked to a telephone. But the problem is my images go into the table fine but the tp_id column always has the value of 0, what I am missing here? can somebody guide me? Thanks
PS: I know about the security vulnerability of my code I am just doing some test here!
<?php
if (isset($_POST['submit'])) {
include 'dbconnect.php';
for ($i = 0; $i < count($_FILES["photo"]["name"]); $i++) {
$target = "img/"; //This is the directory where images will be saved
$target_files = $target . basename($_FILES['photo']['name'][$i]); //This gets all the other information from the form
$ad_title = $_POST['title'];
$ad_price = $_POST['price'];
$ad_photo = $target . ($_FILES['photo']['name'][$i]);
if (!move_uploaded_file($_FILES['photo']['tmp_name'][$i], $target_files)) { //Tells you if its all ok
echo "Sorry, there was a problem uploading your file.";
} else { //Gives and error if its not
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$sql1 = "INSERT INTO images (photos) VALUES ('$ad_photo') ";
$conn->query($sql1);
//Writes the photo to the server
header('location: addconfirm.php');
}
}
}
?>
get the last inserted primary key value using this
$last_id = $conn->insert_id;
You need to get last insert id form telephones table using $conn->insert_id; and the insert into images table as
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$tp_id=$conn->insert_id;// get last insert id
$sql1 = "INSERT INTO images (photos,tp_id) VALUES ('$ad_photo',$tp_id) ";
$conn->query($sql1);
Note:- Your script is Open for sql injection check How can I prevent SQL injection in PHP? to prevent it
Question has already been answered many times Use : MySQL: LAST_INSERT_ID()
$sql = "INSERT INTO telephones (title, price) VALUES ('$ad_title', '$ad_price')";
$conn->query($sql);
$tp_last_insert_id = $conn->LAST_INSERT_ID;// get last insert id
you should call this function right after you insert to get the latest added id
$sql1 = "INSERT INTO images (photos,tp_id) VALUES ('$ad_photo',$tp_last_insert_id) ";
$conn->query($sql1);

PHP inserting data from one table to another

<?php
$con=mysqli_connect("localhost","usr","pwd","db");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con, "SELECT id, Name, email FROM users WHERE status='ACTIVE'");
while($row = mysqli_fetch_array($result)){
// echo $row['Name']. " - ". $row['email'];
// echo "<br />";
$userid = $row['id'];
$username = $row['Name'];
$email = $row['email'];
mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
VALUES ($userid, $username, $email)");
}
mysqli_close($con);
?>
i have the above code i am trying to insert data from one table to another
The above code do not returning any error but it do not puts any data to second table "other_user"
There is an error in INSERT query - you have to enclose strings in quotes, like this:
"INSERT INTO other_user (user_id, username, email)
VALUES ($userid, '$username', '$email')"
A single query would be enough:
$result = mysqli_query($con, "INSERT INTO other_user (user_id, username, email)
SELECT id, Name, email FROM users WHERE status='ACTIVE'");
No need for an agonizing slow row by row insert.
PS: The original error was leaving out quotes around your values.
You should use mysqli prepared statement to insert data to table. Now you don't use quotes in your query (probably that's why data is not inserted into second table) and even if you were, it would be still vulnerable to SQL Injection
I think you should carefully check the table design of your new table.
Check if the column names and types are what you expect.
Also user_id in your new table may be an autoincrement index and than if doesn't have to be inserted.

Add to a record if record exists, otherwise create a record

I’ve created a little weekly trivia game for my website. Basically its five questions, then at the end the user can add their score to a scoreboard.
The problem is that I want the scores to carry from week to week and cumulate. So let’s say you got 4 points one week, then 5 points the next. I want the scoreboard to reflect you have 9 points.
So I created a small form with an i
nvisible field that has the users score, a field for the username, and a field for the e-mail address. Next week, when the user takes the quiz again, I want their score to be updated if the username and e-mail match a record in the database. If no record does match, I want an entry to be created.
Here’s the script I came up with, however, it doesn’t work (which doesn’t surprise me, I’m pretty new to PHP/MySQL)
$name = $_POST['name']; //The Username
$score = $_POST['submitscore']; //The users score (0-5)
$email = $_POST['email'];//Users email address
$date = date("F j, Y, g:i a");//The date and time
if($name != '') {
$qry = "SELECT * FROM scoreboard WHERE name='$name'";
$result = mysql_query($qry);
if($result) {
if(mysql_num_rows($result) > 0) {
$sum = ($row['SUM(score)']+$score);
"UPDATE scoreboard SET score = '$sum' WHERE name = '$name'";
}
else
$q = mysql_query("INSERT INTO scoreboard (`name`, `email`, `date`, `score`) VALUES ('$name', '$email', '$date', '$score');");
#mysql_free_result($result);
}
else {
die("Query failed");
}
}
My table scoreboard looks like this
id........name........email...........date...........score
1........J.Doe.....j.doe#xyz.com.....7/27/11.........4
You're looking for INSERT... ON DUPLICATE KEY syntax
"INSERT INTO scoreboard (`name`, `email`, `date`, `score`) ".
" VALUES ('$name', '$email', '$date', '$score') ".
"ON DUPLICATE KEY UPDATE `score` = $sum";
Aside:
Use mysql_real_escape_string!
$name = mysql_real_escape_string( $_POST['name'] );
$score = mysql_real_escape_string( $_POST['submitscore'] );
$email = mysql_real_escape_string( $_POST['email'] );
$date = date("F j, Y, g:i a");//The date and time
EDIT
First, this doesn't really work unless you have a column SUM(SCORE):
$sum = ($row['SUM(score)']+$score);
If you want the sum of a column, you need to put that in the MySQL query directly. If you just want the score for that row, however, you can use $row['score']. If you need to add to an existing score you don't need to select for the value (thanks to a1ex07 for pointing this out)
ON DUPLICATE KEY UPDATE `score` = $score + score
This line is incorrect:
$sum = ($row['SUM(score)']+$score);
You probably want to replace it by:
$sum = ($row['score']+$score);
As you are new to PHP/MySQL I recommend you to read about MySQL Injections as your queries contain potential risks.
I'd have a database table to hold quizzes; a database table for members; and a database table that contains foreign keys to both tables along with a score so only one record can be created for each member and each quiz.
I'd also save the score in a session when the user finishes the quiz so the user can't then just submit any old score to your database; the score entered is the score your application generated.
This way, you can then just query SUM(score) of a member based on that member's ID.

Categories