Update and Insert into three tables simultaneously - php

I have a record that needs to be updated. If the update is successful, then it should insert record into three different tables. I did it with the code below,but one of the table(tab_loan_targetsave)is not inserting.I need a third eye to looked into this, as I have had a lot of pain in fathoming where the problem lies.
Pls i need assistance.Also, I welcome better approach if possible.
<?php
if(isset($_POST["savebtn"])){
$custNo = $_POST["custid"];
$transDate = $_POST["transDate"];
$grpid = $_POST["custgrp"];
$contAmount =$_POST["amtCont"];
$amount = $_POST["amount"];
$disAmount =$_POST["disbAmt"];
$savAmount =$_POST["savAmt"];
$intAmount =$_POST["intAmt"];
$postedBy = $_SESSION["staffid"];
//$preApproved =$_POST["preAmount"];
$loanRef = $_POST["refid"];
$st = "Approved";
$appDate = date("Y-m-d H:i:s");
$appBy = $_SESSION['staffid'];
$counter = 1;
$locate = $_SESSION['location'];
$insure = $_POST["insuAmt"];
$dis = $_POST["DisAmt"];
$update = mysqli_query($connection,"UPDATE tab_loan_request SET approval_status='$st',approvalDate='$appDate',approvedBy='$appBy',loanRef='$loanRef' WHERE custid='$custNo' AND RepayStatus='1'");
if($update && mysqli_affected_rows($connection)>0){
$insertTar = mysqli_query($connection,"INSERT INTO tab_loan_targetsave(custid,grpid,transactionDate,loanRef,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef,'$savAmount','Cr','$postedBy','$locate','1')");
$insertInt = mysqli_query($connection,"INSERT INTO tab_loan_interest(custid,requestAmt,transactionDate,interestFees,postedBy,loanRef,InsuranceFees,DisasterFees)VALUES(
'$custNo','$amount','$transDate','$intAmount','$postedBy','$loanRef','$insure','$dis')");
//if($insertInt){
//}if($insertTar){
$insertSav = mysqli_query($connection,"INSERT INTO tab_loan_saving(custid,grpid,transactionDate,loanRef,loanAmount,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef','$amount','0','Cr','$postedBy','$locate','1')");
}//first if
if($insertSav){
echo "<span style='font-weight:bold;color:red;'>"." Application Approval is successful!"."</span>";
}else{
//Unable to save
echo "<span style='font-weight:bold;color:black;>"."Error! Application Approval not Successful!"."</span>";
}
}else{
$custid = "";$saving=0.00;$st="";
$transDate = "";
$grpid = "";
$amount = "";
$postedBy = "";$loanRef="";
}
?>

"#Fred: See the error generated when i used mysqli_error($connection). Could you please interprete this: ErrorMessage: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '1000.00','Cr','SPL002','Ojo','1')' at line 2 – Dave"
Seeing the error generated by the suggestion I've given you to check for errors.
You're missing a quote here '$loanRef
in your query:
VALUES('$custNo','$grpid','$transDate','$loanRef , '$savAmount'...
^ right there
I suggest to escape all of your incoming data.
I.e.:
$var = mysqli_real_escape_string($connection, $_POST['var']);
and apply that same logic to all your POST arrays.
Plus, as I stated; make sure you started the session, since there is no mention of that in your question and session_start(); wasn't included in your posted code.
The session needs to be started inside all pages using sessions.
Using a prepared statement will is better.
http://php.net/manual/en/mysqli.prepare.php
http://php.net/manual/en/pdo.prepared-statements.php
which is what you really should be using.
Additional references:
http://php.net/manual/en/mysqli.error.php
http://php.net/manual/en/function.error-reporting
Also make sure there aren't any constraints in your table(s).

Dude make sure you properly escape your variables http://php.net/manual/en/mysqli.prepare.php
i would check the Table Name! make sure it is case sesntive, also just wondering if you could do something to your database design? It seems a lot of duplicate data is going into your tables. Think about a better way to organise and store that data

I got where the error is emanting from . Just because I forgot to add a single quote to one of the values. ie missing the quote- near $loanRef. No closing string. Anyway, I was able to detect that through the error message stated parameter as adviced by Fred nad Mark. Correct
$insertTar = mysqli_query($connection,"INSERT INTO tab_loan_targetsave(custid,grpid,transactionDate,loanRef,savingAmt,status,postedBy,location,appStatus)
VALUES('$custNo','$grpid','$transDate','$loanRef','$savAmount','Cr','$postedBy','$locate','1')");
Thank you all.

Related

SQL UPDATE not working

I am trying to update some of the data in a database called customer. This is my code
<?php
Require("dbconnect.php");
$Customer_id = $_POST['Customer_id'];
$Customer_title = $_POST['Customer_title'];
$Customer_forename = $_POST['Customer_forename'];
$Customer_surname = $_POST['Customer_surname'];
$Customer_contact = $_POST['Customer_contact'];
?>
all the variables are holding the correct data as I have test echoed them.
No errors are recieved when I run this code however it is not updating the database either? Can anyone help? Thank in advance!
String constants need single quotes (forename and surname):
$sql = "UPDATE `a6123854_a220559`.`Customer`
SET Customer_forename = '".$Customer_forename."', Customer_surname = '".$Customer_surname."'
WHERE Customer_id = ".$Customer_id."";
Please note that your code may be susceptible to SQL injection.
There is one little thing that will quite possibly fix your problem. It is in the quotation.
$sql = "UPDATE `a6123854_a220559`.`Customer`
SET Customer_forename='".$Customer_forename."',
Customer_surname='".$Customer_surname."'
WHERE Customer_id='".$Customer_id."'";

PHP INSERT into creates Database error

I am attempting to create a function that will insert items (and will do the same to edit) items in a database through a form. I have the form and the PHP - and when I run the function, I get the correct database name to pull and the variable names to pull along with the values I input, but I then see a database error? Any help would be great (I'm still newer to PHP really and pulling out some hair)
Config File:
$hostname = 'localhost';
$username = 'DEFINED';
$password = 'DEFINED';
$database = 'DEFINED';
$table = 'recipes';
require('../config.php');
$link = mysql_connect($hostname,$username,$password);
mysql_select_db($database,$link);
/* Get values and submit */
$rid = mysql_real_escape_string($_POST['rid']);
$name = mysql_real_escape_string($_POST['name']);
$category = mysql_real_escape_string($_POST['category']);
$tags = mysql_real_escape_string($_POST['tags']);
$search_tags = mysql_real_escape_string($_POST['search_tags']);
$description = mysql_real_escape_string($_POST['description']);
$description2 = mysql_real_escape_string($_POST['description2']);
$recipeAbout = mysql_real_escape_string($_POST['recipeAbout']);
$ingredients_1 = mysql_real_escape_string($_POST['ingredients_1']);
$directions_1 = mysql_real_escape_string($_POST['directions_1']);
$query = "INSERT INTO $table (name, category, tags, search_tags, description,description2, recipeAbout, ingredients_1,directions_1) VALUES ('$name','$category','$description','$description2' $tags','$search_tags','$description','$recipeAbout','$ingredients_1','$directions_1')";
echo $query;
Besides the missing comma in '$description2' $tags' => '$description2', $tags' which you said had been added afterwards, and signaled by Ryan: there's also a missing quote, so change it to '$description2', '$tags' and having 2x '$description' variables, remove one.
VALUES
('$name','$category','$tags','$description','$description2', '$search_tags','$recipeAbout','$ingredients_1','$directions_1')";
However, the most important part to querying, is that you must use mysql_query() which you are not using => mysql_query() which is why data isn't being inserted, once you've fixed the syntax errors.
mysql_query() is the essential part.
Add the following to your code:
if(mysql_query($sql,$link)){
echo "Success";
}
else{
echo "Error" . mysql_error();
}
Plus, use prepared statements, or PDO with prepared statements.
You're using a deprecated library and open to SQL injection..
Plus make sure you have assigned $table to the table you wish to enter data into. It's not shown in your question.
You also did not show what your HTML form contains. Make sure that you are using a POST method and that all elements are named with no typos.
Add error reporting to the top of your file(s) which will help find errors.
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
Sidenote: Error reporting should only be done in staging, and never production.
EDIT: and using mysqli_
As a quick test, try the following and replacing the values in the line below with your own.
<?php
$link = mysqli_connect("host","username","password","database")
or die("Error " . mysqli_error($link));
$table = "recipes";
$name = mysqli_real_escape_string($link,$_POST['name']);
mysqli_query($link,"INSERT INTO `$table` (`name`) VALUES ('".$name."')")
or die(mysqli_error($link));
?>
If that still does not work, then you need to check your database, table, column name(s), including types and column lengths.
Lot's of stuff wrong here...
You're missing a quote on the second of these two items, as well as either a string concat or a comma: '$description2' $tags'
You've also got your order messed up for tags, search tags, and description 1/2.
$description is in there twice (you have 9 columns defined and 10 values in your statement)
You don't seem to have declared a value for $table
As Fred -ii- has pointed out in his answer, you're missing mysql_query() to actually run it. I assumed you have it further down in your code, but it's missing from the post, which is causing some confusion...
Also, consider updating to use mysqli instead of mysql functions.
what are you echoing $query for?
You do not have any reason to do that except if you just want to use it as a string variable.
it should be mysql_query($query);
What is the exact "database error" error you are getting?
I suggest reading this article about PDO
If you can't insert the data correctly, this might be your problem too.

SQL syntax error edit post

getting :
You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use
near 's Creed III', description='The plot is set in a fictional
history of real ' at line 2
when trying to edit posts on a database.
heres my display and edit php:
$result = mysql_query("SELECT * FROM gallery");
while ($row = mysql_fetch_array( $result )){
// while looping thru each record…
// output each field anyway you like
$title = $row['title'] ;
$description = $row['description'];
$year = $row['year'];
$rating = $row['rating'];
$genre = $row['genre'];
$filename = $row['filename'];
$imageid = $row['imageid'];
include '../modules/edit_display.html';
}
// STEP 2: IF Update button is pressed , THEN UPDATE DB with the changes posted
if(isset($_POST['submit'])){
$thisTitle = $_POST['title'];
$thisDescription = $_POST['description'];
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
$thisNewFilename = basename($_FILES['file']['name']);
$thisOneToEdit = $_POST['imageid'];
$thisfilename = $_POST['filename'];
if ($thisNewFilename == ""){
$thisNewFilename = $thisfilename ;
} else {
uploadImage();
createThumb($thisNewFilename , 120, "../uploads/thumbs120/");
}
$sql = "UPDATE gallery SET
title='$thisTitle',
description='$thisDescription',
year='$thisYear',
rating='$thisRating',
genre='$thisGenre',
filename='$thisNewFilename'
WHERE
imageid= $thisOneToEdit";
$result = mysql_query($sql) or die (mysql_error());
}
You're suffering from an imminent dose of SQL Injection due to using a dangerous user input model.
When you type "Assassin's Creed III" in the title field, that gets placed in single quotes in the UPDATE statement in your code (via the $_POST['title'] variable):
'Assassin's Creed III'
The problem there is that MySQL sees it as 'Assassin', followed by s Creed III'. It doesn't know what to do with the latter.
Of course, this becomes a HUGE problem if someone types in valid SQL at that point, but not what you expected. Have a look at How can I prevent SQL injection in PHP? or any of several other advices on avoiding SQL Injection.
i have seen you are adding ' into database so you need to escape it using addslashes()
addslashes($thisTitle)
You have syntax error here. Use $_POST instead of $POST.
Replace
$thisYear = $POST['year'];
$thisRating = $POST['rating'];
$thisGenre = $POST['genre'];
With
$thisYear = $_POST['year'];
$thisRating = $_POST['rating'];
$thisGenre = $_POST['genre'];
you need to escape your input like
$thisDescription = mysql_real_escape_string($_POST['description']);
do this for all input that contains quotation marks etc..
NOTE: mysql will soon be gone so its advised to write new code using mysqli instead
You have alot of issues in your script.
You're trying to add ' character to database, you need to escape it properly with addslashes.
You're vulnerable to SQL Injection. Escape it properly with mysql_real_escape_string, or even better, use PDO.
Third, it is $_POST, not $POST. You're using it wrong in some areas.
Add quotes to $thisOneToEdit in query.
The error is causing because you're trying to add Assasin's Creed III string to database. The single quote breaks your query and creates a syntax error.
Do a addslashes() on the values that might contain single or double quotes like below before using them in query
$thisTitle = addslashes($_POST['title']);

Append 2 Mysql rows

I have a two step registration, one with vital data, like email username and password, and a second optional one with personal info, like bio, eye color, etc.. i have 2 exec files for these, the first ofc writes the data in the first part of the database, leaving like 30 columns of personal data blank. The second one does another row, but with the vital data empty now.. I would like to append, or join these two rows, so all the info is in one row..
Here is the 2nd one
$qry = "UPDATE `performers` SET `Bemutatkozas` = '$bemuatkozas', `Feldob` = '$feldob', `Lehangol` = '$lehangol', `Szorzet` = '$szorzet', `Jatekszerek` = '$jatek', `Kukkolas` = '$kukkolas', `Flort` ='$flort', `Szeretek` = '$szeretek', `Utalok` = '$utalok', `Fantaziak` = '$fantaziak', `Titkosvagyak` = '$titkos_vagyak, `Suly` = '$suly', `Magassag` = '$magassag', `Szemszin` = '$szemszin', `Hajszin` = '$hajszin', `Hajhossz` = '$hajhossz', `Mellboseg` ='$mellboseg', `Orarend` = '$orarend', `Beallitottsag` = '$szexualis_beallitottsag', `Pozicio` = '$pozicio', `Dohanyzas` = '$cigi', `Testekszer` = '$pc', `Tetovalas` ='$tetko', `Szilikon` ='$szilikon', `Fetish1` = '$pisiszex', `Fetish2` = '$kakiszex', `Fetish3` = '$domina', `Testekszerhely` = '$pchely', `Tetovalashely` = '$tetkohely', `Csillagjegy` = '$csillagjegy', `Parral` = '$par', `Virag` = '$virag' WHERE `Username` ='" . $_POST['username']. "'";
$result = #mysql_query($qry);
//Check whether the query was successful or not
if($result) {
header("location: perf_register_success.php");
exit();
I'm not sure if $_POST works here. I have the form, then the exec of that form, which works, then this form, and this is the exec of that.. Anyway I always get "query failed" message, which is in the else statement of the 'if' i'm using. What am i doing wrong?
Thanks!
The correct syntax for UPDATE is as follows:
UPDATE table SET columnA=valueA, columnB=valueB WHERE condition=value
(documentation here)
Thus, your query should look like the following:
$qry = "UPDATE performers SET Bemutatkozas = $bemuatkozas, Feldob = $feldob, Lehangol = $lehangol [...] WHERE Username ='" . $_POST['username']. "'
You'll have to replace [...] with all your values (that's gonna take some time) but hopefully you get the pattern.
Other than that there are a number of things you should improve/change in your code but I'll just point you to jeroen answer in this question since he pretty much covers it all.
You want UPDATE instead of INSERT for your second query.
Apart from that you really need to fix that sql injection error, preferably by switching to PDO or mysqli in combination with prepared statements. The mysql_* functions are deprecated.
And whatever solution you take, you need to add proper error handling, suppressing errors is wrong, especially when you try to fix a problem but even in a production site, errors need to be logged, not ignored.

Problems with mysql_real_escape_string

I have field called filter1 on a form, I would like to be able to save quoted text into mysql. So I would like to be able to save the value "foo bar"...instead its saving just /
Here is what I have:
$keyword1 = mysql_real_escape_string($_POST['filter1']);
Any help is appreciated.
Here is how I construct the query
$keyword1 = mysql_real_escape_string($_POST['filter1']);
$keyword2 = $_POST['filter2'];//."|".$_POST['filterby'];
$keyword3 = $_POST['filter3'];//."|".$_POST['filterby2'];
$urlfilter1 = $_POST['url1'];
$urlfilter2 = $_POST['url2'];//."|".$_POST['url_filter'];
$urlfilter3 = $_POST['url3'];//."|".$_POST['url_filter2'];
//echo "combo_id:".$num." <BR></br>";
//echo "status:".$status." <BR></br>";
//echo "saveQuery:".$saveQuery." <BR></br>";
//$myFilter = "save";
$insert_query = sprintf("UPDATE COMBINATION
SET STATUS_ID=%s, QUERY=\"%s\",
KEYWORD1=\"%s\", KEYWORD2=\"%s\", KEYWORD3=\"%s\",
URLFILTER1=\"%s\", URLFILTER2=\"%s\", URLFILTER3=\"%s\"
WHERE COMBINATION_ID=%s",$status,$saveQuery,
$keyword1,$keyword2,$keyword3,
$urlfilter1,$urlfilter2,$urlfilter3,
$num);
//echo "insert_query:".$insert_query." <BR></br>";
$result = mysql_query($insert_query) or die(mysql_error());
if($result)
{
echo "Saved successfully<br>";
}
}
?>
Unless you have a very old and restricted environment, use PDO. It will save you buckets of sweat and tears. With PDO it is very easy to escape input and avoid SQL injection attacks, which is illustrated in the answer that this link leads to.
Well first you need to connect to the database with mysql_connect() http://php.net/manual/en/function.mysql-connect.php
Then you need to call your INSERT query with mysql_query() http://php.net/manual/en/function.mysql-query.php
By the way, you are doing the right thing by escaping the string before putting it into a query, well done :)
For some reason you are escaping only one variable, while adding to the query several of them.
Why don't you escape them all?
However, your problem may be somewhere else.
What is $saveQuery I am curious?

Categories