UPDATE specific fields in mysql php - php

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

Related

get values from database and work on them

<?php
include('connection.php');
/* code for id goes here */
$q2= "select MAX(id) from usertable";
echo mysqli_query($sql,$q2);
$name=$_POST['name'];
$username=$_POST['usrname'];
$password=$_POST['psw'];
$dob=$_POST['date'];
$query="insert into usertable(name, username, password, dateofbirth) values('$name', '$username','$password','$dob')";
if(mysqli_query($sql,$query))
{
echo "Registered successfully";
}
?>
This is my insert command to register a user in my database. However the database contains a column named id which is the primary key. How do I fetch the id before executing the insert query so that it fetches the last id and increments it by 1 and inserts it in the db along with the other data. The id is numeric and I want the program to perform the operation itself rather than the user entering the data of the id. Please help.
You need to set your id field to auto incement and your database will do it automatically:
ALTER TABLE usertable MODIFY COLUMN id INT auto_increment;
You need to write a query
SELECT MAX(id) FROM usertable
and get the result from that and then increment that value by 1 and then set that value in id field.

PHP & MYSQL -- dont insert same data

I need your help. I’m stuck at a point from where I can’t figure it out that how to stop a product to be booked twice a day on a web form.
I have 41 products to rent out on daily basis.
My problem is: if a client books a product #4 (pg_no) and date 26-06-2017 then another client isn't able to book the same product for the same period of time.
If a client selects the same product and date, then a message should appear saying "already booked - please select another date"
Also, do I have to define anything on database level?
Your help will be highly appreciated.
Please note: this rule is only for product # (pg_no) and date fields are not allow for the same day.
<?php
//connecting string
include("dbconnect.php");
//assigning
$pg_no=$_REQUEST['pg_no'];
$name=$_REQUEST['Name'];
$tele=$_REQUEST['Tele'];
$city=$_REQUEST['City'];
$date=$_REQUEST['Date'];
//checking if pg_no and Date are same
$check=mysqli_query($db_connect,"SELECT * FROM lstclient WHERE pg_no='{$pg_no}', Date='{$date}'");
if(mysqli_fetch_row($check) ==0)
{
echo "Already booked please select another date<br/>";
}
//if not the insert data
else
{
$query=mysqli_query($db_connect,"INSERT INTO lstclient(pg_no,Name,Tele,City,Date) VALUES('$pg_no','$name','$tele','$city','$date')") or die(mysql_error());
}
mysqli_close($db_connect);
// messaging
if($query)
{
header("location:index.php?note=failed");
}
else
{
header("location:index.php?note=success");
}
?>
Create a UNIQUE KEY constraint on your table between the two columns.
ALTER TABLE lstclient ADD CONSTRAINT `pg_no_date` UNIQUE (pg_no, date)
Then when you try to insert a row that violates this constraint mysql will throw an error. You should catch this MySQL error and respond with the correct error.
if( mysqli_errno() == 1062) {
// Duplicate key error
}
Add a unique key to your lstclient table like ryan suggested. Also, your check query has syntax error, it should be like below.
SELECT * FROM lstclient WHERE pg_no='{$pg_no}' AND Date='{$date}'

how to remove data duplicacy in customer table

i have a table customer_stock_entries.. i want to insert the item if the item and supplier is not available and i want to update the item if item and supplier is available
Example in my table i have stock_supplier_name and quantity. What i want to do is that if the stock supplier name entry is new then insert it into the table and if the entry is already there then delete the previous value in column 'quantity' and insert the new value.
i am stuck with this. Please help me out
I have tried something like this.
for ($i = 0; $i < count($stock_name); $i++) {
$count = $db->countOf("customer_stock", "name='$stock_name[$i]'");
if ($count == 0) {
$db->query("insert into customer_stock(name,quantity) values('$stock_name[$i]',$quty[$i])");
echo "<br><font color=green size=+1 >New Stock Entry Inserted !</font>";
$db->query("insert into stock_details(stock_id,stock_name,stock_quatity,supplier_id,company_price,selling_price) values('$autoid','$stock_name[$i]',0,'$supplier','$cost[$i]','$sell[$i]')");
$db->query("INSERT INTO customer_stock_entries(stock_id,stock_name, stock_supplier_name, quantity, company_price, selling_price, opening_stock, closing_stock, date, username, type, total, payment, balance, mode, description, due, subtotal,count1,billnumber) VALUES ( '$autoid1','$stock_name[$i]','$supplier','$quty[$i]','$cost[$i]','$sell[$i]',0,'$quty[$i]','$date','$username','entry','$total[$i]','$payment','$balance','$mode','$description','$due','$subtotal',$i+1,'$bill_no')");
} else if ($count == 1) {
$amount = $db->queryUniqueValue("SELECT quantity FROM customer_stock WHERE name='$stock_name[$i]'");
$amount1 = $amount + $quty[$i];
$db->execute("UPDATE customer_stock SET quantity='$amount' WHERE name='$stock_name[$i]'");
$db->query("INSERT INTO customer_stock_entries(stock_id,stock_name,stock_supplier_name,quantity,company_price,selling_price,opening_stock,closing_stock,date,username,type,total,payment,balance,mode,description,due,subtotal,count1,billnumber) VALUES ('$autoid1','$stock_name[$i]','$supplier','$quty[$i]','$cost[$i]','$sell[$i]','$amount','$amount1','$date','$username','entry','$total[$i]','$payment','$balance','$mode','$description','$due','$subtotal',$i+1,'$bill_no')");
Thanks
Typical solution to this problem involve following typical steps:
Check if the record for the stock supplier exists by using a select query and if it exists, update the quantity attribute.
If the the record doesn't exist, then insert the record in the table.
Sample Code as requested:
IF EXISTS(SELECT * FROM Users WHERE UserId = #UserId)
BEGIN
UPDATE TC_Users SET Salary = 25000 WHERE UserId = #UserId
END
ELSE
BEGIN
INSERT INTO TC_Users(UserId, Salary) VALUES(#UserId, 25000)
END
Hope this helps you.
Hare are some information's regarding your problem:
Primary Keys (To Avoid Duplication Of Data) :
Always use primary keys in your Database Table Structure i.e consider one column as primary key in order for it to be unique so that duplicate value won't be able to be inserted in your records.
Example : For instance I have a table with following columns as id,username,password,name .Now in order for to avoid duplication of data i.e that I don't want people to register with same username which means that username column value should be unique so instead I mark my username column as Primary Key.So now the new upcoming members won't be able to register with the same username which is already available in database i.e someone already registered using that username.Instead they will be needed to register with unique username.
Solution :
While here is code for to update your quantity value if supplier is already present in the database and if not so then insert the new record..!
$supplier_name = $_POST['supplier];
$query = mysqli_query($mysqli,"SELECT * FROM table");
$results = mysqli_fetch_array($query);
for ($i=0;$i<=count($results);$i++) {
//IF supplier is available in database
if ($results[$i]['supplier'] == $supplier_name) {
$query = mysqli_query($mysqli,"UPDATE table SET quantity=$quanity_new_value WHERE supplier=$supplier_name");
} else {
// If supplier is not available in database so it will insert new record
$query = mysqli_query($mysqli,"INSERT INTO table (supplier, quanity, email) VALUES ($supplier_name, $quantity, $email)");
}
}

prevent duplicate records in mysql table

Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.

import data from one table and insert it into another

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 */
?>

Categories