stop insert dublicate entery in my database - php

we have use this below code to avoid to insert dublicate entery in our databse
but in some case it's not working
$device_id = $_REQUEST['device_id'];
$fcm_id = $_REQUEST['fcm_id'];
$model_number = $_REQUEST['model_number'];
$os_version = $_REQUEST['os_version'];
$app_version = $_REQUEST['app_version'];
$created = round(microtime(true) * 1000);
if(isset($device_id)){
$exist = mysqli_query($con, "SELECT * FROM `user` WHERE `device_id`='$device_id'");
if(mysqli_num_rows($exist)>0){
mysqli_query($con, "UPDATE `user` SET `fcm_id`='$fcm_id', `topics`=0 WHERE `device_id`='$device_id'");
}
else{
mysqli_query($con, "INSERT INTO `user` (`device_id`, `fcm_id`, `model_number`, `os_version`, `created`) VALUES ('".$device_id."', '".$fcm_id."', '".$model_number."', '".$os_version."', '".$created."')");
}

try with this
$device_id = $_REQUEST['device_id'];
$fcm_id = $_REQUEST['fcm_id'];
$model_number = $_REQUEST['model_number'];
$os_version = $_REQUEST['os_version'];
$app_version = $_REQUEST['app_version'];
$created = round(microtime(true) * 1000);
if(isset($device_id))
{
$qry="UPDATE `user` SET `fcm_id`='$fcm_id', `topics`=0 WHERE EXISTS (SELECT * FROM `user` WHERE `device_id`='$device_id')";
if(!mysqli_query($con,$qry)){ mysqli_query($con, "INSERT INTO `user` (`device_id`, `fcm_id`, `model_number`, `os_version`, `created`) VALUES ('".$device_id."', '".$fcm_id."', '".$model_number."', '".$os_version."', '".$created."')");
}

Try this
$device_id = $_REQUEST['device_id'];
$fcm_id = $_REQUEST['fcm_id'];
$model_number = $_REQUEST['model_number'];
$os_version = $_REQUEST['os_version'];
$app_version = $_REQUEST['app_version'];
$created = round(microtime(true) * 1000);
if(isset($device_id)){
$stmt = $con->prepare("INSERT IGNORE INTO `user` (`device_id`, `fcm_id`,
`model_number`, `os_version`, `created`) VALUES (?, ?, ?,?,?)");
$stmt->bind_param($device_id, $fcm_id, $model_number, $os_version, $created );
if ($stmt->execute()) {
}
$stmt->close();
}
Update: Add to your tabekl following index,
But you should think about what you put in the index.
because only when all 4 Columns are identical, no new entry will be crated.
CREATE UNIQUE INDEX idx_insert_user
ON user (`device_id`, `fcm_id`,
`model_number`, `os_version`);
the insert ignore into will not enter duplicates into the table

For stoping the duplicate data on row from mysql database on insert query:
MySQL INSERT IGNORE statement
For update case you need to put your condition for duplicate handling.

Related

How to change from simple mysqli query to prepared statement?

I did 3 queries (SELECT, INSERT, UPDATE) it works but at the current state looks ugly and not safe.
Is there any way to make these SELECT, INSERT, UPDATE queries more readable and safer than this with the prepared statement?
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES ('".$_POST["commentID"]."', '".$_POST["comment"]."', '$username', '$id')";
mysqli_query($connect, $sql) or die("ERROR: ". mysqli_error($connect));
/// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$sql1 = "UPDATE user_comments SET id = id +1 WHERE custom_id = '$id'";
mysqli_query($connect, $sql1) or die("ERROR: ". mysqli_error($connect));
Give this a try. You can use $ex->insert_id to get the last entered ID. This may come in handy when mass inserting into a DB. I generally use PDO as I find the code looks cleaner but it's all preference I suppose. Keep in mind for the ->bind_param line that "isii" is referring to the type(s) of data which you are entering. So, in this case, its Integer, String, Integer, Integer (I may have got this wrong).
$email = $_SESSION['email'];
$query = "SELECT username FROM users WHERE email='$email'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_assoc($result);
$username = $row['username'];
if(!empty($_POST["comment"])){
$id = $_GET['id'];
$commentID = $_POST["commentID"];
$comment = $_POST["comment"];
$sql = "INSERT INTO user_comments (parent_id, comment, username, custom_id) VALUES (?, ?, ?, ?)";
$ex = $connect->prepare($sql);
$ex->bind_param("isii", $commentID, $comment, $username, $id);
if($ex->execute()){
// query success
// I need this update query to make every inserted comment's ID +1 or can I do this more simple?
$lastInsertID = $ex->insert_id;
$sql1 = "UPDATE user_comments SET id = id + 1 WHERE custom_id = ?";
$ex1 = $connect->prepare($sql1);
$ex1->bind_param("i",$lastInsertID);
if($ex1->execute()){
// query success
}else{
// query failed
error_log($connect->error);
}
}else{
//query failed
error_log($connect->error);
}

check user exit in database if yes duplicate key if not insert data in database

i am trying to insert data if user exists in duplicate row if not then insert data in new row i am trying but failed but is problem here please help me
$result = "SELECT * FROM coder WHERE name='".$name."'";
$sql = $conn->query($result);
if ($sql->num_rows > 0) {
$result = mysqli_query("UPDATE coder SET stuts=1 WHERE name='Basic'".$conn);
while($row = mysqli_fetch_array($result)){
echo $row['Name'];
}
} else {
$sql = "INSERT INTO coder (Name, Startdate, Enddate, Users, Documenttype)
VALUES ('$name', '$start', '$end', '$users', '$Documenttype')";
}

Android update MySQL table (Android profile)

I am making profile update Android application. I need assistance to get JSON values, as I am getting null JSON result - can anyone spot a mistake?
Profile Update Response:
{"tag":"profile_update","error":false,"user":{"fname":null,"lname":null,"email":null,"mobile":null,"class":null,"school":null,"uid":null,"profile_pic":null,"created_at":null}}
My PHP code:
public function profileUpdate($fname, $lname, $email, $mobile, $class, $school, $uid, $profile_pic){
$result = mysqli_query($this->con, "SELECT * FROM users WHERE unique_id = '$uid'")
or die(mysqli_error($this->con));
$path = "userImages/$uid.png";
$actual_path = "http://192.168.1.101/cedu/login/$path";
$no_of_rows = mysqli_num_rows($result);
if ($no_of_rows > 0) {
$result = mysqli_fetch_array($result);
$old_email = $result['email'];
$old_profile_pic = $result['profile_pic'];
$status = 0;
$otp = rand(100000, 999999); // otp code
if ($old_email == $email) {
if ($old_profile_pic == $profile_pic){
$result = mysqli_query($this->con, "UPDATE `users` SET `firstname` = '$fname',`lastname` = '$lname', `mobile` = '$mobile',`class` = '$class',`school` = '$school'
WHERE `unique_id` = '$uid'") or die(mysqli_error($this->con));
} else {
$result = mysqli_query($this->con, "UPDATE `users` SET `firstname` = '$fname',`lastname` = '$lname', `mobile` = '$mobile',`class` = '$class',`school` = '$school' , `profile_pic` = '$actual_path'
WHERE `unique_id` = '$uid'") or die(mysqli_error($this->con));
file_put_contents($path, base64_decode($profile_pic));
}
} else {
if ($old_profile_pic == $profile_pic){
$result = mysqli_query($this->con, "UPDATE `users` SET `firstname` = '$fname',`lastname` = '$lname', `email` = '$email', `mobile` = '$mobile',`class` = '$class',`school` = '$school' , `otp` = '$otp', `verified` = '$status'
WHERE `unique_id` = '$uid'") or die(mysqli_error($this->con));
} else {
$result = mysqli_query($this->con, "UPDATE `users` SET `firstname` = '$fname',`lastname` = '$lname', `email` = '$email', `mobile` = '$mobile',`class` = '$class',`school` = '$school' , `profile_pic` = '$actual_path', `otp` = '$otp', `verified` = '$status'
WHERE `unique_id` = '$uid'") or die(mysqli_error($this->con));
file_put_contents($path."user".$uid.".jpg", base64_decode($profile_pic));
}
}
} else {
//
return false;
}
}
I don't know if this relates to your problem, but you might as well change your potentially vulnerable code first, since any bug tracing you do beferehand may need to be done again. Your code is likely to be susceptible to SQL injection. I will add a (non-tested) example below, and you will need to:
understand it
make similar changes across the rest of your application
Here is a statement that is likely to be vulnerable: you're injecting what looks like user input directly into a SQL string:
$result = mysqli_query(
$this->con,
"SELECT * FROM users WHERE unique_id = '$uid'"
) or die(mysqli_error($this->con));
So firstly let's change this to use explicit column names, and to bind:
$statement = mysqli_prepare(
$this->con,
"SELECT email, profile_pic FROM users WHERE unique_id = ?"
) or die(mysqli_error($this->con));
mysqli_stmt_bind_param($statement, "i", $uid);
mysqli_stmt_execute($statement);
mysqli_stmt_bind_result($statement, $email, $profile_pic);
What's happening here?
We bind an input variable using the i type, which specifies that it is an integer
We run the query using the mysqli_stmt_execute method
We bind a list of output variables, corresponding to each item in the SELECT list
All of the MySQLi "statement" methods are documented here in the PHP manual, and all have very good examples. Do please read up on each of the methods I've used - the manual is one of the best things about PHP!
Stack Overflow also has a set of definitive answers on SQL injection - there are resources there for both PDO and MySQLi.
Once you have made these changes, I recommend stepping through your code, one line at a time, to check that the intermediate values you get are what you expect.

updating the data using implode in php

please help me out and sorry for my bad English,
I have fetch data , on basis of that data I want to update the rows,
Follows my code
I fetched data to connect API parameters
<?php
$stmt = $db->stmt_init();
/* publish store for icube*/
$stmt->prepare( "SELECT id,offer_id,name,net_provider,date,visible,apikey,networkid FROM " ."affilate_offer_findall_icube WHERE visible='1' ");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result( $id, $offer_id, $name, $net_provider, $date, $visible,$apikey,$networkid);
$sql = array();
if($rows>0)
{
while($info = $stmt->fetch() ) {
$jsondataicube = file_get_contents('filename/json?NetworkId='.$networkid.'&Target=Affiliate_Offer&Method=getThumbnail&api_key='.$apikey.'&ids%5B%5D='.$offer_id.'');
$dataicube = json_decode($jsondataicube, true);
foreach($dataicube['response']['data'][0]['Thumbnail'] as $key=>$val)
{
$offer_id = $dataicube['response']['data'][0]['Thumbnail']["$key"]['offer_id'];
$display = $dataicube['response']['data'][0]['Thumbnail']["$key"]['display'];
$filename = $dataicube['response']['data'][0]['Thumbnail']["$key"]['filename'];
$url = $dataicube['response']['data'][0]['Thumbnail']["$key"]['url'];
$thumbnail = $dataicube['response']['data'][0]['Thumbnail']["$key"]['thumbnail'];
$_filename = mysqli_real_escape_string($db,$filename);
$_url = mysqli_real_escape_string($db,$url);
$_thumbnail = mysqli_real_escape_string($db,$thumbnail);
$sql[] = '("'.$offer_id.'","icube","'.$_thumbnail.'","'.$_url.'")';
}
}
As I store values which have to be inserted in 'sql'
now
$stmt->prepare( "SELECT offer_id FROM " ."affilate_offer_getthumbnail_icube ORDER BY 'offer_id' ASC");
$stmt->execute();
mysqli_stmt_execute($stmt); // <--------- currently missing!!!
mysqli_stmt_store_result($stmt);
$rows = mysqli_stmt_num_rows($stmt);
$stmt->bind_result($offer_id);
$sqlimplode = implode(',', $sql);
if($rows>0)
{
$query = "UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}`
`
Insert query working well,but how can I update all the data like insert query ?
My Answer is refering to a "set and forget"-strategy. I dont want to look for an existing row first - probably using PHP. I just want to create the right SQL-Command and send it.
There are several ways to update data which already had been entered (or are missing). First you should alter your table to set a problem-specific UNIQUE-Key. This is setting up a little more intelligence for your table to check on already inserted data by its own. The following change would mean there can be no second row with the same value twice in this UNIQUE-set column.
If that would occur, you would get some error or special behaviour.
Instead of using PHPMyAdmin you can use this command to set a column unique:
ALTER TABLE `TestTable` ADD UNIQUE(`tablecolumn`);
After setting up your table with this additional intelligence, you alter your Insert-Command a little bit:
Instead of Insert you can drop and overwrite your Datarow with
REPLACE:
$query= "REPLACE INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100) VALUES (".$sqlimplode.")";
See: Replace Into Query Syntax
Secondly you can do this with the "On Duplicate Key"-Commando.
https://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
$query= "INSERT INTO affilate_offer_getthumbnail_icube
(offer_id, net_provider,logo2020,logo100)
VALUES (".$sqlimplode.")
ON DUPLICATE KEY UPDATE net_provider = ".$newnetprovider.",
logo2020 = ".$newlogo2020.",
logo100 = ".$newlogo100.";";
Note: I think you missed some ( and ) around your $sqlimplode. I always put them around your implode. Maybe you are missing ' ' around strings as well.
Syntax of UPDATE query is
UPDATE table SET field1 = value1, field2 = value2 ...
So, you cannot pass your imploded array $sql to UPDATE query. You have to generate another sql-string for UPDATE query.
This is clearly incorrect:
$query = "UPDATE affilate_offer_getthumbnail_icube
WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'";
If the intention is to INSERT offer_id='".$offer_id."' and then UPDATE ... SET offer_id = '".$sqlimplode."'";
You have to use two separate queries, one for INSERT and then another one for UPDATE
An Example:
$query = "INSERT INTO affilate_offer_getthumbnail_icube
(col_name) VALUES('".$col_Value."')";
//(execute it first);
$query2 = "UPDATE affilate_offer_getthumbnail_icube SET
col_name= '".$col_Value."'" WHERE if_any_col = 'if_any_Value';
//(execute this next);
Try this:
$sqlimplode = implode(',', $sql);
if($rows>0)
{
/*$fields_values = explode(',',trim(array_shift($sql), "()"));
$combined_arr = array_combine(['offer_id','net_provider','logo2020','logo100'],$fields_values);
$sqlimplode = implode(', ', array_map(function ($v, $k) { return $k . '=' . $v; }, $combined_arr, array_keys($combined_arr))); */
$query = "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode." ON duplicate key update net_provider = values(net_provider),logo2020 = values(logo2020),logo100 = values(logo100)";
$stmt->prepare( $query);
$execute = $stmt->execute();
}
else
{
$sqlimplode = implode(',', $sql);
$query= "INSERT INTO affilate_offer_getthumbnail_icube(offer_id, net_provider,logo2020,logo100) VALUES".$sqlimplode;
$stmt->prepare( $query);
$execute = $stmt->execute();
}

MySQL "UPDATE" syntax is entering 0 in column

I am trying to enter into a table in with PDO if using an if condition. My code for the function is below:
function add_user_info($conn, $user, $info, $fName, $sName, $past, $pos){
// Prepare and execute statements
$info1 = addslashes($info);
$sql = $conn->prepare("SELECT * FROM `User_Info` WHERE `User` = '$user'");
$sql->execute();
if ($sql->fetch()){
// Update current entry
$sql1 = $conn->prepare("UPDATE `User_Info` SET `Info` = '$info1' AND `Past` = '$past' AND `Position` = '$pos' WHERE `User` = '$user'");
} else {
// Create new entry
$sql1 = $conn->prepare("INSERT INTO `User_Info` (`User`, `Info`, `FName`, `SName`, `Past`, `Position`) VALUES ('$user', '$info1', '$fName', '$sName', '$past', '$pos')");
}
$sql1->execute();
}
The ONLY (I repeat, ONLY) part that is not working for me is on line 9 with the update query. I have narrowed the problem down to it being related with the update of the Info column, and not only that but it is a problem with the string so the variable $info1.
I am trying to pass in a string of text from CKEditor. It is a rich text string and so has HTML tags, quotations, etc in it when passed to the SQL.
The initial creation of the row in the table (line 12 of the function) works PERFECTLY so it is only on the update that the string is seen as funny. When I update with a word in place of $info1 it still does not work.
As shown in phpmyadmin, my table schema is as follows:
Update command multiple set is separated by , not and
UPDATE `User_Info`
SET
`Info` = '$info1' ,
`Past` = '$past' ,
`Position` = '$pos'
WHERE `User` = '$user'"
Change AND to ,
$sql1 = $conn->prepare("UPDATE `User_Info` SET `Info`='$info1', `Past`='$past', `Position`='$pos' WHERE `User`='$user'");

Categories