I want to update a text field in my mysql database but it doesn't change when I run the query. I've tried stripping special characters but it still doesn't work.
UPDATE: It returns the following error: It gives the following error:
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 'datatext='LET OP! Aantal Mate' at line 1
Here is the data:
The HTML
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
<input type="hidden" name="nr" value="1">
<textarea rows="20" cols="50" name="text"></textarea>
</form>
The PHP
$change_text = $_POST['text'];
$change_nr = $_POST['nr'];
if ((!empty($change_text))&&(!empty($change_nr)))
{
mysql_query("UPDATE table SET datatext='$change_text' WHERE datanr='$change_nr'");
}
Structure MySQL (tablename = table)
datanr = int(6)
order = text utf8_general_ci
The text area is not to blame. your sql references a column name that your table doesn't seem to have.
Your schema has datanr and order while the update query has datanr and datatext.
Some more tips:
don't use mysql keywords as column or table names or at least escape them with `backticks` if you must.
always validate/sanitise your user input
don't use mysql but use mysqli, pdo or better yet, a good data access layer
try to check with key exists instead empty
if (array_key_exists('nr', $_POST)) {
$change_text = $_POST['text'];
$change_nr = $_POST['nr'];
mysql_query("UPDATE table SET datatext='$change_text' WHERE datanr='$change_nr'");
}
Debug your code
var_dump($_POST);
$change_text = $_POST['text'];
$change_nr = $_POST['nr'];
if ((!empty($change_text))&&(!empty($change_nr)))
{
$sqlString = "UPDATE table SET datatext='$change_text' WHERE datanr='$change_nr'";
var_dump($sqlString);
mysql_query($sqlString) or die(mysql_errno() . " " . mysql_error());
}
Your form lacks <input type="submit" />. Without submit button, form (and data) cannot be submitted.
Haha! I know the problem! It is the query. You must use those special quotes around column names. Like this: mysql_query("UPDATE table SET datatext='$change_text' WHERE datanr='$change_nr'");
Notice ` quotes aound datatext. Now your script should work. If it doesn't, I will shut down my pc and go to bed immediatelly lol
Your query should be like this:
mysql_query("UPDATE table SET datatext='".$change_text."' WHERE datanr=".$change_nr);
Related
I am a beginner to PHP and I am working on a profile page. The current problem is to change the name (This is a trial page that's why i am changing the name).For some reason i am getting the error:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'lastName ='Lname' WHERE email ='qwerty#example.com'' at line 1.
<?php
include('server.php');
$db = mysqli_connect('localhost','root','','userdata');
$query = "SELECT * FROM data WHERE email = '".$_SESSION['username']."'";
$result = mysqli_query($db,$query);
$data = mysqli_fetch_assoc($result);
?>
<html>
<head>
<title>Profile</title>
</head>
<body>
<form method="POST" action="">
<p>First name: <input type="text" name="fname" value="<?php echo htmlspecialchars($data['firstName']); ?>" > </p>
<p>Last name: <input type="text" name="lname" value="<?php echo htmlspecialchars($data['lastName']); ?>"> </p>
<p><input type="Submit" name="confirm" value="Confirm"></p>
</form>
<?php
if(isset($_POST['confirm']))
{
$db = mysqli_connect('localhost','root','','userdata');
$query = "UPDATE data SET firstName ='".$_POST['fname']."' lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
mysqli_query($db,$query);
echo mysqli_error($db); //For checking error.Remove afterwords.
}
?>
<p>HOMEPAGE</p>
</body>
</html>
The server.php is a page where I manage the backend of the entire operation so it's not involved in this operation.The first PHP block takes data from the table. The HTML block creates a form where the user can edit the data. The PHP block should update data into the table.
I would appreciate any tips to further improve my page as i am still new to this.Thanks in advance
UPDATE:- Adding , to the query still does not change the situation.
you have an error in your sql statement (as the error message suggests). in mysql the error message usually points out the exact position where the error occurs, and it usually quotes the first character/word that causes the problem.
in your case, that's lastname. Your update query so far is:
UPDATE data SET firstName ='fname' lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ error occured here
when you look-up how UPDATE queries are supposed to look like (mysql docs) you'd find, that the different updated fields must be separated by comma:
UPDATE data SET firstName ='fname', lastName ='Lname' WHERE email ='qwerty#example.com'
-- ^ add this here
also, you're vulnerable to sql injections (please read up on them, and how to prevent them - this is done by prepared statements)
Please try with that(there was a missing comma on your SQL query).
$query = "UPDATE data SET firstName ='".$_POST['fname']."', lastName ='".$_POST['lname']."' WHERE email ='".$_SESSION['username']."'";
The other problem of using code that is open to sql injection is you can easily change the syntax of an sql statement from the input side. For example if for last name you input "O'connor", you change the syntax. Try to use echo $query and then analyse the output or better still,copy it and run it directly without using php
As mentioned in the comment. When updating multiple fields you need to comma separate them:
UPDATE data
set
field1="meh", /* <-- comma */
field2="foo"
where otherField="something"
I am trying to make an update form using PHP, getting my data from MySQL 5. I have the fields set as a TINYTEXT type. My problem is when I attempt to display a field in my form for editing, the display stops at the first space. For example: my database my have "John Doe" in one field, but when I attempt to display that field I only see "John". Here is a portion of my code:
$id =mysql_real_escape_string ($_GET['id']);
if(isset($_POST['update'])) {
$UpdateQuery = "UPDATE members SET business_name='$_POST[business_name]', phone='$_POST[phone]', fax='$_POST[fax]', address1='$_POST[address1]', address2='$_POST[address2]', city='$_POST[city]', state='$_POST[state]', zip='$_POST[zip]', website='$_POST[website]', contact='$_POST[contact]', email='$_POST[email]', update_flag='$_POST[update_flag]', WHERE id='$id'";
mysql_query($UpdateQuery, $con);
}
$sql = "SELECT * FROM members WHERE id = $id";
$my_Data = mysql_query($sql,$con);
while($record = mysql_fetch_array($my_Data)) {
?>
<form action=listingupdate.php method=post>
<tr><input type=text name=business_name value=<?=$record['business_name']?> ></tr></br>
<tr><input type=text name=phone value=<?=$record['phone']?> > </tr></br>
<tr><input type=text name=fax value=<?=$record['fax']?> > </tr></br>
I have been googling several different ways, but I have not found what I am doing wrong. Would someone be so kind as to show my what I need to do to get all of the data in a field to display in my form?
Well a few things.. You should be using mysqli, not mysql since it is deprecated. Also you're calling mysql_real_escape_string on the id, but none of the other data so your script is wide open to SQL injection attacks. It looks like your code will fail if any of the posted data contains apostrophes. I'm not sure how you're planning to use GET and POST at the same time since your form, when submitted doesn't submit a GET value. With all that said, you should check the database to see if names are getting truncated in there, or if it's a client side issue.
I just updated this question.
I can't seem to update my database whenever I am putting variable $ecode on my WHERE condition. But when I echo this variable it always echoes its right value.
<?php
require 'sqlicon.php';
$q=$_GET['q'];
$ecode= $_GET['ecode'];
echo"".$ecode;
$result=$db->query("UPDATE offset_form SET Approved='".$q."' WHERE Employee_Code='".$ecode."'");
?>
this is the content of sqlicon.php:
<?php
$db=new mysqli('localhost','root','',dbuser'); //localhost,username,password, dbname
?>
This is where I am getting the date for $q and $ecode: Sorry if it haven't been in mysqli yet.
testingjava.php:
<html>
<title> Offset Requests </title>
<head><link rel="stylesheet" type="text/css" href="up.css"/></head>
<script>
function Approval() {
var name;
name=document.getElementById('ename').textContent;
if(document.form1.approval[0].checked true) {
alert(name);
window.location.href = "sqli.php?q=Yes" + "&ecode=" + name;
}
}
</script>
<body>
<form id="form1" name="form1" method="post" action="testingjava.php">
<?php
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("dbuser",$conn);
$query=mysql_query("Select * from offset_form where Approved=''");
while($fetch=mysql_fetch_array($query)) {
$ecode=$fetch['Employee_Code'];
//$_SESSION['ecode']=$ecode;
$ename=$fetch['Employee_Name'];
$epos=$fetch['Employee_Position'];
$edpt=$fetch['Employee_Department'];
$dleave=$fetch['Date_Leave'];
$dreturn=$fetch['Date_Return'];
$reason=$fetch['Offset_Reason'];
echo "".$ecode ."".$ename." ".$epos." ".$edpt." ".$dleave." ".$dreturn." ".$reason;
echo "<input type='radio' name='approval' onChange='Approval()'>Yes";
echo "<input type='radio' name='approval'>No";
echo "<input type='text' name='remarks' size='30'>";
echo"<hr id='br'></hr>";
echo"<input type='submit' value='Submit' name='send' onClick='Approval()'>";
}
?>
</form>
</body>
</html>
I am only testing to manipulate my database when I triggered a radio button.
1) you should be using mysql_real_escape_string($_GET[]) or someone with inject a mysql command into you system like DROP TABLE which will be the end of your database.
2)secondly I would move over to using PHP PDO it is more secure and it is faster (by a long way).
3) change your scond to last line from
mysql_query($sql,$conn);
to
mysql_query($sql,$conn) or die(mysql_error()." _____is the string correct? ".$sql);
then is should echo out any errors, if you post the echoed error we can probably fix it
having looked at it I am guessing the problem is you have missed the .. around the $q, so the $sql contains the string "$q" rather than the string assigned to the variable $q
try this
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");
try this way..
$sql=("update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'");
always try to echo your query and see what's going wrong with your query..
if password is set to your dbms the provide the third param passwrod
$conn = mysql_connect("localhost","root","<passwrod>");
or you can leave it blank if passwrod is not set.
and try this
$sql="update offset_form set Approved =$q where Employee_Code=$ecode";
or
$sql="update offset_form set Approved ='".$q."' where Employee_Code='".$ecode."'";
note: double quotes will parse the php variable ,
most probably there is problem in the manner of quotes you are using.
are you should your query is what you want?
One thing that is confusing is the fact that you have this commented out:
"INSERT INTO offset_form (Approved) VALUES ('".$ecode."')"
And then you have this as your update:
"UPDATE offset_form SET Approved = '$q' WHERE Employee_Code = '".$ecode."'"
The values you are using don't tally together. Surely you should have:
"UPDATE offset_form SET Approved = '$q' where Approved = '".$ecode."'"
This is because you are inserting $ecode into the column Approved, but then searching for $ecode in another column called Employee_Code. Perhaps you need to modify your insert statement instead? Either that or $ecode could be just representing two different values at different times?
quotes
The only way switching quotes will make a difference is if your embedded values contain quotes themselves. In which case using the correct escape function will sort the problem. So you are free to use either:
"UPDATE offset_form SET Approved = '$q' where Approved='$ecode'"
or:
"UPDATE offset_form SET Approved = '".$q."' where Approved = '".$ecode."'"
or:
'UPDATE offset_form SET Approved = "'.$q.'" where Approved = "'.$ecode.'"'
but not:
'UPDATE offset_form SET Approved = "$q" where Approved = "$ecode"'
either of the first three should not make a difference.
further things to do
backticks
As a rule I always write my queries escaping table and column names using backticks, just to make sure I'm not accidentally using a reserved word:
"UPDATE `offset_form` SET `Approved`='$q' WHERE `Employee_Code`='".$ecode."'"
double check your dataset
Make certain that the same query you are trying to run in PHP, works inside your dbms. This involves echoing the query out in PHP and then executing it via PHPMyAdmin, Navicat, or whatever you use to access your database outside of coding. For example, a query with hard-coded values, if this doesn't work you have a logic problem in your query or database design that has nothing to do with PHP:
"UPDATE offset_form SET Approved='13' WHERE Employee_Code='12'"
check your white space
Sometimes queries that seem they should be working are having problems because your column values contain accidental invisible white space. If so, they would only be selectable using something like:
"UPDATE offset_form SET Approved='$q' WHERE Employee_Code LIKE '%".$ecode."%'"
check user privileges
Make certain your MySQL user has the ability to perform the type of query you are attempting, this means allowing SELECT, INSERT and UPDATE queries.
disclaimer
As others have already stated, you should upgrade to non deprecated database access methods. If not, you should at least be using mysql_real_escape_string to better protect against malicious intent.
Please debug the value of $q and try to run this code:
session_start();
$q=$_GET['q'];
$ecode=$_GET['ecode'];
$conn = mysql_connect("localhost","root","");
if(!$conn)
echo ("Could not connect");
mysql_select_db("asiantech",$conn);
echo"".$ecode;
echo"<br>".$q;
$sql="update offset_form set Approved ='".mysql_real_escape_string($q)."' where Employee_Code='".$ecode."'";
//$sql = "INSERT INTO offset_form (Approved) VALUES ('".$ecode."')";
mysql_query($sql,$conn);
I tested the variables in the update statement and checked if a database connection is established, however the query doesn't run, can you please show me the error in my code.
for($i=0; $i <= $numcourses; $i++){
echo '<div class="new'.$i.'" id="new'.$i.'"><label>'.$course_names[$i].'</label>
<input name="edit'.$i.'" type="submit" value="Edit" /><input name="delete'.$i.'" type="submit" value="Delete" /><br /></div>';
$name="edit".$i;
if (isset($_POST[$name])){
echo '<input name="text" type="text" value="'.$course_names[$i].'" /><input name="save'.$i.'" type="submit" value="Save"/>';
}
$name2="save".$i;
if (isset($_POST[$name2])){
include "includes/open.php";
$newname=($_POST['text']);
$int=$i+1;
$query = "UPDATE course SET cname = '".$newname."' WHERE cid = '".$int."'";
mysql_query($query) or die(mysql_error());
include "includes/close.php";
}
}
Update: Thanx Marc B, adding or die(mysql_error());showed me the error in my code, everything works again and I'm back on track.
You have no error handling on your query calls:
mysql_query($query) or die(mysql_error());
^^^^^^^^^^^^^^^^^^^^^^
which would tell you if there's any problems with the query execution. On a meta level, you're wide open to SQL injection attacks, so you'd better read up about that and fix the problem before you go any further with your code.
$query = "UPDATE course SET cname = '".$newname."' WHERE cid = '".$int."'";
is cID an integer ? in the update statement, looks to me like a string, try to echo every query and check the validity by executing it directly in your db
where do you connect to the database??
use mysql_connect(string hostname, string username, string password'); to connect to the database and then execute the query after selecting your database using mysql_select_db..
First you should remove the extra ; on $name="edit".$i;;
Then, how do you post the values? I see no <form> attributes in your code, hence it cannot be posted.
Also, everything is in a for loop. $newname=($_POST['text']); is never being set.
Maybe instead of this:
if (isset($_POST[$name2]))
try this:
if ($name2!="")
I have been working on something like a sign up form for a facebook app but instead of INSERT it UPDATE because before that I have already INSERT
$inserP = "INSERT INTO particular (id, name)
VALUES ($userid, 0)";
pg_query($conn, $inserP);
and I come across this error after submitting the form with the username tom:
pg_query(): Query failed: ERROR: column "tom" does not exist LINE 2: SET name=tom
Here is my form
<form action="update.php" method="post">
<input type="text" name="username" id="username" autocomplete="off" />
<input type="image" name="confirm" src="/images/confirm.png"/>
</form>
Here is my update.php
require('conn.php');
require('getfacebookapi.php');
$userid = idx($facebook->api('/me/'), 'id', string);
$username=$_POST['username'];
$pszz = "UPDATE particular
SET name=$username
WHERE id=$userid";
if(preg_match("/^[a-zA-Z]+$/", $username)) {
pg_query($conn, $pszz);}
There is absolutely nothing wrong with my pg_pconnect.. Can someone tell me where I went wrong and how to fix this error? I'm new to both php and sql... Thanks!!
Never, never compose SQL statements by string concatenation or interpolation. Use bind parameters (PDO or at least pg_query_params).
You need to put quotes around your strings values, otherwise it will think it's a column.
SET name='tom'
WHERE id='someid'
name is a text field; inserting into text fields requires single-quotes around the value: 'tom'