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."'";
Related
I've created this script to insert some data from PHP to MySQL, but it doesen't work, and I don't know why.
if (isset($_SESSION['userSession'])!="") {
$session_created=1;
$session_query = "SELECT * FROM users WHERE user_id=".$_SESSION['userSession'];
$session_query_result = $DBcon->query($session_query);
$user_row=$session_query_result->fetch_array();
}
if(isset($_POST['create_post_button'])){
$post_name = $DBcon->real_escape_string(strip_tags($_POST['post_title']));
$post_content = $DBcon->real_escape_string(strip_tags($_POST['post_content']));
date_default_timezone_set('Europe/Athens');
$post_date=date("Y-m-d h:i:sa");
$post_categ_id = $DBcon->real_escape_string(strip_tags($_POST['post_category']));
$post_creator = $user_row['user_name'];
$pass_flag=0;
$error_msg_cp = "Posted!";
$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
post_categ_id,post_user_name) VALUES ('$post_name','$post_content','$post_date','
$post_categ_id','$post_creator')";
echo "<br><br><br><br>".$create_post_query;
if($DBcon->query($create_post_query)){
$error_msg_cp="Error, pug!";
}
echo $error_msg_cp;
}
Thank you!
Edit:
The result of this code is:
Even with ini_set('display_errors', 'stdout'); it doesen't display the error...
This is the structure of the posts table in MySQL:
Seems to have a newline in your integer field.
Change your query like this. Single quote around '$post_categ_id' has changed.
$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
post_categ_id,post_user_name)
VALUES ('$post_name','$post_content','$post_date',
'$post_categ_id','$post_creator')";
echo "<br><br><br><br>".$create_post_query;
if (!$DBcon->query($create_post_query)){
$error_msg_cp="Error, pug!";
}
NB I suggest you to read this post How can I prevent SQL injection in PHP? to prevent your queries against SQL injections.
Change your insert query as follows, use '{$variable}' instead of '$variabe'
$create_post_query = "INSERT INTO posts(post_name,post_content,post_date,
post_categ_id,post_user_name) VALUES ('{$post_name}','{$post_content}','{$post_date}','
{$post_categ_id}','{$post_creator}')";
I've been trying to update my data according to the user session (UserLogin) but it kept saying: Data type mismatch in criteria expression. The print_r is just for testing purposes.
Thanks in advance,
Z
function Employee1_BeforeShow(& $sender)
{
$Employee1_BeforeShow = true;
$Component = & $sender;
$Container = & CCGetParentContainer($sender);
global $Employee1; //Compatibility
$Page = CCGetParentPage($sender);
$db = $Page->Connections["PettyCashMDB"];
$sql1 = "UPDATE Employee SET Employee.LastActive = Date() WHERE Employee.[EmpID] = ". $_SESSION['UserLogin'];
$db->query($sql1);
print_r($_SESSION['UserLogin']);
$db->close();
Employee1_BeforeShow #67-67106FAD
return $Employee1_BeforeShow;
}
EDIT: I've tried #NanaPartykar 's method and by accident I've noticed that it does get the value from $_SESSION['UserLogin'], just that somehow the datatype is different.
EDIT: It displays the error Data type mismatch but both of them are string and returns string.
Instead of Employee.[EmpID], use Employee.EmpID
You need some quotes:
$sql1 = "UPDATE Employee SET Employee.LastActive = Date() WHERE Employee.[EmpID] = \'". $_SESSION['UserLogin'] . "\'";
Z - There are a bunch of built-in Codecharge functions to assist with getting values from querystring, sessions and controls.
eg: CCGetSession("UserLogin", "default");
http://docs.codecharge.com/studio50/html/index.html?http://docs.codecharge.com/studio50/html/Components/Functions/PHP/Overview.html
and executing SQL with some validating (from 'Execute Custom SQL' help topic):
$db = new clsDBConnection1();
$SQL = "INSERT INTO report (report_task_id,report_creator) ".
"VALUES (". $db->ToSQL(CCGetFromGet("task_id",0),ccsInteger) .",". $db->ToSQL(CCGetUserID(),ccsInteger) .")";
$db->query($SQL);
$db->close();
The $db->ToSQL (and CCToSQL) functions convert and add quotes for relevant data types (ccsText, ccsDate).
There are many examples in the Manual under 'Examples' and 'Programming Reference' for PHP (and ASP, .NET, etc)
http://support.codecharge.com/tutorials.asp
I strongly suggest looking at some of the examples, as Codecharge will handle a lot of the 'plumbing' and adding a lot of custom code will causing problems with the generation of code. In your example, you should add a 'Custom Code' action to the Record's 'Before Show' Event and add your code there. If you add code just anywhere, the entire section of code (eg: Before Show) will change colour and no longer be updated if you change something.
For example, if you manually edited the 'Update' function to change a default value, then no changes through the IDE/Properties will change the 'Update' function (such as adding a new field to the Record).
Finally got it to work, this is the code $sql1 = "UPDATE Employee SET LastActive = Date() WHERE EmpID = '$_SESSION[UserLogin]' "; Thanks to everyone that helped out.
I have a page that brings up a users information and the fields can be modified and updated through a form. Except I'm having some issues with having my form update the database. When I change the update query by hardcoding it works perfectly fine. Except when I pass the value through POST it doesn't work at all.
if (isset($_POST['new']))
{
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = '$_POST[id_updated]',
name = '$_POST[name_updated]',
department = '$_POST[department_updated]',
email = '$_POST[email_updated]',
access = '$_POST[access_updated]'
where id = '$_POST[id_updated]'");
if (!$result1)
{
echo "Update failed!!";
} else
{
echo "Update successful;";
}
I did a vardump as an example early to see the values coming through and got the appropriate values but I'm surprised that I get an error that the update fails since technically the values are the same just not being hardcoded..
UPDATE supplies.user SET name = 'Drake Bell', department = 'bobdole',
email = 'blah#blah.com', access = 'N' where id = 1
I also based the form on this link here for guidance since I couldn't find much about PostGres Online
Guide
Try dumping the query after the interpolation should have happened and see what query you're sending to postgres.
Better yet, use a prepared statement and you don't have to do variable interpolation at all!
Do not EVER use data coming from external sources to build an SQL query without proper escaping and/or checking. You're opening the door to SQL injections.
You should use PDO, or at the very least pg_query_params instead of pg_query (did you not see the big red box in the manual page of pg_query?):
$result1 = pg_query($db,
"UPDATE supplies.user SET
id = $1,
name = $2,
department = $3,
email = $4,
access = $5
WHERE id = $6",
array(
$_POST[id_updated],
$_POST[name_updated],
$_POST[department_updated],
$_POST[email_updated],
$_POST[access_updated],
$_POST[id_updated]));
Also, when something goes wrong, log the error (pg_last_error()).
By the way, UPDATE whatever SET id = some_id WHERE id = some_id is either not really useful or not what you want to do.
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.
I have a little problem to save html-code in phpmyadmin.
Thats the html-code ($html_txt) which I would like to save in the sql-table. I get the code from an other sql-query.
An günstigen Tagen "Paradies" ist es dienlich.
Test/Test<br /><br />"Test"
And that is my query.
$id = 1;
$html = "'".$html_txt"'";
$sql = 'UPDATE table SET text = '.$html_txt.' WHERE id = '.$id.'';
That does not work. Any idea? I tried it also like this:
$id = 1;
$html_txt;
$sql = 'UPDATE table SET text = '.$html_txt.' WHERE id = '.$id.'';
You must escape the string statements before querying. Your query should be like the following:
$con = mysqli_connect("localhost","user","password","db");
$id = mysqli_real_escape_string($con, $id);
$html_txt = mysqli_real_escape_string($con, $html_txt);
$sql = 'UPDATE table SET text = ' . $html_txt . ' WHERE id = ' . $id . '';
I die if I do not say:
Please use parameterized query
Please avoid using vulnerable sql statements.
use mysql_escape_string to support for html entities and may the text be the kwyword so use like this text
$id = 1;
$html =mysql_real_escape_string($html_txt);
$sql = 'UPDATE table SET `text` = '.$html.' WHERE id = '.$id.'';
This should be a comment - but it's a bit verbose.
It should be obvious to most PHP developers that the problem is lack of escaping of the HTML string, however that in itself is not a reason for this being a poor question.
You've not provided details of any attempt to investigate the problem yourself. "Doesn't work" is not a good description of what happenned - in this case the expected outcome is fairly obvious to me, but that's not always the case. I aslo know what the actual outcome would be - but you've not documented that either. In most occassions where code does not behave as expected, an error message will be reported somewhere - you should be looking for it. The DBMS would have returned a specific error message - which your code should poll - especially if you are running into problems.
If you had viewed the SQL you were sending (or included it in your post) this would also have helped diagnosis.
You should properly escape your HTML value. Though this solution is not optimal as it does not use parameterized queries (PDO, ....), try this:
$html = 'An günstigen Tagen "Paradies" ist es dienlich. Test/Test<br /><br />"Test"';
$id = 1;
$sql = 'UPDATE table SET text = '.mysql_real_escape_string($html).' WHERE id = '.$id.'';
i would suggest you use mySQli prepared statement, WHY : i think somewhere along the line your variable have funny characters that r messing up with your query..with prepared statements the query is send alone then after your variables are binded to it, pls check above code
$conn = new mysqli("localhost", "your username", "your pass", "your db");
$myString = "Your string here";
$id = 1;
$insertDB = $conn->prepare("UPDATE table SET text = ? WHERE id = ?");
$insertDB->bind_param('si', $myString, $id); //bind data, type string and int 'si'
$insertDB->execute(); //execute your query
$conn->close(); //close connection