MySQL: Insert if this ip dont have any records - php

I use:
INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section',
'{$_SERVER['REMOTE_ADDR']}');";
I would like to add an if condition in the IF statement so that.
IF SELECT ip from rating
where ip={$_SERVER['REMOTE_ADDR']} AND section=$section AND name=$name
then update ELSE INSERT new row
is it doable or I better code it in php ?
thank you very much
P.s: I know how to do it with php, I want to learn it with MySQL.
Also i require that all 3 name,section,ip matchs not only ip

Assuming you have a unique constraint (UNIQUE index or PRIMARY KEY) on ip, section and name, you can use this syntax:
INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '{$_SESSION['user']}', '$rate', '$section', '{$_SERVER['REMOTE_ADDR']}')
ON DUPLICATE KEY UPDATE user = VALUES(user), rating = VALUES(rating);

To expand on Eric's excellent answer.
To add a unique constraint on each of the columns ip, name, section run the following code on the database
ALTER TABLE `test`.`rating`
ADD UNIQUE INDEX `name`(`name`),
ADD UNIQUE INDEX `section`(`section`),
ADD UNIQUE INDEX `ip`(`ip`);
To run a unique constraint on the combination of columns ip+name+section do:
ALTER TABLE `test`.`rating`
ADD UNIQUE INDEX `name_section_ip`(`name`, `section`, `ip`);
The last thing is probably what you want.
One last thing
I'm not 100% sure, but this usage of {$_SERVER['REMOTE_ADDR']} in the query does not look SQL-injection safe.
Consider changing it into:
$remote_adr = mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
$session = mysql_real_escape_string($_SESSION['user']);
$query = "INSERT INTO `rating` (`name`, `user`, `rating`, `section`, `ip`)
VALUES ('$name', '$session', '$rate', '$section','$remote_adr')";
Finally putting a ";" in a mysql_query() like so mysql_query("select * from x;"); does not work mysql_query() will only ever execute one query and will reject your ;.

Related

How to replace some values if a user already exists?

I don't know how to replace some data if a "user" already exists.
I've tried ON DUPLICATE KEY UPDATE but I came to realize that this will probably not work. Because the only value that isn't updated is 'user' in my code but the other 3 values are constantly updated every 5 minutes.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES ('$Name'), world = VALUES ('$World'), status = VALUES ('$status')
The idea is if, for example, user "bob" already exists update his other 3 values bot, world, status, instead of creating a new line and so on.
Edit: this is how I have it setup in Mysql
The argument to VALUES() should be the name of a column, not a string. You put the name of the column that you would have inserted into.
INSERT INTO online ( `user`, `bot`, `world`, `status` ) VALUES ('$User', '$Name', '$World', '$status')
ON DUPLICATE KEY UPDATE bot = VALUES (bot), world = VALUES (world), status = VALUES (status)

Can I put a SELECT query into the IF statement in MySQL?

Well, I am getting some values from the main table say MTB and summarising it in some another table say STB using this script. There is no Unique or Primary key so I can't use ON DUPLICATE KEY situation here.
What I want to do is if the node name) fetched from the MTB Already exists in the STB Then I just want to update it and if the node name from MTB does not exist in the STB then I want to insert the data into the table.
I tried using the If case by first selecting the row in the STB using the nodename fetched from the MTB that if the nodename from the MTB is present in STB (i.e Select query IS NOT NULL) then We Update it else We insert it.
However, this fails to work. Kindly suggest that what I have done wrong.
IF (SELECT * FROM `NodesInfo` WHERE `Nodename` = '".$row2['nodeName']."') IS NOT NULL
THEN
UPDATE `NodesInfo` SET `Time Stamp`= '".$row2['timeStamp']."',`Status`= '$status' WHERE `Nodename` = '".$row2['nodeName']."'
ELSE
INSERT INTO `NodesInfo`(`Nodename`, `Category`, `Time Stamp`, `Type`, `Status`) VALUES ('".$row2['nodeName']."','NodeMCUMQTTData','".$row2['timeStamp']."','$type','$status')
END IF
Just look at the following code, it works.
For MYSQL :
$qry = mysqli_query(<set your db connection variable>, "SELECT * FROM `NodesInfo` WHERE nodeName` = '".$row2['nodeName']."' ");
$res = mysqli_num_rows($qry);
if($res > 0)
{
$update_qry = mysqli_query(<set your db connection variable>, "UPDATE `NodesInfo` SET `Time Stamp`= '".$row2['timeStamp']."',`Status`= '$status' WHERE nodeName` = '".$row2['nodeName']."'");
}
else
{
$insert_qry = mysqli_query(<set your db connection variable>, "INSERT INTO `NodesInfo`(`Nodename`, `Category`, `Time Stamp`, `Type`, `Status`) VALUES ('".$row2['nodeName']."','NodeMCUMQTTData','".$row2['timeStamp']."','$type','$status')");
}
IF exists(SELECT * FROM `NodesInfo` WHERE nodeName` = '".$row2['nodeName']."')
THEN
UPDATE `NodesInfo` SET `Time Stamp`= '".$row2['timeStamp']."',`Status`= '$status' WHERE nodeName` = '".$row2['nodeName']."'
ELSE
INSERT INTO `NodesInfo`(`Nodename`, `Category`, `Time Stamp`, `Type`, `Status`) VALUES ('".$row2['nodeName']."','NodeMCUMQTTData','".$row2['timeStamp']."','$type','$status')
END IF
It seems you want to update nodeName if it already exits otherwise inserts a new entry.
To achieve this, you can make your nodeName field unique.
ALTER TABLE `NodesInfo` ADD UNIQUE INDEX `idx_nodeName` (`nodeName`);
Now you can try ON DUPLICATE KEY UPDATE
INSERT INTO `NodesInfo`(`Nodename`, `Category`, `Time Stamp`, `Type`, `Status`) VALUES ('".$row2['nodeName']."',
'NodeMCUMQTTData',
'".$row2['timeStamp']."',
'$type','$status'
)
ON DUPLICATE KEY UPDATE
`Time Stamp`= '".$row2['timeStamp']."',
`Status`= '$status';

ON Duplicate Key update doesn't work

I have used the following code to Insert/update MySQL table but its not doing anything when duplicate record exists I used ON Duplicate Key update. the code works great to insert but i want to update if description is differ from the source so i added this ON DUPLICATE KEY UPDATE PURCHASE_DESCRIPTION = VALUES ('$pdesc')" but it not inserting also not updating
mysqli_query($con,
"INSERT INTO table_name
(STOCK_NO, PURCHASE_DESCRIPTION, SALES_DESCRIPTION, itemId, itype, ITEM_DESCRIPTION, uOfM, uConvFact, poUOfM, lead, suplId, suplProdCode, minLvl, maxLvl, ordLvl, ordQty, unitWgt, sales, bomRev, makebuy) VALUES
('{$itemid}', '{$pdesc}', '{$sdesc}', '{$itemId}', '{$itype}', '{$itemdsc}', '{$uOfM}', '{$uConvFact}', '{$poUOfM}', '{$lead}', '{$supplId}', '{$suplProdCode}', '{$minLvl}', '{$maxLvl}', '{$ordLvl}', '{$ordQty}', '{$unitWgt}', '{$sales}', '{$bomRev}', '{$makebuy}')
ON DUPLICATE KEY UPDATE PURCHASE_DESCRIPTION = VALUES ('$pdesc')"
);
//STOCK_NO is the primary Key
Your SQL is incorrect. Take a look:
mysqli_query($con,
"INSERT INTO table_name
(STOCK_NO, PURCHASE_DESCRIPTION, SALES_DESCRIPTION, itemId, itype, ITEM_DESCRIPTION, uOfM, uConvFact, poUOfM, lead, suplId, suplProdCode, minLvl, maxLvl, ordLvl, ordQty, unitWgt, sales, bomRev, makebuy) VALUES
('{$itemid}', '{$pdesc}', '{$sdesc}', '{$itemId}', '{$itype}', '{$itemdsc}', '{$uOfM}', '{$uConvFact}', '{$poUOfM}', '{$lead}', '{$supplId}', '{$suplProdCode}', '{$minLvl}', '{$maxLvl}', '{$ordLvl}', '{$ordQty}', '{$unitWgt}', '{$sales}', '{$bomRev}', '{$makebuy}')
ON DUPLICATE KEY
-- HERE --
UPDATE PURCHASE_DESCRIPTION = '{$pdesc}'
");
Another option is UPDATE PURCHASE_DESCRIPTION = VALUES(PURCHASE_DESCRIPTION)
You can read more here: http://dev.mysql.com/doc/refman/5.7/en/insert-on-duplicate.html

Auto increment id

This is query where i want to insert new data to database. Before this id is auto by using old system and now i make a new form by php. This is my query and now i want make auto increment id.How to make a auto increment id.Please Help me if anyone know.
$sql="INSERT INTO $tbl_name(id, name, icno, email, applyIntake_id, modeOfStudy_id,
choice1_id, dob, nationalityType, gender_id, race_id, highestEducation_id,
address1, address2, postcode, city, state_id, permanent_address1,
permanent_address2, permanent_postcode, permanent_city, permanent_state,
telephoneNo, mobileNo)
VALUES('$name', '$icno', '$email', '$id', '$applyIntake_id', '$modeOfStudy_id',
'$choice1_id', '$dob', '$nationalityType', '$gender_id', '$race_id',
'$highestEducation_id', '$address1', '$address2', '$postcode', '$city',
'$state_id', '$permanent_address1', '$permanent_address2',
'$permanent_postcode', '$permanent_city', '$permanent_state',
'$telephoneNo', '$mobileNo')";
$result=mysql_query($sql);
Try this for MYSQL DB..
ALTER TABLE
`TABLE_SCHEMA`.`TABLE_NAME`
CHANGE COLUMN
`ID` `ID` INT(6) NOT NULL
AUTO_INCREMENT;
Ok, one thing first: you should escape your parameters! See here.
To solve your problem: you can define a field in the database as auto_increment, what will automatically increment the id if left empty.
Amir you have 3 errors in above insert.
The columns count match but you try to insert into #tbl_name(email) value of $id
Please set the id field as autoincrement the answer is in above posts.
I think when preparing PHP $sql variable you have to use "." as string operator to get proper SQL INSERT statement with data from your variables - currently the below INSERT will insert instead of your name variable $name as string into DB.
Exmaple :
$name = 'Tom';
$email = 'tom#o2.pl'
$sql = "insert into table(name,email) VALUES (".$name.",".$email.");";
Then use following insert but apply the example of string join above - it should work:
$sql="INSERT INTO $tbl_name(name, icno, email, applyIntake_id, modeOfStudy_id,
choice1_id, dob, nationalityType, gender_id, race_id, highestEducation_id,
address1, address2, postcode, city, state_id, permanent_address1,
permanent_address2, permanent_postcode, permanent_city, permanent_state,
telephoneNo, mobileNo)
VALUES('$name', '$icno', '$email', '$applyIntake_id', '$modeOfStudy_id',
'$choice1_id', '$dob', '$nationalityType', '$gender_id', '$race_id',
'$highestEducation_id', '$address1', '$address2', '$postcode', '$city',
'$state_id', '$permanent_address1', '$permanent_address2',
'$permanent_postcode', '$permanent_city', '$permanent_state',
'$telephoneNo', '$mobileNo')";
$result=mysql_query($sql);
ALTER TABLE document MODIFY COLUMN document_id INT AUTO_INCREMENT;
There are a couple of reasons that your SQL might not work. First, you must re-specify the data type (INT in this case). Also, the column you are trying to alter must be indexed (it does not have to be the primary key, but usually that is what you would want). Furthermore, there can only be one AUTO_INCREMENT column for each table. So, you may wish to run the following SQL (if your column is not indexed):
ALTER TABLE document MODIFY document_id INT AUTO_INCREMENT PRIMARY KEY;
You can find more information in the MySQL documentation: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html for the modify column syntax and http://dev.mysql.com/doc/refman/5.1/en/create-table.html for more information about specifying columns.

mysql table createing new row instead of updating

Instead of finding that a row exists where 'bookName' equals 'bookName' and just updating, it creates a brand new row. What is wrong with my command? thanks!
$query = mysql_query(
"INSERT INTO custombookinfo (userId, sendToAddress, work, caseStudies, url, entryPoint, date, bookName)
VALUES ('$userId', '$emailAddress', '$work', '$caseStudies', '$url', '$entryPoint', '$date', '$bookName')
ON DUPLICATE KEY UPDATE bookName = 'bookName'"
);
the INSERT query is correct but I think you have failed to define UNIQUE constraint on column bookName. Execute the following statement:
ALTER TABLE custombookinfo ADD CONSTRAINT tb_uq UNIQUE (bookName);
Depending on what you want to be UNIQUE in the table, you should create an index (PRIMARY or UNIQUE) for whether user_id, or bookName.
More details about INSERT ... ON DUPLICATE KEY UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html

Categories