Hello I have a table A and I want when a new value (not UPDATE) is inserted in that table to do an INSERT in table B, I tried to play with the responce of the $query INSERT INTO .. ON DUPLICATE KEY UPDATE but no luck, it always returns 1.
$query = "INSERT INTO table ".$fields." VALUES ".$values." ON DUPLICATE KEY UPDATE updated=1"
$response = $dbc->query($query);
if($response == 1)
I have also tried a 'hack' lets say, putting the UPDATE above the INSERT so if the entry doesnt exist to fail but that again returns 1 everytime.
$query = "UPDATE table SET updated=1 ..;
$response = $dbc->query($query);
if($response == 1)
This should work:
<?php
$link = mysqli_connect("localhost", "my_user", "my_password", "world");
mysqli_query($link, "INSERT INTO tableA ".$fields." VALUES ".$values." ON DUPLICATE KEY UPDATE updated=1");
if(mysqli_affected_rows($link)==1)
{
mysqli_query($link, "INSERT INTO tableB ".$fields." VALUES ".$values.");
}
?>
Thanks #boomoto for helping me figuring out the answer:
$query = "UPDATE tableA ..
$response = $dbc->query($query);
if(mysqli_affected_rows($dbc)==0){
$query2 = "INSERT INTO tableB ..
$response2 = $dbc->query($query2);
$query = "INSERT INTO tableA ..
$response = $dbc->query($query);
}
}
Related
I am trying to stop 2 tables from being updated based on an update on the first table.
Here is what I have to check the first table.
//add user to pif_table//
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query="UPDATE `pif_table` SET $g = '$uname', #success = 1 WHERE $g IS NULL OR $g = '' AND id = '$id' ";
$db->setQuery($query);
$result = $db->execute();
So, the first table, above is updated only if the $g column is empty.
I only wish the next 2 tables to be updated IF, $g column was empty and was updated above.
I receive a syntax error from the #success = 1 part of the command.
if ($success == 1){
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query="UPDATE `jospk_users` SET tables = tables +1, payments = payments +1, tbl".$pifbase."= tbl".$pifbase." +1 WHERE id = '$uid'";
$db->setQuery($query);
$result = $db->execute();
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query = "INSERT INTO `pif_payments` (`table_num`, `r_1`, `r_2`, `r_3`, `r_4`, $g, `amount`) VALUES ('$id', '$r1', '$r2', '$r3', '$r4', '$uname', '$pifbase') ON DUPLICATE KEY UPDATE $g = '$uname'";
$db->setQuery($query);
$result = $db->execute();
}
From what I understand, the Jommla's JFactory's execute method will not return false if the record was not updated and you can only check this if you query the database.
So, create a variable or array with the new value(s) before attempting to run the first UPDATE query and once you have, check the record and see if it matches the new value if so keep running the remaining queries.
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();
}
I did 2 tables in mysql database
user_details
bank_details
In user_details am create following entity
user_id as a Primary Key
username
password
address
In bank_details am create following entity
id as a Primary Key
user_id as a Foreign Key
bank_name
ac_no
First am insert user details using following code
<?php
$un = $_POST['un'];
$ps = $_POST['ps'];
$adr = $_POST['adr'];
$sql = mysql_query("insert into user_details username='$un', password='$ps', address='$adr'");
?>
Now i need to insert Bank Details in bank_details table
<?php
$bn = $_POST['bn'];
$ac_no = $_POST['ac'];
$sql = mysql_query("insert into bank_details user_id= ?? bank_name='$bn', ac_no='$ac_no'");
?>
How can i define that foreign key values here ?
Your query omits the MYSQL SET keyword. Anyway, you can do this, as per your code convention:
<?php
$mysql = mysql_connect([...]
$un = mysql_real_escape_string($_POST['un'], $mysql);
$ps = mysql_real_escape_string($_POST['ps'], $mysql);
$adr = mysql_real_escape_string($_POST['adr'], $mysql);
$sql = mysql_query("insert into user_details SET username='$un', password='$ps', address='$adr'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysql_insert_id(); //get the id of the last inserted query/user
$bn = mysql_real_escape_string($_POST['bn'], $mysql);
$ac_no = mysql_real_escape_string($_POST['ac'], $mysql);
$sql = mysql_query("insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'", $mysql);
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>
I must point out, however, that using the mysql_* family of functions is deprecated, and you should seriously start using mysqli_* functions instead.
UPDATE:
As Per CodeGodie's suggestion, here's the re-written code using mysqli_* functions:
<?php
$mysqli = mysqli_connect(SERVER_NAME, USER_NAME, PASSWORD, DB_NAME);
$un = mysqli_real_escape_string($_POST['un']);
$ps = mysqli_real_escape_string($_POST['ps']);
$adr = mysqli_real_escape_string($_POST['adr']);
$sql = mysqli_query($mysqli, "insert into user_details SET username='$un', password='$ps', address='$adr'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
else
{
$user_id = mysqli_insert_id($mysqli); //get the id of the last inserted query/user
$bn = mysqli_real_escape_string($_POST['bn']);
$ac_no = mysqli_real_escape_string($_POST['ac']);
$sql = mysqli_query($mysqli, "insert into bank_details SET user_id = $user_id, bank_name='$bn', ac_no='$ac_no'");
if(!$sql)
{
// something went wrong with the query, add error handling here
trigger_error('query failed', E_USER_ERROR);
}
}
?>
I am running a query to check my database for existing values, if they do exist then update them do not reinsert them.
Currently my code is just reinserting the values into the table instead of updating them, which means my code is never reaching the else part of my statement.
if(isset($user_info->error)){
// Something's wrong, go back
header('Location: twitter_login.php');
}
else {
// Let's find the user by its ID
$query = ("SELECT * FROM twitter WHERE oauth_provider = 'twitter' && oauth_uid = '".$user_info->id."'");
$rs=$mysql->query($query);
$results = $rs->fetch_array(MYSQLI_ASSOC);
// If not, let's add it to the database
if(empty($result)){
$query = ("INSERT INTO twitter (oauth_provider, oauth_uid, username, oauth_token, oauth_secret)
VALUES ('twitter', {$user_info->id}, '{$user_info->screen_name}', '{$access_token['oauth_token']}', '{$access_token['oauth_token_secret']}')");
$rs=$mysql->query($query);
$insert = ("SELECT * FROM twitter WHERE id = " . mysqli_insert_id($mysql));
$rs=$mysql->query($insert);
$results = $rs->fetch_array(MYSQLI_ASSOC);
}
else{
// Update the tokens
$update = ("UPDATE twitter SET oauth_token = '{$access_token['oauth_token']}',
oauth_secret = '{$access_token['oauth_token_secret']}'
WHERE oauth_provider = 'twitter' AND oauth_uid = {$user_info->id}");
$rs=$mysql->query($update);
$rs->close();
}
you have a typo between $result and $results
$results = $rs->fetch_array(MYSQLI_ASSOC);
// If not, let's add it to the database
if(empty($result)){
^
Here
as $result is not declared before it will always be empty and the if part will always be true.
If you want to properly prevent duplicates, create a UNIQUE KEY(oauth_provider,oauth_uid);
then use INSERT ON DUPLICATE statement to insert or update the row.
http://dev.mysql.com/doc/refman/5.5/en/insert-on-duplicate.html
INSERT INTO twitter (oauth_provider, oauth_uid, username, oauth_token, oauth_secret)
VALUES ('twitter', {$user_info->id}, '{$user_info->screen_name}', '{$access_token['oauth_token']}', '{$access_token['oauth_token_secret']}')
ON DUPLICATE KEY UPDATE oauth_token = VALUES(oauth_token), oauth_secret = VALUES(oauth_secret)
I need your help, I have a table whith two column, an id and numpos, i want that the id and numops has the same result.
exemple :
$cnx = mysql_connect( "localhost", "root", "" );
$db = mysql_select_db( "maincourante" );
$sql = mysql_query("INSERT INTO ops (id) values('')");
$req = mysql_query("SELECT LAST_INSERT_ID() as id FROM ops");
$data = mysql_fetch_array($req);
$upd = mysql_query("UPDATE `ops` SET `numops`=`idops` WHERE `idops`=$data");
mysql_query($upd, $cnx) or die(mysql_error());
mysql_close();`
thanks for your help
Try this:
This works for mysql:
INSERT INTO ops (`numops`) VALUES ((SELECT LAST_INSERT_ID())+1);
This works for php:
mysql_query("INSERT INTO ops (`numops`) VALUES (0)");
mysql_query("UPDATE ops `numops` ='".mysql_insert_id()."' WHERE `id` = '".mysql_insert_id()."'");
Or
mysql_query("INSERT INTO ops (`numops`) VALUES ('".mysql_insert_id()."')");
// this will only works if there is the same query executed before this.