How to update if exist, otherwise insert in php? - php

I want to check whether the data is existing or not. If data exists, update the table called "user_star_rate", otherwise insert the data into the table. Inserting is working properly, but the updating is not working.
Here is my code.
$jsqla7 = mysql_query("select * from user_star_rate where product_id='$product_id' and email='$visit_email'") or die(mysql_error());
$jfeta7 = mysql_fetch_assoc($jsqla7);
if($jfeta7 != null) {
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ;
} else {
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ;
}

If I understand what your saying, you should really be using a replace into and it would also decrease your code significantly.
Your code would become:
$query = "REPLACE INTO user_star_rate(product_id, email) VALUES('$product_id', '$visit_email')";
mysql_query($query) or die(mysql_error());
If it already exists then it will update it, else it will insert it. You should pay special attention to the docs in regards to foreign keys and auto incrementing ids.

Try this :
$tot = mysql_num_rows($jfeta7);
if($tot > 0){
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ;
} else {
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ;
}

Try:
$jsqla7 = mysql_query("select count(*) from user_star_rate where product_id='$product_id' and email='$visit_email'") or die(mysql_error());
$count = mysql_num_rows();
if($count) {
$rate = "UPDATE user_star_rate SET rate_value='$rate_value' WHERE product_id='$product_id' and email='$visit_email'" ;
} else {
$rate = "INSERT INTO user_star_rate (email, product_id, rate_value) VALUES ('$visit_email','$product_id','$rate_value')" ;
}

Related

php - why the id automatically turn into 0?

it just set my id into 0 after i inserted some data into the table
then, I get this kind of error:
Duplicate entry '0' for key 'PRIMARY'.
can someone help me identify the problem?
$query = mysql_query("INSERT INTO customer VALUES('', '$name', '$phone', '$address', '$email_add')") or die(mysql_error());
$i=1;
foreach($_SESSION as $namee => $value)
{
if($value > 0)
{
if(substr($namee, 0, 5) == 'cart_')
{
$id = substr($namee, 5, (strlen($namee)-5));
$get = mysql_query("SELECT * FROM product WHERE code='$id'");
while($get_row = mysql_fetch_assoc($get)){
$sub = $get_row['price'] * $value;
echo '<p>'.$i.' '.$get_row['code'].' '.$get_row['name_nl'].' '.$value.' SubTotal : RM '.$sub.'</p> ';
$getCustomer = mysql_query("SELECT customer.id_customer, customer.name, customer.address, product.code, product.name_nl FROM customer, product WHERE name='$name' AND address='$address'" ) or die(mysql_error());
$data = mysql_fetch_array($getCustomer);
$pemb = $data['id_customer'];
$na = $data['name'];
$al = $data['address'];
$ib = $get_row['code'];
$nb = $get_row['name_nl'];
$i++;
}
}
mysql_query("INSERT INTO book VALUES('', '$pemb', '$na', '$al', '$ib', '$nb', '$value', '$sub', now()) ") or die(mysql_error());
}
}
Primary key fields must have different values.
To resolve this, you must set this field to AUTO_INCREMENT, so each time a new record is entered, the primary key field is incremented automatically.

SQL update & insert

I have a MYSQL table named issues_tot including following columns:
v_code, oid, amount, mod_date
02) Then I need to update or insert records of the table according to the given condition as follows:
if(($vt == $vote)||($of == $ono)){
03) update is working properly, but insert is not (else part). My code is showing below:
if (isset($_POST["submit"]))
{
$ono =$_POST["oid"];
$amt =$_POST["amt"];
$allo=mysql_fetch_array(mysql_query("SELECT * FROM allocation WHERE al_code='{$_GET['al_code']}'"));
$vote=$allo['v_code'];
$current_date = date("Y-m-d H:i:s");
$query ="select * from issues_tot where v_code='$vote' ";
$result = mysql_query($query) or die ( mysql_error());
$row = mysql_fetch_assoc($result);
$vt = $row['v_code'] ;
$of = $row['oid'] ;
if(($vt == $vote)||($of == $ono)){
$query ="UPDATE issues_tot SET oid = $ono, amount = amount + $amt WHERE v_code=$vote";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}else {
$query ="INSERT INTO issues_tot (v_code, oid, amount, mod_date) VALUES ('$vote', '$ono', '$amt', '$current_date')";
$result = mysql_query($query) or die ( mysql_error());
$rc = mysql_affected_rows();
}
}
I can not understand what I am going wrong. Can anyone help me ?. Pls

My MySQLi dosen't update only inserts? What's wrong with my script?

$check_verified_user = mysqli_query("SELECT * from user_verified where user_mail = '$payer_email'");
$user_verified = mysqli_fetch_array(mysqli_query($conDB, "SELECT * FROM user_verified where user_mail = '$payer_email'"));
if(mysqli_num_rows($check_verified_user) > 0) {
mysqli_query($conDB, "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'");
} else {
mysqli_query($conDB, "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')");
}
I don't know what's wrong with my script, it checks if the row exists, then if it exists it should update, but instead it inserts another row, which i don't understand...
Give this a try.
$query = "SELECT * FROM user_verified WHERE user_mail = $payer_email";
$check_verified_user = mysqli_query($conDB, $query);
You basically wasn't giving it the database connection, so it was always coming back as not being greater than 0 rows. Personally, I always put my query into its own variable first, and this will ensure that you don't forget params for the mysqli_query() function. It also makes it easier to read, and allows you to use the query in other places if needed.
You can do this method:
$sql = "SELECT * from user_verified where user_mail = '$payer_email'";
$result = mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
if (mysqli_num_rows($result)) {
$sql = "UPDATE user_verified SET total_paid = total_paid + '$payment_amount' where user_mail = '$payer_email'";
}
else {
$sql = "INSERT into user_verified (user_mail,total_paid) VALUES ('$payer_email', '$payment_amount')";
}
mysqli_free_result($result);
mysqli_query($conDB, $sql) or trigger_error(mysqli_error($conDB));
If your user_mail is a UNIQUE KEY you would be able to use the option ON DUPLICATE KEY UPDATE in the INSERT. You can do everything in just 1 query.
$sql = "INSERT INTO user_verified (user_mail,total_paid) VALUES ('$payer_email',$payment_amount) ON DUPLICATE KEY UPDATE total_paid = total_paid + $payment_amount";
mysqli_query($conDB, $sql);
Check this example of a table using UNIQUE KEY.
http://sqlfiddle.com/#!2/4919e2/1/0

insert into mysql else update using select?

Can someone please help, I'm trying to make this script select the values from my mysql table where appropriate and update them if they exist, and if they don't exist then to insert them instead.
Can someone show me where I'm going wrong thanks.
<?php
require_once("session.php");
require_once("functions.php");
require('_config/connection.php');
session_start();
include '_config/connection.php';
$height_ft = $_POST['height_ft'];
$height_in = $_POST['height_in'];
$weight_st = $_POST['weight_st'];
$weight_lb = $_POST['weight_lb'];
$result = mysql_query("SELECT height_ft FROM ptb_stats WHERE id=".$_SESSION['user_id']."");
$result2 = mysql_query("SELECT height_in FROM ptb_stats WHERE id=".$_SESSION['user_id']."");
$result3 = mysql_query("SELECT weight_st FROM ptb_stats WHERE id=".$_SESSION['user_id']."");
$result4 = mysql_query("SELECT weight_lb FROM ptb_stats WHERE id=".$_SESSION['user_id']."");
if( !$result ) {
echo "The username you entered does not exist";
} else if( $height_ft != mysql_result( $result, 0 ) ) {
echo "";
$sql = mysql_query("UPDATE ptb_stats SET height_ft='$height_ft' WHERE id=".$_SESSION['user_id']."");
$sql = mysql_query("UPDATE ptb_stats SET height_in='$height_in' WHERE id=".$_SESSION['user_id']."");
$sql = mysql_query("UPDATE ptb_stats SET weight_st='$weight_st' WHERE id=".$_SESSION['user_id']."");
$sql = mysql_query("UPDATE ptb_stats SET weight_lb='$weight_lb' WHERE id=".$_SESSION['user_id']."");
mysql_query("INSERT INTO ptb_stats (user_id, height_ft) VALUES (".$_SESSION['user_id'].", ".$height_ft.")");
mysql_query("INSERT INTO ptb_stats (user_id, height_in) VALUES (".$_SESSION['user_id'].", ".$height_in.")");
mysql_query("INSERT INTO ptb_stats (user_id, weight_st) VALUES (".$_SESSION['user_id'].", ".$weight_st.")");
mysql_query("INSERT INTO ptb_stats (user_id, weight_lb) VALUES (".$_SESSION['user_id'].", ".$weight_lb.")");
}
if( $sql ) {
$_SESSION['edit_done']="<div class=\"infobox-edit-done\"><strong>Thank You -</strong> Your Details were changed.</div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
} else {
$_SESSION['edit_done2']="<div class=\"infobox-edit-done\"><strong>Oooops! -</strong> That didn't work. Try again.</div>";
header("Location: {$_SERVER['HTTP_REFERER']}");
}
?>
There is an option in MySQL for an update or insert using ON DUPLICATE KEY UPDATE which may more concisely solve your question.
http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
For you query would look something like:
$sql=mysql_query("INSERT INTO ptb_stats (user_id, height_ft)
VALUES (".mysql_real_escape_string($_SESSION['user_id']).", "
.mysql_real_escape_string($height_ft).")
ON DUPLICATE KEY UPDATE user_id = ".mysql_real_escape_string($_SESSION['user_id']).");

Check to Insert or Update table

See the code below, it check if the data exist in the table, if not exist then insert it or else update the table.
As you can see it look a bit messy - is there anyway to improve the code logic or something smaller? I have a few tables that need doing same thing.
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQL = "SELECT * FROM phone_affiliate WHERE affiliate_id = 1 AND affiliate_phone_id = '$dataPhoneID'";
$q = mysql_query($SQL);
if (mysql_num_rows($q) == 0) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
if (mysql_query($SQLInsert)) {
$phone_id = mysql_insert_id();
$SQLInsert = "INSERT INTO phone_affiliate (phone_id, affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUE('$phone_id', '1', '$dataPhoneID', '$stock')";
mysql_query($SQLInsert) or die(mysql_error());
}
} else {
$row = mysql_fetch_assoc($q);
$phone_id = $row['phone_id'];
$SQLUpdate = "UPDATE phone_affiliate set stock = '$stock' WHERE affiliate_id = 1 AND phone_id = $phone_id";
mysql_query($SQLUpdate) or die(mysql_error());
}
// Similar code block above for other tables.
}
}
Note: I am aware about PDO but I don't have time to replace it on existing system.
Use mysql's REPLACE INTO or INSERT... ON DUPLICATE KEY UPDATE. For example:
foreach ($sheet as $data) {
// Get Phone ID
$dataPhoneID = mysql_escape_string($data['handset']['phone_id']);
if (isset($stocks[$dataPhoneID])) {
$stockPhone = $stocks[$dataPhoneID ];
$phoneName = mysql_escape_string($stockPhone['description']);
$stock = mysql_escape_string($stockPhone['stock']);
$SQLInsert = "INSERT INTO phone_affiliate (affiliate_id, affiliate_phone_id, stock) ";
$SQLInsert .= "VALUES ('1', '$dataPhoneID', '$stock') ";
$SQLInsert .= "ON DUPLICATE KEY UPDATE stock = '$stock'";
mysql_query($SQLInsert);
if (mysql_insert_id()) {
$SQLInsert = "INSERT INTO phone (name) VALUE('$phoneName')";
mysql_query($SQLInsert);
$phone_id = mysql_insert_id();
$SQLUpdate = "UPDATE phone_affiliate set phone_id = $phone_id WHERE affiliate_id = 1 AND affiliate_phone_id = $dataPhoneID_id";
}
}
}
Also you can use INSERT IGNORE construction

Categories