Prevent duplicate row insertion php/mysql - php

I'm trying to insert multiple records from a text box into a mysql table.
If I enter more than 2 records, it's inserting duplicates.
Here's the code.
What am I doing wrong?
Some more info
Table info
id (int) primary auto_increment
email (varchar)
imei (varchar)
date_ordered (datetime)
status(varchar)
Since it's only the beginning, I have no problems with changing the table structure.
$email = $_SESSION['email'];
$now = time():
$status = "1";
$imeis = $_POST['imeis'];
$row = explode("\n", $imeis);
foreach ($row as $key => $imei)
{
$imei = mysql_real_escape_string($imei);
$query = "SELECT * FROM orders WHERE imei = '$imei'";
$result = mysqli_query($link, $query);
if (mysqli_num_rows($result) == 0)
{
$query1 = "INSERT IGNORE INTO orders (email, imei, date_ordered, status) VALUES ('$email', '$imei', '$now', '$status')";
$result1 = mysqli_query($link, $query1) OR die("fml");
if ($result1)
{
echo "Added $imei<br>";
}
}
else
{
echo "<B>$imei</B> already there<br>";
}
}

It looks like you want each value of imei to be unique in your table. It;s a guess, but it looks like what you're doing.
You do that in SQL by defining the imei column to be unique: that is, by creating a unique index on it. Your present table has an id as a unique (primary) key. You can easily create another one.

Related

How do I fetch the generated foreign key created in MySQL to be used in Insert Function [duplicate]

This question already has answers here:
PHP/MySQL insert row then get 'id'
(10 answers)
Closed 3 years ago.
I am running the following PHP, as I want to insert data from a form into 2 tables: EventLocation and Events (EventLocationID is the foreign key in the table Events).
First I run an INSERT query to insert into EventLocation. As EventLocationID is auto-incremented, it generates the next ID without me having to enter anything. My question is how should I fetch this unique ID to be used in the next INSERT query to insert into events?
Note that the first query inserts fine, but the second query gives me an error
PHP:
<?php
require '../dbh.inc.php';
$Event_Name = $_POST['Event_Name'];
$Event_Date = $_POST['Event_Date'];
$Street_1 = $_POST['Street_1'];
$Street_2 = $_POST['Street_2'];
$City = $_POST['City'];
$Start_Time = $_POST['Start_Time'];
$End_Time = $_POST['End_Time'];
$Zipcode = $_POST['Zipcode'];
$query = "INSERT INTO EventLocation (Street_1, Street_2, City, Zipcode) VALUES ('$Street_1', '$Street_2', '$City', '$Zipcode')";
$queryexecution = mysqli_query($conn, $query);
if(!$queryexecution){
echo "damn, there was an error inserting into Event Location";
}
else {
echo "Event Location was added!";
}
$querytwo = "SELECT EventLocationID from EventLocation where Street_1 = '$Street_1';";
$querytwoexecution = mysqli_query($conn, $querytwo);
while ($displayname = mysqli_fetch_assoc($querytwoexecution)){
echo "<h1>".$displayname['EventLocationID']."</h1>";
}
$secinsert = "INSERT INTO events (Event_Name, Event_Date, Start_Time, End_Time, EventLocationID) VALUES ('$Event_Name','$Event_Date','$Start_Time','$End_Time', '$displayname')";
$secqueryexecution = mysqli_query($conn, $secinsert);
if(!$secqueryexecution){
echo "damn, there was an error inserting into Events";
}
else {
echo "Event data was added!";
}
?>
I am curious to know if I could just use an Inner Join function to make it more efficient; I tried before but to no success?
You can just use mysqli_insert_id:
$displayname = mysqli_insert_id($link);
this will fetch the last auto_incremented id value from the current connection.

How to store insert array values as separate record

i've one field in mySql table i.e Expanse and another field called Amount.
now i want to break string in expanse and amount field on the basis of ';' and store each as a seperate record such that data in other fields i.e id and name remains unchanged. such that
I am fetching record from orignal table and want to store this desired result in temporary table. while fetching record from orginal table i'm exploding expanse and amount string on the basis on ';'.
$query="SELECT * FROM table";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$newid=$row["id"];
$temp=explode(';',$row["expanse"]);
$new=array_unique($temp);
//what to do after this ?
$temp2=explode(';',$row["amount"]);
$new2=array_unique($temp2);
//what to do after this ?
$query2="INSERT INTO table2 (id, $expanse,$amount) VALUES ('$newid','$new',$new2);
$result2=mysql_query($query2);
}
//after this i'll be inserting values in these variables into new temporary table that is having same structure so that my orignal data remain unchanged and new data as my need inserted into temporary table.
Hope you get my question.
You need to iterate threw each record and again iterate threw each ; delimitted values. id and name will be same for each record but expanse and amount will vary. Number of insert queries is depends on number of ; delimitted values
$query="SELECT * FROM table";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result))
{
$id = $row["id"]; // duplicating for each
$name = $row['name']; // duplicating for each
$expance_array = explode(';',$row["expanse"]);
$amount_array = explode(';',$row["amount"]);
/* count of expance_array and amount_array will be same always as per your idea */
for($i=0;$i<count($expance_array);++$i) {
$expanse = $expance_array[$i];
$amount = $amount_array[$i];
/* now insert $id $name $expanse $amount into the table*/
$query2="INSERT INTO table2 (id, name , expanse, amount) VALUES ($id,'$name','$expanse' , $amount");
$result2=mysql_query($query2);
}
}
You will need a separate INSERT for every item in the array.
function getInsertQueries($id, $expanse, $amount){
$insertQueries = array();
$expanses = array_unique(explode(";", $expanse));
$amounts = array_unique(explode(";", $amount));
if(count($expanses) == count($amounts)){
for($i=0;$i<count($expanses);$i++){
$insertQueries[] = "INSERT INTO table2 (id, expanse, amount) VALUES ('$id', '$expanses[$i]', '$amounts[$i]')";
}
}
return $insertQueries;
}
$query="SELECT * FROM table";
$result=mysql_query($query);
while ($row=mysql_fetch_array($result)){
$insertQueries = getInsertQueries($row["id"], $row["expanse"], $row["amount"]);
foreach($insertQueries as $query){
mysqli_query($query);
}
}

Possible to have Mysql table with 2 unique columns

I currently save game scores using this code:
function SubmitScore()
{
global $result, $db;
$playername = $db->real_escape_string(strip_tags($_POST["playername"]));
$score = $db->real_escape_string(strip_tags($_POST["score"]));
$fbusername = $db->real_escape_string(strip_tags($_POST["fbusername"]));
$gamelevel = $db->real_escape_string(strip_tags($_POST["gamelevel"]));
$query1 = "SELECT * FROM leaderboard WHERE playername = '$playername'";
$query2 = "INSERT INTO leaderboard (playername, score,fbusername,gamelevel) VALUES ('$playername', $score,'$fbusername','$gamelevel')";
$query3 = "UPDATE leaderboard SET score = $score WHERE playername = '$playername'";
$scores = $db->query($query1);
if ($scores->num_rows == 0)
{
$db->query($query2);
$result = "0:New entry";
}
else
{
$row = $scores->fetch_object();
$oldscore = $row->score;
if ($score > $oldscore)
{
$db->query($query3);
$result = "0:Successful update";
} else
$result = "0:Score was lower than before";
}
}
The playername column is unique and inserts a new row for a new player but only updates an existing players score if it is higher than the existing one.
This is fine just for high scores and one level but I need to also need to store the users facebook name and the multipule game levels.
Is it possible to have playername and gamelevel columns to be unique, whereby I can obtain player 1 level 1, player 1 level 2 etc;
bearing in mind I also have to keep the high score as well.
John
MySQL supports a combination of columns to be defined as a unique key. If you remove the index for playername and add a new one for playername+level you are set as far as MySQL goes.
This is how it's done with SQL:
ALTER TABLE `leaderboard` DROP INDEX `unique_index`;
ALTER TABLE `leaderboard` ADD UNIQUE `unique_index`(`playername`, `gamelevel`);

retrieve id value from sql database in php which IS NOT last inserted

I have a database that is designed for Football players and so have the table with the following fields:
Person_ID
First_Name
Surname
NicName
Address_Line_1
Contact_Number
Date_of_birth
Postcode
I need to extract the Person_ID for a player without actually entering the ID number as players will not know their individual number and is designed to be used just by the system.
I have the My sql code for selecting a player when certain values are entered:
SELECT `Person_ID` FROM `person` WHERE `First_Name` = 'A Name' and `Surname` = 'Another Name'
This does not however return very well within php when placed into a function. The function I currently have is shown below (php)
function showid($fname, $sname, $d) {
$sql = "SELECT `Person_ID` FROM `person` WHERE `First_Name` = '$fname' and `Surname` = '$sname'";
$result = mysqli_query($d, $sql);
if (!$result)
print ("$sql failed".mysqli_error($d));
else {
print ("$fname $sname is selected<br>");
}
}
$name and $sname are values which will be entered by the user and they will then be able to transfer to a different team or update their account etc but I need to have the ID selected so that further functions and queries can work fully.
If you want to fetch the ID of the selected player, use the fetch_array function
http://php.net/manual/en/mysqli-result.fetch-array.php
function showid($fname, $sname, $d) {
$sql = "SELECT `Person_ID` FROM `person` WHERE `First_Name` = '$fname' and `Surname` = '$sname'";
$result = mysqli_query($d, $sql);
if (!$result)
print ("$sql failed".mysqli_error($d));
else {
print ("$fname $sname is selected<br>");
}
$row = $result->fetch_array(MYSQLI_ASSOC);
echo "Your ID is" . $row['Person_ID'];
}
This of course assumes there is only one result (otherwise we would have to loop) so you might want to check $result->num_rows is equal to 1 and return an error if it isnt (assuming you arent using UNIQUE in your database)

Inserting array data using mysql insert id and if statements

Ok so whilst I have been working on my PHP and MySQL skills I am new to inserting data into multiple tables in one go. I have done some reading around the subject and I appreciate the basics and the importance of normalised data etc and as such the need to put the information into various tables.
I have pieced the code below together from some of my previous work as well as the tutorial offered at http://www.desilva.biz/mysql/insertid.html . The issue I currently face is that the tutorial I learnt the code from for inputting into various tables was not based around an array of data and whilst I have got it to almost work I cannot use my fuelrecords_id because where I have to call it in my current code it has not yet been defined. Therefore to make my code work at present I just have to use a comma for the column.
Finally I would like to perfect a way to make the if statements work correctly with the array data so if a 0 or blank is submitted as part of the array a new row is not inserted with just 0's in my database tables for that respective row of data
<?php
$wedrf=trim($_POST['FR_WE']);
list($d, $m, $y) = explode('/', $wedrf);
$mk=mktime(0, 0, 0, $m, $d, $y);
$wed_refor=strftime('%Y-%m-%d',$mk);
$con = mysql_connect("ip","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("jbsrint", $con);
//New Code
$row_data = array();
foreach($_POST['VEH_LIST_REG'] as $row=>$VEH_LIST_REG) {
$WEDATE=$wed_refor;
$VEH_LIST_REG=mysql_real_escape_string($VEH_LIST_REG);
$FR_DIE_L=mysql_real_escape_string($_POST['FR_DIE_L'][$row]);
$FR_DIE_C=mysql_real_escape_string($_POST['FR_DIE_C'][$row]);
$FR_PET_L=mysql_real_escape_string($_POST['FR_PET_L'][$row]);
$FR_PET_C=mysql_real_escape_string($_POST['FR_PET_C'][$row]);
$FR_OIL_L=mysql_real_escape_string($_POST['FR_OIL_L'][$row]);
$FR_OIL_C=mysql_real_escape_string($_POST['FR_OIL_C'][$row]);
$row_data[] = "(',', '$VEH_LIST_REG', '$WEDATE')";
$row_data1[] = "(',','$FR_DIE_L', '$FR_DIE_C', ',')";
$row_data2[] = "(',', '$FR_PET_L', '$FR_PET_C', ',')";
$row_data3[] = "(',', '$FR_OIL_L', '$FR_OIL_C', '$FR_OIL_C')";
}
if (!empty($row_data)) {
$query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data);
#$result = mysql_query( $query);
# get fuelrecord id
$fuelrecords_ID = mysql_insert_id();
# if the user submitted diesel information
if( isset($FR_DIE_L) )
{
# and insert the diesel details
$sql = "INSERT INTO fuelrecords_die(FRD_ID,FR_DIE_L,FR_DIE_C,fuelrecords_ID) VALUES ".implode(',', $row_data1);
$result = mysql_query( $sql);
}
# if the user submitted petrol information
if( isset($FR_PET_L) )
{
# and insert the diesel details
$sql = "INSERT INTO fuelrecords_pet(FRP_ID,FR_PET_L,FR_PET_C,fuelrecords_ID) VALUES ".implode(',', $row_data2);
$result = mysql_query( $sql);
}
# if the user submitted oil information
if( isset($FR_OIL_L) )
{
# and insert the oil details
$sql = "INSERT INTO fuelrecords_oil(FRO_ID,FR_OIL_L,FR_OIL_C,fuelrecords_ID) VALUES ".implode(',', $row_data3);
$result = mysql_query( $sql);
}
if (mysql_query($query))
echo '<font color=\"FFFFFF\" size=\"3px\">Successful inserted</font>';
else
echo '<font color=\"FFFFFF\" size=\"3px\">Insert failed</font>';
}
?>
<?php
mysql_close($con)
?>
Tables are as follows:
fuelrecords
FR_ID (Auto increment)
VEH_LIST_REG
FR_WE
fuelrecords_die
FRD_ID (AUTO INCREMENT)
FR_DIE_L
FR_DIE_C
fuelrecords_ID (foreign ID from fuelrecords)
fuelrecords_pet
FRP_ID (AUTO INCREMENT)
FR_PET_L
FR_PET_C
fuelrecords_ID (foreign ID from fuelrecords)
fuelrecords_oil
FRO_ID (AUTO INCREMENT)
FR_OIL_L
FR_OIL_C
fuelrecords_ID (foreign ID from fuelrecords)
Basically the purpose is to log vehicle fuel usage and cost. As there wont always be data for petrol, diesel and oil hence the separate tables so only needed dat is logged.
Hope this clarifies
A always all help and assistance is much appreciated.
If I understand your code correctly you have 4 tables: fuelrecords, fuelrecords_die, fuelrecords_pet, fuelrecords_oil.
The 3 tables fuelrecords_die, fuelrecords_pet, fuelrecords_oil each have a foreign key fuelrecords_id to fuelrecords.fr_id.
You now want to insert multiple tuples into fuelrecords and, if additional data is provided, multiple tuples into the other 3 tables. I assume the fuelrecords.fr_id column is a auto incrementing primary key.
To insert multiple tuples into fuelrecords and to have them each have a new fr_id, you just don't pass a value for the column fr_id. This is equivalent to passing NULL as value. MySQL will then automatically insert unique consecutive numbers for each tuple.
After that you can call mysql_insert_id() to get the first inserted id. Using mysql_affected_rows() you can get the number of inserted tuples. This is enough information to get the id for all lastly inserted tuples. The first is mysql_insert_id()+0 the second is mysql_insert_id()+1, ..., the last is mysql_insert_id()+(mysql_affected_rows()-1).
In the next step you iterate over your input data again and insert the fuelrecords_id into each of the tuples for the other 3 tables, using the above mentioned method. If $i is the index of your input data $_POST['FR_DIE_L'][$i] (starting at $i==0), the fuelrecords_id will be mysql_insert_id()+$i. You are only allowed to iterate to mysql_insert_id()+mysql_affected_rows()-1, but you will probably have the same count of POST-data anyways.
A much simpler but slightly less efficient way is to just do one insert into fuelrecords and then one insert into the other 3 tables for each single POST-data object. You won't have to calculate the fuelrecords_id as mysql_insert_id() will give you the correct id after each insert.
<?php
$wedrf=trim($_POST['FR_WE']);
list($d, $m, $y) = explode('/', $wedrf);
$mk=mktime(0, 0, 0, $m, $d, $y);
$wed_refor=strftime('%Y-%m-%d',$mk);
$row_data = array();
// shorthand for mysql_real_escape_string
function esc($value) {
return mysql_real_escape_string($value);
}
// all tuples for fuelrecords to be inserted
foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) {
$row_data[] = "(NULL, '".esc($VEH_LIST_REG)."', '".esc($wed_refor)."')";
}
if (!empty($row_data)) {
$query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data);
$result = mysql_query($query);
# get first fuelrecord id
$first_fuelrecords_id = mysql_insert_id();
// all tuples for the other 3 tables. insert only if data is givin.
$die_data = array();
$pet_data = array();
$oil_data = array();
foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) {
// calculate the right fuelrecords_id for this tuple
$fuelrecords_id = (int)($first_fuelrecords_id + $row);
// insert for fuelrecords_die
if (isset($_POST['FR_DIE_L'][$row]))
{
$die_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_DIE_L'][$row])."', '".esc($_POST['FR_DIE_C'][$row])."')";
}
// insert for fuelrecords_pet
if (isset($_POST['FR_PET_L'][$row]))
{
$pet_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_PET_L'][$row])."', '".esc($_POST['FR_PET_C'][$row])."')";
}
// insert for fuelrecords_oil
if (isset($_POST['FR_OIL_L'][$row]))
{
$oil_data[] = "(NULL, ".$fuelrecords_id.", '".esc($_POST['FR_OIL_L'][$row])."', '".esc($_POST['FR_OIL_C'][$row])."')";
}
}
// insert the tuples into fuelrecords_die
if (!empty($die_data))
{
$sql = "INSERT INTO fuelrecords_die(FRD_ID, fuelrecords_ID, FR_DIE_L, FR_DIE_C) VALUES ".implode(',', $die_data);
$result = mysql_query( $sql);
}
// insert the tuples into fuelrecords_pet
if (!empty($pet_data))
{
$sql = "INSERT INTO fuelrecords_pet(FRP_ID, fuelrecords_ID, FR_PET_L, FR_PET_C) VALUES ".implode(',', $pet_data);
$result = mysql_query( $sql);
}
// insert the tuples into fuelrecords_oil
if (!empty($oil_data))
{
$sql = "INSERT INTO fuelrecords_oil(FRO_ID, fuelrecords_ID, FR_OIL_L, FR_OIL_C) VALUES ".implode(',', $oil_data);
$result = mysql_query( $sql);
}
}
?>
A small off-topic addition: Try not to use upper case variable names. Upper case identifiers are usually preserved for constants:
define("MY_SHORT_PI", 3.14159265);
define("MY_CONST", "foobar");
$my_variable = "bat";
echo "I am a constant ".MY_SHORT_PI;
echo "Me too ".MY_CONST;
echo "I am a variable ".$my_variable;
This won't have any effect on the PHP interpreter. It's just a common notation to make your code readable for others. There are many style guides out there like the one from PEAR.
Second Example (see comments)
<?php
$wedrf=trim($_POST['FR_WE']);
list($d, $m, $y) = explode('/', $wedrf);
$mk=mktime(0, 0, 0, $m, $d, $y);
$wed_refor=strftime('%Y-%m-%d',$mk);
// VALUES strings for fuelrecords
$row_data = array();
// temporary storage for just _L and _C values
$die_data_tmp = array();
$pet_data_tmp = array();
$oil_data_tmp = array();
// VALUES strings for the three tables
$die_data = array();
$pet_data = array();
$oil_data = array();
// shorthand for mysql_real_escape_string
function esc($value) {
return mysql_real_escape_string($value);
}
// all tuples for fuelrecords to be inserted
foreach($_POST['VEH_LIST_REG'] as $row => $VEH_LIST_REG) {
// check if diesel values are greater than 0
if (0 < (int)$_POST['FR_DIE_L'][$row] && 0 < (int)$_POST['FR_DIE_C'][$row])
$die_data_tmp[$row] = array($_POST['FR_DIE_L'][$row], $_POST['FR_DIE_C'][$row]);
// check if petrolium values are greater than 0
if (0 < (int)$_POST['FR_PET_L'][$row] && 0 < (int)$_POST['FR_PET_C'][$row])
$pet_data_tmp[$row] = array($_POST['FR_PET_L'][$row], $_POST['FR_PET_C'][$row]);
// check if oil values are greater than 0
if (0 < (int)$_POST['FR_OIL_L'][$row] && 0 < (int)$_POST['FR_OIL_C'][$row])
$oil_data_tmp[$row] = array($_POST['FR_OIL_L'][$row], $_POST['FR_OIL_C'][$row]);
// check if at least one of the 3 tables will get tuples. if not just continue
// with the next and don't assign this fuelrecord tuple to $row_data
if (! isset($die_data_tmp[$row]) && ! isset($pet_data_tmp[$row]) && ! isset($oil_data_tmp[$row]))
continue;
// all values are at least 1, so add this tuple to our inserts
$row_data[$row] = "(NULL, '".esc($VEH_LIST_REG)."', '".esc($wed_refor)."')";
}
if (!empty($row_data)) {
$query = 'INSERT INTO fuelrecords(FR_ID, VEH_LIST_REG, FR_WE) VALUES '.implode(',', $row_data);
$result = mysql_query($query);
# get first fuelrecord id
$current_fuelrecords_id = mysql_insert_id();
// all tuples for the other 3 tables. insert only if data is givin.
foreach($row_data as $row => $VEH_LIST_REG) {
// insert for fuelrecords_die
if (isset($die_data_tmp[$row]))
{
$die_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($die_data_tmp[$row][0])."', '".esc($die_data_tmp[$row][1])."')";
}
// insert for fuelrecords_pet
if (isset($pet_data_tmp[$row]))
{
$pet_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($pet_data_tmp[$row][0])."', '".esc($pet_data_tmp[$row][1])."')";
}
// insert for fuelrecords_oil
if (isset($oil_data_tmp[$row]))
{
$oil_data[] = "(NULL, ".$current_fuelrecords_id.", '".esc($oil_data_tmp[$row][0])."', '".esc($oil_data_tmp[$row][1])."')";
}
// increment the fuelrecords_id for the next tuple.
++$current_fuelrecords_id;
}
// insert the tuples into fuelrecords_die
if (!empty($die_data))
{
$sql = "INSERT INTO fuelrecords_die(FRD_ID, fuelrecords_ID, FR_DIE_L, FR_DIE_C) VALUES ".implode(',', $die_data);
$result = mysql_query( $sql);
}
// insert the tuples into fuelrecords_pet
if (!empty($pet_data))
{
$sql = "INSERT INTO fuelrecords_pet(FRP_ID, fuelrecords_ID, FR_PET_L, FR_PET_C) VALUES ".implode(',', $pet_data);
$result = mysql_query( $sql);
}
// insert the tuples into fuelrecords_oil
if (!empty($oil_data))
{
$sql = "INSERT INTO fuelrecords_oil(FRO_ID, fuelrecords_ID, FR_OIL_L, FR_OIL_C) VALUES ".implode(',', $oil_data);
$result = mysql_query( $sql);
}
}
?>

Categories