Update query works but not insert query - php

I'm having a problem with inserting info into the database. Strangely the update query works but not the insert query. I don't get any error either when submitting, it goes through correctly and echo account saved but nothing is inserted. What am i missing or doing wrong. please assist
if(isset($_POST['Submitaccount'])){
$allowedusers = $_POST['users'];
$accountid = trim($_POST['accountid']);
if(!$_POST['copyperms']) $_POST['copyperms']='N';
if(!$_POST['allusers']) $_POST['allusers']='N';
if(!$_POST['enabled']) $_POST['enabled']='N';
if(!$_POST['servertime']) $_POST['servertime']='N';
if(!$_POST['delremovals']) $_POST['delremovals']='N';
unset($_POST['Submitaccount']);
unset($_POST['accountid']);
unset($_POST['users']);
$notmust = array("email" , "skip" , "comments" , "firstmod");
foreach($_POST as $key=>$val){
if(!trim($val) && !in_array($key , $notmust)) {
$err = 1;
$empty = "$key";
break;
}
$qpart .= "`$key` = '".mysql_escape_string($val)."' , " ;
}
if($qpart) $qpart = substr($qpart , 0 , -2);
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
}
}
if(!$err){
if(!$accountid){
$q = "INSERT into accounts SET $qpart ";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}

This is because the INSERT command has different syntax:
INSERT into accounts SET $qpart "
is not usual, you can write it like this:
INSERT into accounts (column names) VALUES your values"
13.2.5 INSERT Syntax

You have double if(!$err){. Do you want both (!$err) into one? If the first (!$err) is for indicator for the second to insert, function SELECT can not be placed above the function INSERT indirectly.
try this:
if(!$err){
$chk = mysql_num_rows(mysql_query("SELECT * from accounts WHERE name = '".mysql_escape_string($_POST['name'])."' and id <> '$accountid'"));
if($chk >0){
$err = 2;
// if(!$err){ again ...
if(!$accountid){
$q = "INSERT into accounts SET (column1) VALUES ($var1)";
mysql_query($q) or die("Error inserting the record :".mysql_error()."<br>".$q);
$accountid = mysql_insert_id();
}
else{
$q = "UPDATE accounts SET $qpart WHERE id = '$accountid'";
mysql_query($q) or die("Error updating the record :".mysql_error()."<br>".$q);
}
}
}
else{
//other code to handle if ($err)
}
Note: I would prefer using PDO to handle database, it's so simple scripting, besides, it's no longer supported

You have to understand that mysql functions have become deprecated. Either using mysqli or pdo would be the better option, but if you absolutely have to use mysql as a solution i would suggest not posting the form to itself, rather post to another php file as you will have less problems.In my environment it seems to work well as an interim solution while we are rewriting everything to use mysqli.If it a go and let me know.

Related

Conditional PDO Delete statement probably not working

The portion that is trying to delete duplicate entries in the database seems incorrect. So I suppose I am asking what would be the correct way to do that in this example. I am not totally new to PHP , but this is beyond me. If you could please tell me what is wrong and how to fix that would be greatly appreciated.
Now on to what I am trying to accomplish. I have a multidimensional array filled with values that is generated by a function. What I am trying to do is if there is a value in the array that already exists in the database delete it. Code:
enter code here
if(is_array($items)){
$values = array();
foreach($items as $row => $value){
$rsn = mysqli_real_escape_string($connect, $value[0]);
$rank = mysqli_real_escape_string($connect, $value[1]);
$values[] = "('', '$rsn', '$rank', '')";
$sql = "SELECT id FROM users WHERE rsn = :rsn";
$query = $conn->prepare($sql);
$query->execute(array(":rsn" => $value[0]));
$results = $query->rowCount();
while($deleted = $query->fetch(PDO::FETCH_ASSOC)){
$sql = "DELETE FROM users WHERE id = :id";
$query = $conn->prepare($sql);
foreach($deleted as $delete){
$query->execute(array(':id' => $delete));
}
}
}
//user_exists_delete($conn, $rsn);
$sql = "INSERT INTO users(id, rsn, rank, points) VALUES ";
$sql .= implode(', ', $values);
if(!empty($rank)&& !empty($rsn)){
if(mysqli_query($connect, $sql)){
echo "success";
}else{
die(mysqli_error($connect));
}
}
}
EDIT: I have got it partially working now, just need it to delete all dupes instead of only one. I edited code to reflect changes.
There are a couple problems, if you didn't strip much of your original code and if you don't need to do more than just what you shown why not just send a delete instruction to your database instead of checking validity first?
You have
//Retrieve ID according to rsn.
$sql = "SELECT id FROM users WHERE rsn = :rsn ";
//Then retrieve rsn using rsn??? Useless
$sql = "SELECT rsn FROM users WHERE rsn = :rsn ";
//Then delete using ID, retrieved by rsn.
$sql = "DELETE FROM users WHERE id = :id";
All those could simply be done with a delete using rsn...
$sql = "DELETE FROM users WHERE rsn = :rsn";
The row won't be deleted if there are no rows to delete, you don't need to check in advance. If you need to do stuff after, then you might need to fetch information before, but if not, you can use that while still checking the affected rows to see if something got deleted.
Now, we could even simplify the script by using only one query instead of one per user... We could get all rsn in an array and then pass it to the DELETE.
$sql = "DELETE FROM users WHERE rsn in :rsn";
//Sorry not exactly sure how to do that in PDO, been a while.
I fixed it I just omitted the WHERE clause in the delete statement so all records are being deleted before that insert gets ran again.

PHP insert and Update on Multiple Query and table

in there i want to make update and create on one condition,so when I create a new record, automatically update my Data if have i success make new.
here my PHP :
<?php
require "dbconnection.php";
$a = array();
$a['transidmerchant'] = $_POST['TRANSIDMERCHANT'];
$a['totalamount'] =$_POST['AMOUNT'];
$a['words'] = $_POST['WORDS'];
$a['payment_channel'] = $_POST['PAYMENTCHANNEL'];
$a['session_id'] = $_POST['SESSIONID'];
$a['payment_date_time'] = $_POST['REQUESTDATETIME'];
$a['trxstatus'] = 'Requested';
$query = "INSERT INTO doku (transidmerchant,totalamount,words,payment_channel,session_id,payment_date_time,trxstatus)
VALUES ('$_POST[TRANSIDMERCHANT]','$_POST[AMOUNT]','$_POST[WORDS]','$_POST[PAYMENTCHANNEL]','$_POST[SESSIONID]','$_POST[REQUESTDATETIME]','Requested')";
$sql = "UPDATE orders SET status='Paid' where id='$_POST[TRANSIDMERCHANT]'";
if(mysqli_query($con,$query)) {
mysqli_connect($con,$sql);
echo 1;
}else{
echo("Error description: " . mysqli_error($con));
}
my query : $query and $sql
i want my $sql its update when $query is success create
if (mysqli_query($con, $query) === true) {
mysqli_query($con, $sql);
echo 1;
} else {
echo('Error description: ' . mysqli_error($con));
}
Create a stored procedure for insert then update. You may want to do something like this to get you away from issuing regular queries checking sub-queries and move you to creating a stored procedure.
Create your procedure to something similar below and run it in your sql dialog. Once you're done, run it:
DELIMITER //
CREATE PROCEDURE Payment
(
a_transidmerchant int,
a_atotalamount float,
a_words varchar(200),
a_payment_channel varchar(200),
a_session_id int,
a_payment_date_time datetime,
etc...
)
BEGIN
insert into doku(field_name1, field_name2, field_name3, field_name4) values(a_field1, a_field2, a_field3, a_field4);
END //
DELIMITER;
Now, in your php file, do the following:
if(isset($_POST[transidmerchantid])) /**** start a post check ****/
//before you touch the db
{
$con = mysqli_connect("localhost","user","pass","database");
//start defining variables
$transidmerchantid = $_POST[name];
$totalamount = $_POST[course];
$words = $_POST[words];
//calling stored procedure - call values for parameters in stored procedure
$sql = "CALL Payment('$transidmerchantid','$totalamount','$words')"; // <----
//in the order of operation, meaning once you have inserted the data,
//you can update the table. you're automatically updating the table row
//based on a successful insert, which is after calling the insert row
//stored procedure.
$result = mysqli_query($con,$sql);
if($result) //insert successful.
echo "Record Added Successfully!";
$sql = "UPDATE orders SET status='Paid' where id='$_POST[TRANSIDMERCHANT]'";
mysqli_query($con,$query);
}else{
echo("Error description: " . mysqli_error($con));
}else{
echo "Record Not added!"; //insert unsuccessful.
}
} /**** end post check ****/

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();
}

verifying and inserting details into db

I need to insert the details (name, id , number )of many documents into database if they are not already existing and if they exist i just need to do a update for any changed information. I have arrived at the following code but it doesn't work. I am new to this and need help on this.
foreach($A->Documents -> Document as $Document)
{
$query = "SELECT * from table where id = '".$Document->id."'";
$outcome = mysql_query($query) or die(mysql_error());
if(($outcome)&&(mysql_num_rows($result)>0)){
echo "Document already available" ;
while($row = mysql_fetch_object($outcome)){
if(!($outcome->name == $document->name)){
$update= "UPDATE table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
else
{
$insert= "INSERT table SET name= '.$Document->Name.'";
mysql_query($update) or die(mysql_error());
}
}
}
}
Use $row->name instead of $outcome->name. and your INSERT statement is wrong.
while($row = mysql_fetch_object($outcome)){
if(!($row->name == $document->name)){
$update = "UPDATE table SET name ='".$Document->Name."' WHERE id = ".$Document->id;
mysql_query($update) or die(mysql_error());
}
else {
$insert = "INSERT INTO table (name) VALUES('".$Document->Name."')";
mysql_query($insert) or die(mysql_error()); // $insert not $update
}
}
Note: Stop using mysql_* functions! Use PDO or mysqli_* instead. And use prepared statements
Change the
mysql_query($update) or die(mysql_error());
To:
$insert = INSERT into table_name values(" values");
mysql_query($insert) or die(mysql_error());
in the else condition
Issue is with $result variable with in if statement
( if(($outcome)&&(mysql_num_rows($result)>0)){)
It should be $outcome because you initialized query output to $outcome variable
First of, dont yse mysql_ functions. Read the docs (read the warning).
use mysqli or PDO instead.
Then, your INSERT statement is wrong.
INSERT INTO table (col1) VALUES (value_for_col1);

Need Help with Update statement in SQl

I'm new to sql database. I'm using the update statement to modify a value in my column. All my columns are of type char, but I'm not able to modify the column. Please point out what mistake I'm making
if ($info['Patient'] === '' )
{
UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda';
$sql = "INSERT INTO guestbook(Name)VALUES('$patient')";
$result=mysql_query($sql);
//check if query successful
if($result){
echo "Successful";
echo "<BR />";
}
else {
echo "ERROR";
}
The rest of the code is working fine and the Insert statement is working good whereas I c an't get the update statement to modify the table.
Since you appear to be calling this from PHP you need to use the mysql_query method to execute the update statement like so:
$sql = "UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda'";
mysql_query($sql);
Replace
UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda';
$sql = "INSERT INTO guestbook(Name)VALUES('$patient')";
with
$sql = "UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda'";
You need to use mysql_query() for your update statement as well...
$update = "UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda'";
mysql_query($update);
$sql = " UPDATE guestbook SET Message = 'howdy' WHERE Name = 'mathilda' ";
if(mysql_query($sql)){
// true
}

Categories