I have two functions on the same webpage, each of them will update one different table on the same database depending which button you press.
This function modifies one table and works:
function SaveMItem()
{
$DayOfWeekNumber = 0;
if ($_POST['selDayOfTheWeek'])
{$DayOfWeekNumber = $_POST['selDayOfTheWeek'];}
mysql_query("UPDATE tblMItem SET ItemText = '" . $_POST['txtFirstOne'] . "' WHERE MenuItemID = " . (1 + $DayOfWeekNumber));
echo "SaveMItem Ok";
}
function SavetblAnnouncement(){
mysql_query("UPDATE TblAnuncios SET Title=".$_POST['txtAnnouncementTitle']. ",Content=".$_POST['txtAnnouncementContent']." WHERE 1");
echo "Completed announcement" ;
}
When I press SaveMItem button I can see the message SaveMItem Ok and it saves new values on Table.
When I press SavetblAnnouncement button I can see the message Completed announcement but the table TblAnuncios will not get updated.
As this is on the same file, the Database is the same and the function SaveMItem is able to update the table I suppose the connexion to the DB is ok.
Can anyone let me know what am I doing wrong?
Thanks in advance.
You're missing quotes around the values.
$title = mysql_real_escape_string($_POST['txtAnnouncementTitle']);
$txt = mysql_real_escape_string($_POST['txtAnnouncementContent']);
mysql_query("UPDATE TblAnuncios SET Title='".$title. "',Content='".$txt."' WHERE 1");
You should also escape the string, both to prevent SQL injection and also to make the query correct if the title or text contains quote characters.
Related
Here is a function I have in my php file
function deleteLocation() {
global $con;
$val = $_POST['id'];
$escaped = mysqli_real_escape_string($con,$val);
$sql = "DELETE FROM settings WHERE value = '".$escaped."'";
if(!mysqli_query($con,$sql)){
die("Query failed:" . mysqli_error($con));
} else {
die("DELETE FROM settings WHERE value = '".$escaped."' / num rows affected: " . mysqli_affected_rows($con));
}
}
Here is the text that is returned on the page
DELETE FROM settings WHERE value = 'asdasd ' / num rows affected: 0
If I take the first part, and run it on my phpmyadmin page,
DELETE FROM settings WHERE value = 'asdasd '
it will correctly delete the row, but as you can see from the output, 0 rows are affected when the script is run on the page.
If anyone can help to fix this I will be very grateful.
PS: The connection string and user permissions are indeed set up correctly, because every other function in this file works properly
EDIT: Got it, the space at the end of the string was a newline character that was sent from my javascript.
I tried re-creating your problem on my machine and the only time I get the same message as you is when that item was already deleted from the table (or when it wasn't there in the first place)
This was a pretty unique situation, so I don't know how much this would help other people but,
I had an array of strings that all had \n at the end, so I had to do
str[value] = str[value].trim();
foreach value in the array. It turns out that this was not a php problem, but rather js
Trying to update a mysql db by clicking a close button and updating the status attribute with "0" and echo'ing a "closed" verbiage. The current code I inherited from someone else updates the db if the job number is only numeric integers. When the job number is an alphanumeric or just alpha I get an error message:
UPDATE not successful: Unknown column 'test5' in 'where clause'
Initial updateTable comes from this function in a functions.php file:
function updateTable($table, $update, $where){
$query = ("UPDATE $table "."SET $update "."WHERE $where ");
$result = mysql_query($query)
or die("UPDATE not successful: " . mysql_error());
}
The closing of the record and update to mysql is done with this code:
if($_SESSION['login']){
include("functions.php");
$currentPOJO = $_GET["pojo"];
dbConnect();
$where = "pojo_number=".$currentPOJO;
updateTable("records", "status=0", $where);
echo "closed";
}
I have tried several changes with no luck. What am I missing?
Again updating a column in a db with "0" to signify closure of a record. The job number or "pojo" has to be able to have both alpha and numeric chars.
NOTE - My mysql db has the "status" attribute/column set to, varChar(35).
Thanks for any help possible.
Looks like you're missing a set of quotes:
$where = "pojo_number='". $currentPOJO ."'";
That makes the query change from:
WHERE pojo_number=test5 to WHERE pojo_number='test5'
I have a submission script that I wrote in PHP. It is used by multiple surveys at our organization. The surveys are created by other users. When they submit to the script, PHP puts the data into the appropriate table in MySQL. The error that I run into sometimes is that the user(s) update the form. They add a field, or rename an input and the script doesn't account for it since it expects everything to be the same. So, I am trying to find a way to make it accomodate for when a new field is added. Here is what I have:
if( mysql_num_rows( mysql_query("SHOW TABLES LIKE '".$survey."'"))){
echo "table exists";
$sql = "SELECT * FROM " . $survey . ";";
$result = mysql_query($sql)
or die(mysql_error());
$i=0;
while($row = mysql_fetch_row($result));{
echo $row[0];
foreach($_POST as $k => $v){
$i++;
if($k != $row[$i]){
$query = "ALTER TABLE " . $survey . " ADD " . $k . " VARCHAR(100);";
mysql_query($query)
or die(mysql_error());
}
}
}
}
I am used to doing while loops in JS, so I don't know if using i works here (actually, I know it doesn't work... because it doesn't work...). What I am trying to say is that if a key doesn't match a current field name, then add it to the table. How can I return $row correctly?
When I submit to the script it says:
Duplicate column name 'V4'
I have echo $row[0] but it returns a 1. Which is the is the int used in the primary key for the for the first record.
You have a ; at the end of your while loop declaration that shouldn't be there. Not sure if that is causing the problem as you don't say what the above code does do. Update the question if the ; is not the issue.
Your while loop declaration should look like this: while($row = mysql_fetch_row($result)) {
Also, as Marc B so diplomatically put it in a comment to your question, you should be escaping any user input that goes directly into a query.
The easiest way to do this is to use $survey = mysql_real_escape_string($survey), before your first use of $survey, as a start or switch to PDO/MySQLi and use input binding (prepared statements). Here are the prepared statements docs for PDO. More can, and should, be done to protect yourself, but the above is a good start.
I have php application which gets information from a SAML POST and creates a record in the MySQL database, if the record is already present it just updates it
Here is the code
//getMemberRecord returns true for successful insertion.
$row = $this->getMemberRecord($data);
if ($row) {
//if the row already exists
$this->updateMemberRecord($data)
} else {
// creates a new record
$this->setMemberRecord($data);
}
This code is causing double inserts in the database, we don't have a unique key for the table due to some poor design constraints, but I see two HTTP posts in the access logs happening at the same time.
The create date column is same or differs by a second for the duplicate record.
This issue is happening for only select few, it works for most of them.
The table is innoDB table and we can not use sessions on our architecture.
Any ideas of why this would happen
You said:
I see two HTTP posts in the access logs
You should try avoiding this and have just one http POST invocation
May be it is a problem related to concurrency and mutual exclusion. The provided code must be executed in a mutually exclusion zone, so you must use some semaphore / mutex to prevent simultaneous execution.
If you have two HTTP POST happening your problem is not on the PHP/MYSQL side.
One thing is allowing a second 'transparent' HTTP POST in the HTTP protocol. It's the empty url. If you have an empty GET url in the page most browsers will replay the request which rendered the page. Some recent browser are not doing it, but most of them are still doing it (and it's the official way of HTTP). An empty GET url on a page is for example <img src=""> or < script url=""> but also an url() in a css file.
The fact you have one second between the two posts make me think it's what's happening for you. The POST response page is quite certainly containing an empty Get that the browser fill by replaying the POST... I hate this behaviour.
I found that the double inserts were happening becuase double submits and our application doesnot handle double submits efficiently, I read up on some articles on this, here are some of the solutions
it always best to handle double posts at the server side
best solution is to set a UNIQUE KEY on the table or do a INSERT ON DUPLICATE KEY UPDATE
if you have sessions then use the unique token , one of the technique in this article
http://www.freeopenbook.com/php-hacks/phphks-CHP-6-SECT-6.html
or use can use the Post/Redirect/Get technique which will handle most double submit problems
http://en.wikipedia.org/wiki/Post/Redirect/Get
note: the Double submit problem only happens on a POST request, GET request is immune
public function setMemberRecord($data, $brand_id, $organization_id, $context = null)
{
global $gRegDbManager;
$sql = "insert into member ......"
$gRegDbManager->DbQuery($sql);
// Popuplate the iid from the insert
$params['iid'] = $gRegDbManager->DbLastInsertId();
$data = some operations
return (int)$data;
}
public function getMemberRecord($field, $id, $brand_id, $organization_id, $organization_level_account = null)
{
global $gRegDbManager;
$field = mysql_escape_string($field);
$id = mysql_escape_string($id);
$sql = "SELECT * FROM " . DB_REGISTRATION_DATABASE . ".member WHERE $field = '$id' ";
if($organization_level_account) {
$sql .= "AND organization_fk = " . $organization_id;
} else {
$sql .= "AND brand_fk = " . $brand_id;
}
$sql .= " LIMIT 1";
$results = $gRegDbManager->DbGetAll($sql);
if(count($results) > 0) {
return $results[0];
}
return;
}
/* * ******************************************************************************************************
* Updates member record in the member table
* *******************************************************************************************************
*/
public function updateMemberRecord($id, $changes)
{
global $gRegDbManager;
$id = mysql_escape_string($id);
if(!empty($changes)) {
$sql = "UPDATE " . DB_REGISTRATION_DATABASE . ".member SET ";
foreach($changes as $field => $value) {
$sql .= mysql_escape_string($field) . " = '" . mysql_escape_string($value) . "', ";
}
$sql = rtrim($sql, ", ");
$sql .= " WHERE iid = '$id'";
$gRegDbManager->DbQuery($sql);
} else {
return false;
}
}
i have written few codes to show time spent by users at site but when a users click on submit it should be stored in mysql but its not getting stored can you please tell where i have done mistake here is my code.
Your query seems to be wrong.
Either use INSERT without WHERE if you want to insert a new record. If however you want to update an already present record, use UPDATE instead of INSERT.
And it is always a good idea to check whether a query was successful:
if (mysql_query ("insert into jcow_accounts(Time_Spent) values ('{$Time}') where uid='{$client['id']}' ") === FALSE) {
echo 'MySQL error: ' . mysql_error() . "\n";
}
You need to use an UPDATE instead of an insert.
$dtime = getChangeInTime(); // this is the change in time from the last update
mysql_query( "UPDATE jcow_accounts SET `TIME_SPENT` = `TIME_SPENT` + $dtime ".
" where id='{$client['id']}'" );
Try
insert INTO `jcow_accounts` (`Time_Spent`) VALUES ('{$Time}') where uid='{$client['id']}' WHERE `uid` = '{$client['id']}'
Are you sure the uid is in the DB? try running it without the WHERE...