I am working on a MySQL query to check duplicate values from table using MySQL and PHP. Let me to explain my table structure and conditions.
db_product_info
pro_id product_name product_code status
The above are my columns in db_product_info table.
conditions:
1-> When table has no value the data should entry in table.
2-> In same product name only same product code will be inserted for once/multiple time in table.If input will different code for same product name (for more than one entry) it should be checked and return the validation message.
3- Duplicate of product_code will be checked according to the product_name as explained above.means for same product_name only same product_code should entry multiple time but this product_code should not used for any other product_name .
Let me show my code below.
require_once("../include/dbconfig.php");
$result=array();
$fields=array("Product_name","status","product_code");
$tablename=PREFIX."product_info";
$values=array($_POST['product_name'],$_POST['status'],$_POST['product_code']);
$id=db_insert($tablename,$values,$fields);
if($id){
$result[0]["msg"]="Added successfully";
$result[0]['id']=$id;
echo json_encode($result);
}else{
header("HTTP/1.0 401 Unauthorized");
$result[0]["msg"]="Unable to add try again";
$result[0]["data"]=$values;
echo json_encode($result);
}
How can I resolve this problem?
Related
Table Product
pid product_name
Table Category
cid category_name
Table Product_category
cid pid
For table Product and Category, their primary keys are "pid and cid" with auto_increment
For product_category table, its used to store the data where 1 product is assigned to multiple categories and thats why the table columns are "cid and pid"
I am using php+mysql to write some functions like creating new product, category and then assign product to one or multiple categories.
Assume that we have created a 2 categories with cid-> 1,2
3 steps to assign product to category
add new product so that we have pid->123
then assign this product into category cid->1
insert into database table Product_category with pid->123 and cid->1
I want to do something simple like this instead
1. add new product and assign this product to category at the same time
However, for Table Product_category, it needs 2 value which are pid and cid , so that means we only know this pid after creating new product as its auto_increment. So my question is how to know this pid when adding new product? OR its impossible to do it this way?
public function conn(){
$this->db_host="localhost";
$this->db_name="bs";
$this->db_user_name="root";
$this->db_pass="";
return mysqli_connect($this->db_host, $this->db_user_name, $this->db_pass, $this->db_name);
}
$query = "INSERT item(uid,item_id,item_name,item_price,item_quantity)
VALUES('$this->user_uid','$this->item_id','$this->item_name','$this->item_price','$this->item_quantity')";
if (!mysqli_query($this->conn(), $query)) {
echo "Failed to Add item!" . mysqli_error($query);
return false;
}else{
printf("Last inserted record has id %d\n", mysqli_insert_id($this->conn()));
return true;
}
I try to test by adding new records, but it always get this
"Last inserted record has id 0"
The cause of your mistake is the method conn. Because you create a new connection for every call $this->conn(). A new connection doesn't know anything about INSERT statement that was performed in previous connection that is why mysqli_insert_id returns 0. A quick solution is to define a new var $conn = $this->conn(); and use this one in all queries.
I think your SQL required mysql_last_id so it should be like this
INSERT INTO Product VALUES(null, product_name);
$product_last_id = LAST_INSERT_ID();
INSERT INTO Category VALUES($product_last_id, category_name);
$category_last_id = LAST_INSERT_ID();
INSERT INTO Product_category VALUES($product_last_id, $category_last_id);
Have a look at LAST_INSERT_ID().
You need to set 2 database call first is product table. Insert a product. Then you will get the return value as pid, and I think you will get the cid from the page itself. You will select the option the new products belongs to which category then you can pass the cid. Then you can set the second database call insertProduct_categoryTable(cid,pid).
I have 4 mySQL tables with the following entries:
user
-user_id PK,AI
-user_name
-user_mobil
-user_passw
-user_email
bookingdetails
-booking_id PK,AI
-booking_date
-booking_time
-person_number
booking
-booking-_id FK
-restaurant_id CK
-user_id CK
restaurant
-restaurant_id PK
-restaurant_name
-restaurant_address
-restaurant_description
I would like to make a booking, I insert all the bookingdetails data, which gives me a AI booking_id, and after I would like to make my booking table and insert the restaurant_id and the user_id With the same booking_id which was given by the bookingdetails table.
I made the following code for achieve that in php on a localserver:
$booking_date=$_POST["booking_date"];
$booking_time=$_POST["booking_time"];
$number_of_place=$_POST["number_of_place"];
$customer_id=$_POST["customer_id"];
$restaurant_id=$_POST["restaurant_id"];
$res;
$sql_query = "INSERT INTO bookingdetails(booking_date, booking_time, number_of_place) VALUES ('$booking_date','$booking_time', '$number_of_place')";
$sql_query2 = "INSERT INTO `booking`(`booking_id`, `customer_id`, `restaurant_id`) SELECT booking_id, '$customer_id', '$restaurant_id' FROM bookingdetails ORDER BY booking_id DESC LIMIT 1 ;";
if(mysqli_query($con,$sql_query))
{
}
else
{
}
if(mysqli_query($con,$sql_query2))
{
}
else
{
}
?>
Is that a legit solution on a server which joining to an Android app? Is there any case, that i don't get the good id on the second query? What would be a better solution?
Answer given in comment by #Mark Ng
Use last insert id, criteria is that your pk has to be AI.
The mysqli_insert_id() function returns the id (generated with AUTO_INCREMENT) used in the last query.
Source: w3schools.com/php/php_mysql_insert_lastid.asp
To elaborate
you have to execute the query from which you need the last inserted id, then you can access that by using
$last_id = $conn->insert_id;
which in turn you can use for your following query.
Note:
I see you use a query to use the results for your insert query, but your syntax is incorrect (your missing values)
I've got 2 tables :
jos_tempcsv, which contains among others the following field: Category of goods
jos_categories, which contains among others the following fields: Category_id, slug
I would like to create the following query:
I've got a table called jos_tempcsv which contains a field called Category of goods. This field contains alphanumeric values that needs to be changed in a numeric value.
I need to compare the value of the Category of goods field of the jos_tempcsv table with the value of the slug field of the jos_categories table.
If comparison matches, then I would like to insert the value contained in the Category_id field of the jos_categories table into the Category of goods field of the jos_tempcsv table (it should overwrite the initial value with a numeric value).
Find a solution which works, record are updated|overwritten :
$sql = "update jos_tempcsv u left join jos_virtuemart_categories_fr_fr c on c.slug=u.`Category of goods` set u.`Category of goods`=c.virtuemart_category_id;
if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
Thank you to #PRANAV and a special thanks to #Abdulla which has a great sens of humor
I have two tables product_myob and products. What I want to do is to import products from product_myob when the import button is clicked to table products. Table products already contains some products.
I try to execute below query but the table is not updated. Please help me with the code.
INSERT INTO products(myob_id, myob_displayID, Name)
SELECT UID,displayID,itemName
FROM product_myob
WHERE UID NOT IN (SELECT myob_id from products);
It seems there is a unique check on your products table and you are inserting some duplicate data if this is the case then you can ignore duplicate values by below query, even you don't need to check UID in product table as this query automatically ignore it. Other wise elaborate your question:
INSERT ignore INTO products(myob_id, myob_displayID, Name)
(SELECT UID,displayID,itemName
FROM product_myob);
This is a sample code that you can use. Using MySQLi though because MySQL is deprecated already.
<?php
/* ESTABLISH CONNECTION AND CHANGE THE NECESSARY HOST, USERNAME, PASSWORD AND DATABASE */
$connection=mysqli_connect("YourHost","YourUsername","YourPassword","YourDatabase");
if(mysqli_connect_errno()){
echo "Error".mysqli_connect_error();
}
$result=mysqli_query($connection,"SELECT * FROM product_myob");
while($row=mysqli_fetch_array($result)){
$myobid=mysqli_real_escape_string($con,$row['UID']);
$myobdisplayid=mysqli_real_escape_string($con,$row['displayID']);
$name=mysqli_real_escape_string($con,$row['itemName']);
/* CHECK IF DATA IS ALREADY IN THE products TABLE */
$result2=mysqli_query($connection,"SELECT * FROM products WHERE myob_id='$myobid' AND myob_displayID='$myobdisplayid' AND Name='$name'");
if(mysqli_num_rows($result2)==0){
mysqli_query($connection,"INSERT INTO products (myob_id, myob_displayID, Name) VALUES ('$myobid','$myobdisplayid','$name')");
} /* END OF IF MYSQLI_NUM_ROWS($RESULT2) IS 0 */
else {
echo "Data has already been inserted before.<br>";
}
} /* END OF WHILE LOOP RESULT */
?>
I've a table in MySQL named product where fields are set as below..
id int(3) NOT NULL AUTO_INCREMENT,
nm varchar(255),
category varchar(255),
price int(4)
when i insert a new product then I've put some code to check duplication as below.
select nm,category from product where nm='".$pnm."' AND category='".$cat."'
If there is any row then code will not insert that record in database...(problem starts now)
same condition I've set during update..
if user edit that product and change name or category which is already in database then it'll return false and exit the code..
now if i want to just update price then name and category will be same then what to do???
please give your best ! !
Thank you friends
You can do it by using unique id..First check for duplication while updating and if duplication occurs then only update other fields except name and category else update all the fields which are going to be changed.
I give you demo.Make changes according to your requirement like field name,table name and all that.
$sql="select * from product where nm='".$_REQUEST['name']."'" or category='".$_REQUEST['category']."';
$query=mysql_query($sql);
if(mysql_num_rows($query)>0)
{
while($row=mysql_fetch_array($query))
{
$id=$row['id'];
if(isset($_REQUEST['price']))
{
$sql="update product set price='".$_REQUEST['price']."' where id='$id'";
$query=mysql_query($sql);
}
}
}
else
{
$sql="update product set nm='".$_REQUEST['name']."',category='".$_REQUEST['category']."',price='".$_REQUEST['price']."' where id='$id'";
$query=mysql_query($sql);
}
Two step solution:
- Create a UNIQUE index
- Use INSERT IGNORE and UPDATE IGNORE instead of INSERT and UPDATE