php - duplicate entry - php

what should do if the entry are doubled?
<?php
require_once('auth.php');
session_start();
$exam = $_SESSION['exam'];
$subject_id = $_SESSION['exam'];
$_SESSION['sub'] = $subject_id;
$subject_title = $_POST['subject_title'];
$subject_description = $_POST['subject_description'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_compre', $con);
$sql = "INSERT INTO examsubjectrecord_table(subject_id , subject_title ,
subject_description)
VALUES ('$subject_id','$subject_title', '$subject_description')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
header("location: addsubject.php?exam=".$exam ."");
}
?>`
Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\compre\admin\addsubjectacc.php on line 4
**Error: Duplicate entry '1' for key 'PRIMARY'**

It depends on yout application business-logic.
You can notify a user about a duplicated entry or silently update information with INSERT ... ON DUPLICATE KEY UPDATE ... SQL statement.

In your database you have a primary key of subject_id which cant have duplicates.
If you need to have duplicates in the subject_id column then you should add a column and set it as a primary key in your database. For example add another column unique_id and set it to auto_increment and as a primary key for row identification.

Basically, you'll first want to check if the value you're trying to insert into your primary key field already exists.
So if you primary key field is subject_id, you'd need to check if that already exists by doing a select query followed by PHP's mysql_num_rows function. For example:
$subject_id = 1337;
$check = mysql_query("SELECT `subject_id` FROM `examsubjectrecord_table` WHERE `subject_id`=" . $subject_id);
// See if anything was returned
if(mysql_num_rows($check) > 0) {
// We have something with this subject_id already!
echo "Cannot insert duplicate subject!";
} else {
// All clear, run your INSERT query here
}

Which column is your primary key? I'm going to assume that's subject_id. This needs to be unique for each row in your table. The easiest way to ensure this is to use AUTO_INCREMENT and then avoid inserting the subject_id at all. It will be assigned automatically.
If you need to find out what the ID of new subjects is, you can use mysql_insert_id.

Related

How to insert values in database if it set foreign key?

<?php
if(isset($_GET['email']) && !empty($_GET['email']))
{
$email = mysql_real_escape_string($_GET['email']);
$sml="UPDATE USERS SET password=$_POST[password] where email='$email' ";
$account=mysql_query("INSERT INTO ACCOUNT(email) SELECT email from USERS WHERE email='$email' ") or die('Error:' .mysql_error());
if (mysql_query($sml,$con))
{
header('Location: ../home.html');
}
else{
die('Eror: ' . mysql_error());
}
}
else
{die('Eror: ' . mysql_error());}
mysql_close($con);
?>
How to insert email in account table its an foreign key for the account table.
I want to insert same email value to the account table for the other table reference.
You have to add user/s first. You can't add a record into Accounts table if you don't have a matching record in the parent(Users) table.
That is how foreign key constraint works. For example if you have a record in Users table with user_id = 1, you are only allowed to have records with user_id = 1 in the Accounts table. And so on...
Hint 1:
Try not to put $_POST['key'] directly into query because that makes it vulnerable to sql injection.
Hint 2:
Use exit after header function.

Duplicate Data for Primary Key

I have a table that saves an ID for the user. The data for that id is gotten from LDAP
The first time the user logs in, it inserts his ID on the table. but i need to do this considering users that have data already on the database.
I get the error
Duplicate entry 'whateverdata' for key 'PRIMARY'.
Since the field it is inserting data is Primary key. But i need to get around this.
$check = "select * from utilizadores where id = '$samaccountname[0]'";
$h = mysql_query($check);
if (!$h) {
die (mysql_error());
}
$data = mysql_fetch_array($h);
if ($data[0] > 1) {
header('location:pprincipal.php');
}
else {
$query = mysql_query("insert into utilizadores (id) values('$samaccountname[0]');");
if (!$query){
die (mysql_error());
}
}
I don't want to duplicate data, i just want to check if the data is inserted, and if it is, proceed, if it isn't, insert data.
NOTE: the $samaccountname is a variable that contains data gotten from the LDAP
basicaly - The user logs in the first time and it inserts data on the database.
The second time - Since the field is Primary Key, It will fail.
In order to proceed to the main page (pprincipal.php) the user must have his data inserted on the database.
Thanks in advance.
use mysql_num_rows function in if condition.
if (mysql_num_rows($h)){
header('location:pprincipal.php');
} else {
$query = mysql_query("insert into utilizadores (id) values('$samaccountname[0]');");
if (!$query){
die (mysql_error());
}
}
You can just insert ignore data without checking if it's exist or not.
replace you code with:
$query = mysql_query("insert ignore into utilizadores (id) values('$samaccountname[0]');");
if (!$query){
die (mysql_error());
}

Duplicate entry '' for key 2

Here is the php code that gives me "Duplicate entry '' for key 2" error...
<?php
$host = "localhost";
$user = "admin";
$pass = "123";
$connection = mysql_connect($host,$user,$pass) or die (mysql_errno().": ".mysql_error()."<BR>");
$userid= mysql_real_escape_string($_POST['userid']);
$latitude= mysql_real_escape_string($_POST['latitude']);
$longitude= mysql_real_escape_string($_POST['longitude']);
//$time= mysql_real_escape_string($_POST['time']);
$db_select=mysql_select_db("new");
if(!$db_select){
die(mysql_error());
echo "error";
}
$query= "INSERT INTO location(Userid, Latitude, Longitude )
VALUES ('{$userid}', '{$latitude}', '{$longitude}'); " ;
if($medo=mysql_query($query)){
header("localhost/filename");
exit;
}else{
echo"<p> Error</p>";
die(mysql_error());
}
I don't think there is a problem with my code. please help.
As I suppose you'll want to update if already present, use this syntax for your MySQL request :
$query= "INSERT INTO location (Userid, Latitude, Longitude )
VALUES ('{$userid}', '{$latitude}', '{$longitude}')
ON DUPLICATE KEY UPDATE Latitude='{$latitude}', Longitude='{$longitude}';";
So that when your user already exist, it will be updated with the new coordinates
if the user_id is primary key make it auto increment and don,t post this value from front end.
if it is not a primary key than it will be definitely a unique key. so before insertion first check that record already exists or not.
If you want the unique record for each user, you have to check if user record already exists, then use UPDATE instead of INSERT.
If there are many records for each user, just remove PRIMARY KEY or UNIQUE KEY from 'Userid' column.

Update statement not updating table but inserting new entry into table instead

For the life of me I cannot figure out why my update statement will not update the table row but instead it creates a new row. I have an ID column that is the unique identifier and is auto_increment, I am just not sure if you can update an auto_incremented data set the way i am trying to.
I have a form that is echo'ing data from the database into the fields and then am using it to edit the fields and update them.
The code:
<?php
$EntryID = $_GET['Eid'];
$IDlist = mysql_query("SELECT * FROM BD WHERE Id='$EntryID'");
$IDresults = mysql_fetch_array($IDlist);
$update_query = "UPDATE `BD` SET `Id` ='$IDresults['Id']',`EntryTitle` = '$MyTitle',`EntryDescription` = '$MyDescription',`Category` = '$MyCategory' WHERE `Id` ='$EntryID'";
mysql_query($update_query);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else{
header('location: /admin/bd-edit-entry.php?sub=1');
exit();
}
mysql_close($con);
?>
Any help or advice would be a great.
SET `Id` ='$IDresults['Id']'
should be either:
SET `Id` ='$IDresults[Id]'
or
SET `Id` ='{$IDresults['Id']}'
If you turn on error reporting, you should get errors about a bad index.
Or you can leave this column out of the update entirely, since this column isn't changing.

Issues with when writing to database

I'm unable to write to my database while using this script that I whipped up earlier.
<?php
include("db.php");
if($_SERVER["REQUEST_METHOD"] == "POST")
{
// Data sent from form, then posted to "admin" table in database
$name = mysql_real_escape_string($_POST['name']);
$description = mysql_real_escape_string($_POST['description']);
$author = mysql_real_escape_string($_POST['author']);
$image = mysql_real_escape_string($_POST['image']);
$category = mysql_real_escape_string($_POST['category']);
$sql = "INSERT INTO admin(name,description,author,image,category) VALUES('$name','$description','$author','$image','$category');";
$result = mysql_query($sql);
header("Location: video.php?file=' . $filename . '");
}
?>
And here's my SQL:
CREATE TABLE admin
(
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(50) UNIQUE,
description VARCHAR(50) UNIQUE,
author VARCHAR(50) UNIQUE,
image VARCHAR(50) UNIQUE,
category VARCHAR(50) UNIQUE
);
Everything is submitted with POST via an HTML form. I'm not really sure what I'm doing wrong, so that why I'm wondering what you guys think. Any thoughts?
$result = mysql_query($sql) is not valid (no connection specified).
It needs to be $result = mysql_query($sql, [CONNECTION]);
There may be other issues, but that's an obvious one.
Follow these steps:
Open a MySQL connection (if not omitted in the snippet)
Check your MySQL statement by using var_dump($sql)
Check for the return value of mysql_query(), should be true if the INSERT statement succeeded.
Check for the number of rows affected by the INSERT statement: mysql_affected_rows()
Note:
I'm pretty sure that your INSERT statement fails because all your columns are defined as UNIQUE. As soon as you already have an author with the same name the statement fails!
$auhtor=mysql_real_escape_string($_POST['author']);
The Author variable is spelled wrong.

Categories