I have a table with (id, stock_code, batch_code, qty).
id is primary key and auto increment value.
stock_code and batch_code is combine unique. Now I want update in insert query when stock_code and batch_code is duplicate
example
id stock_code batch_code qty
1 r001 b001 100
2 roo1 b002 100 //it should be insert
3 roo1 boo1 120 //it should be update in first row
4 roo2 boo1 130 //it should be insert
5 roo1 boo2 289 //it should be update in second row
$stockcode = "some value";
$batchcode="some value";
$qty = some value;
$con=mysqli_connect("localhost","my_user","my_password","my_db");
$query22 = "select * from table where stock_code= '".$stockcode."' and batch_code='".$batchcode."'";
$result22 = mysqli_query($con,$query22) or die (mysqli_error());
$num22 = mysqli_num_rows($con,$result22);
if($num22 > 0) {
$query222 = "update table set qty='".$qty."' where stock_code= '".$stockcode."' and batch_code='".$batchcode."'";
$result222 = mysqli_query($con,$query222) or die (mysqli_error($con));
}
else {
$query222 = "insert into table(stock_code, batch_code, qty) values('".$stockcode."','".$batchcode."','".$qty."') ";
$result222 = mysqli_query($con,$query222) or die (mysqli_error($con));
}
Try use
ON DUPLICATE KEY UPDATE
You can read the reff here http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
You are looking for INSERT ON DUPLICATE KEY UPDATEhttp://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
Related
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.
I want to get ids in my table then update
id row is auto increment
if (isset($_POST['reply'])) {
$reply = $_POST['reply'];
$answers = $db->query("SELECT * FROM table_name");
while($answers_ = $answers->fetch_object()){
if($get_answer = $db->query("UPDATE table_name SET answer ='$reply' WHERE question_id = '$answers_->question_id' LIMIT 1")){
echo "done";
}
}
}
I know my code is wrong its update all rows with the same value i want to update only one row
use mysqli_insert_id() — Returns the auto generated id used in the last queryn
$get_answer = $db->query("UPDATE table_name SET answer ='$reply' WHERE question_id = '$answers_->question_id' LIMIT 1")
$last_id = mysql_insert_id();
I need Auto generated sequence number staring from 001 ONLY FOR 3 DIGITS in PHP / MYSQL
ex: 001 next will be 002 and next will be 003 ... 009 .. 010 ..119..120..etc but number generated should be in sequence wise not like 001 then 120 or 008 etc , i need in sequence number.
actually i have product tracking system . where i need mixer of my main product id + auto sequence number ( only 3 digit can change if wanted ) hence my final product id becomes :
111-001 , 111-002 , 111-003 , 111-004 ....etc
Note: this auto sequence number will be insert in my mysql database ( after ADD button follows by Update query ( hence my auto sequence will be enter in database with Update query ))
Just add the length 3 and zerofill to your id column.
ALTER TABLE `YOUR_TABLE` CHANGE
`id_column` `id_column` INT( 3 ) UNSIGNED ZEROFILL NOT NULL AUTO_INCREMENT
This should work for you with slight modifications to fit ur requirement
<?php
$connection = mysql_connect("localhost","root","")
or die("no connection");
$db_select=mysql_select_db("test",$connection)
or die("no connection to db");
$query3 = "SELECT * FROM simple";
$result3 = mysql_query($query3);
$count = mysql_num_rows($result3);
if($count == 0)
{
$seq = 1;
$ref = 111;
$a = sprintf("%04d", $seq);
$emp_id = $ref.'-'.$a;
$query= "INSERT INTO simple (emp_id) VALUES ('$emp_id')";
$result=mysql_query($query)or die(mysql_error());
}
else
{
$query2 = "SELECT * FROM simple ORDER BY id DESC LIMIT 1";
$result2 = mysql_query($query2);
$row = mysql_fetch_array($result2);
$last_id = $row['emp_id'];
$rest = substr("$last_id", -4);
$insert_id = "$rest" + 1;
echo $ars = sprintf("%04d", $insert_id);
$ref = 111;
$emp_id = $ref.'-'.$ars;
$query= "INSERT INTO simple (emp_id) VALUES ('$emp_id')";
$result=mysql_query($query)or die(mysql_error());
}
Try this code:
$maxDigit=5; //maximum digit of ur number
$currentNumber=0020; //example this is your last number in database all we need to do is remove the zero before the number . i dont know how to remove it
$count=strlen($currentNumber); //count the digit of number. example we already removed the zero before the number. the answer here is 2
$numZero="";
for($count;$count<=$maxDigit;$count++)
$numZero=$numZero+"0";
$newNum=$newNum+$currentNumber;
Output :00020
I am trying to write data from an invoice into 2 tables
table 1 is the invoices table
it contains:
invoice_id account sales purchase_date
then a second table invoice_items it contains the information about each line in the invoice.
id invoice_id item description quantity price amount
Basically now I am checking to see if the id exists and if it does I check if the line id exists and if it doesn't it adds the information for the invoice if the id exists it checks to see if the line id exists
$checkin = mysql_query("
SELECT `id`
FROM `invoices`
WHERE `invoices`.`id` =$invoice_id
");
if (mysql_num_rows($checkin) == 1)
{
$updatememocount ++;
mysql_query("UPDATE `invoices` SET `invoices`.`INV_ID` = '".$invid."'WHERE `invoices`.`id` =$invoice_id ") or die("load1 -" . mysql_error());
// check line id
$checklineid = mysql_query("SELECT `Line_ID` from `invoice_items` WHERE `Line_ID` = '$lineid'") or die("load1 -" . mysql_error());
if (mysql_num_rows($checklineid) == 0)
{
$insertlinecount ++;
mysql_query("INSERT INTO `invoice_items` (invoice_id, item, description, quantity, price, amount, Line_ID) VALUES ('".$invoice_id."', '".mysql_real_escape_string($row['3'])."', '".mysql_real_escape_string($row['4'])."', '".$row['9']."', '".$row['7']."', '".$row['5']."', '".$row['14']."' ) ") or die("load1 -" . mysql_error());
}
}
else
{
// makes new invoice entry and enters the line item information for the first line.
}
Data sample this is how the data comes in
Date Invoice_Id Item Description Price Amount Customer_ID Line_ID
05/12/12 1234 something whatever somthing is 15 15 2255 123
05/12/12 1234 Another_thing Whatever that is 25 25 2255 124
look this example, on duplicate key insert
<?php
$sql = "SELECT COUNT(UserID) FROM configuration WHERE UserID='SomeUser'";
$result = mysqli_query($db,$sql);
if ($result && mysqli_num_rows($result)>0) {
$aResult = mysqli_fetch_array($result);
$iRecordExists = ($aResult[0]>0?1:0);
}
if ($iRecordExists>0) {
//make the insert with another ID
}
else {
//do an insert
$sql = "INSERT INTO configuration SET someField='someValue', UserID='SomeUser'";
mysqli_query($db,$sql);
}
?>
I have a table whose primary key is a column named St_ID. I want to update another column in that same (ID) using values stored in an array. But when I try the code below, the result is a new record with an St_ID value of '0' and all other columns are empty.
Note, courseID is a value chosen through a drop down list. Do you have any idea where I went wrong?
for ($i = 0; $i < $count; $i++){
$Student = $foo[$i];
$res = mysql_query("SELECT St_ID FROM student WHERE St_ID='$Student' ");
while($row = mysql_fetch_array($res))
{
$sql = "INSERT INTO student (ID) VALUES
('" . $_POST[$row['courseID']] . "')";
}
}
if (!mysql_query($sql,$connectdb))
{
die ('Error :'.mysql_error());
}
echo "The Students are add to the course <br />";
Here simplified code, with only one query
$where = "'".implode("','", $foo)."'";
$res = mysql_query("UPDATE student set ID = courseID WHERE St_ID IN ($where)")
or die('Error :'.mysql_error());
echo "The Students are add to the course <br />";
you select St_ID but try to insert courseID
in this line
$sql = "INSERT INTO student (ID) VALUES
('" . $_POST[$row['courseID']] . "')";
SELECT St_ID FROM student WHERE St_ID='$Student'
INSERT INTO student (ID) VALUES ...
If you want to update that record you chose, you must use the UPDATE sql command instead;
UPDATE student
SET ID=...
WHERE St_ID='$Student'