2

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 ?

Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
nehaJ
  • 77
  • 1
  • 11

4 Answers4

2

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. a busy cat

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.

Community
  • 1
  • 1
Nibbels
  • 156
  • 10
  • but i have one query again,if I put unique key to offer id but the values of same offer id may different then it should display . – nehaJ Oct 04 '15 at 14:05
  • In every case you have to specify what has to be unique in your datarows. You can specify ONE column as Unique or MORE columns. Example for ONE: You can tell your Table that there can only be different names. Then you insert some row like `ID = 1`, `name=nehaJ`, `year=2000`. Later you Insert `ID = 23`, `name=nehaJ`, `year=2005`. Then you would replace or update the old one and ID = 1 would probably get deleted. Example for Multiple: If you set your Table UNIQUE for NAME+YEAR you would have ID=1 and ID=23 in your Table then. Because nehaJ+2000 is unequal to nehaJ+2005. Answered? – Nibbels Oct 04 '15 at 14:13
  • I once did some data-collecting for a browsergame. There had been Usernames with AccountIDs. I saved all of them with a Date. And I made the Username-Column AND UserID-Column UNIQUE. (That is one Unique-Index covering two columns.) Later on I updated this datastorage. When an account got renamed by the player I had a new tuple of User-Name and UserID and then it was inserted into my database with the Timestamp. So I was able to track the renaming quite easy. When I updated: normally 10000 Inserts failed with `row already exists` and only the new ones got in. – Nibbels Oct 04 '15 at 14:18
  • let I have two columns 1 is offer id and another is categories..I add unque key to now when rows insert values are 1)offer id=2 , categories = marketplace 2)offer id=2 categories = ecommerce, Then it becomes offer_id= 2 , categories = ecommerce.I want both values – nehaJ Oct 04 '15 at 14:33
  • Actually I am calling this from api.so whenever I heat api first entries should updated with another. – nehaJ Oct 04 '15 at 14:39
  • If (offerid=2, categories=marketplace, ...) and (offerid=2, categories=ecommerce, ...) should be able to coexist, but (offerid=2, categories=marketplace, ...) and (offerid=2, categories=marketplace, ...) should cause an overwrite then you should put a combined UNIQUE key to offerid and categories. Then you write "replace into table (offerid,categories,...) values (2, 'ecommerce', ...)". At first it is not existing and getting inserted. The second time you insert this (same key-combination) the first entry is gonna be deleted and the new one is inserted. understood? – Nibbels Oct 04 '15 at 21:40
0

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.

u_mulder
  • 54,101
  • 5
  • 48
  • 64
0

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);
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
0

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();
  }
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
  • thanks for the answer,but it print only 1 value as there are multiple rows – nehaJ Oct 04 '15 at 10:29
  • when I echo $query = "UPDATE affilate_offer_getthumbnai l_icube WHERE offer_id='".$offer_id."' SET '".$sqlimplode."'"; output become UPDATE affilate_offer_getthumbnail_icube WHERE offer_id='12' SET 'offer_id="2", net_provider="icube", logo2020="http://media.icubeswire.com/brand/files/icubes/2/thumbnails_100/jabong-logo.jpg", logo100="http://media.icubeswire.com/brand/files/icubes/2/jabong-logo.jpg"' for offer id 12,but as there are two rows containing offer id 2 , 12 then o/p should be two update statements 1 is for 2 and another is for 12 – nehaJ Oct 04 '15 at 10:46