Update statement not updating table but inserting new entry into table instead - php

For the life of me I cannot figure out why my update statement will not update the table row but instead it creates a new row. I have an ID column that is the unique identifier and is auto_increment, I am just not sure if you can update an auto_incremented data set the way i am trying to.
I have a form that is echo'ing data from the database into the fields and then am using it to edit the fields and update them.
The code:
<?php
$EntryID = $_GET['Eid'];
$IDlist = mysql_query("SELECT * FROM BD WHERE Id='$EntryID'");
$IDresults = mysql_fetch_array($IDlist);
$update_query = "UPDATE `BD` SET `Id` ='$IDresults['Id']',`EntryTitle` = '$MyTitle',`EntryDescription` = '$MyDescription',`Category` = '$MyCategory' WHERE `Id` ='$EntryID'";
mysql_query($update_query);
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else{
header('location: /admin/bd-edit-entry.php?sub=1');
exit();
}
mysql_close($con);
?>
Any help or advice would be a great.

SET `Id` ='$IDresults['Id']'
should be either:
SET `Id` ='$IDresults[Id]'
or
SET `Id` ='{$IDresults['Id']}'
If you turn on error reporting, you should get errors about a bad index.
Or you can leave this column out of the update entirely, since this column isn't changing.

Related

Adding constant to values in Mysql and updating the values to the result

I have got MySQL table with three columns 'primary Key','debit_cash','user_id' So now i want to update the debit_cash values to the corresponding user_id by adding "15" to the value already present. The debit_cash is in VARCHAR so i tried converting to int and sum it , but still the values in MySQL is not changing .
Here is my code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$user_id = $_POST['user_id'];
//importing database connection script
require_once('dbConnect.php');
//Creating sql query
$sql = "SELECT cos_details.debit_cash AS debitCash,
(convert(int, debit_cash)+15) AS updatedDebitCash
FROM cos_details
UPDATE cos_details SET debit_cash = '$updatedDebitCash'
WHERE user_id = $user_id";
//Updating database table
if(mysqli_query($con,$sql)){
echo 'Updated Successfully';
}else{
echo 'Could Not Update Try Again';
}
//closing connection
mysqli_close($con);
}
Any one please help me.
Seems that you don't need the select but the update only
UPDATE cos_details SET debit_cash = cast( (convert(int, debit_cash)+15) as VARCHAR(20))
WHERE user_id = $user_id
could be that your user_id is a string too so you should surround the value with quote
UPDATE cos_details SET debit_cash = cast( (convert(int, debit_cash)+15) as VARCHAR(20))
WHERE user_id = '$user_id'

SQL insert and update in the same time

Hey I have a query that will insert into the table a new data and I want that in the same time update an outher table with the id of the new data that I have entered. ex:
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$query = mysql_query("SELECT `id` FROM `test` WHERE `name` = 'Mark'");
$id = mysql_result($query,0);
mysql_quey("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
How do I do it at same time? because doing it this way I only insert the new data and I dont update the other.
Cumps.
Try this :
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$id = mysql_insert_id();
mysql_quey("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
I've changed the backticks to single quotes in your first insert for the values, backticks should never be used for field values.
Also I've changed it to use only two queries, the mysql_insert_id() will get the last inserted id without you needing to query it.
Ref : http://www.php.net/manual/en/function.mysql-insert-id.php
First of all, you do not need the select to get the id, there is mysql_insert_id() for that.
Then you have to use a transaction to make both queries feel like executed at the same time:
mysql_query('BEGIN');
mysql_query("INSERT INTO `test` (`name`) VALUES ('Mark')");
$id = mysql_insert_id();
mysql_query("UPDATE `test2` SET `test_id` = $id WHERE `name` = 'Mark'");
mysql_query('COMMIT');
A transaction makes sure both statements are executed, and no other script can come between them in any way.

replace not updating in database

I have a table with id which is the primary key and user_id which is a foreign key but the session is based on this in my code.
I have tried EVERYTHING, so I will post my full code.
The form should insert if there is not a user_id with the same session_id in the table. If there is, it should update.
At the moment, when the user has not visited the form before (no user_id in the table) and data is inserted in, the page returns to the location page: but the data is not inserted in the table. if the user changes the data once it is updated it doesn't change either.
This is the table structure:
`thesis` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_id` int(11) NOT NULL,
`thesis_Name` varchar(200) NOT NULL,
`abstract` varchar(200) NOT NULL,
`complete` int(2) NOT NULL DEFAULT '1',
PRIMARY KEY (`id`),
KEY `user_id` (`user_id`)
)
The code I have been using (and failing):
$err = array();
$user_id = intval($_SESSION['user_id']);
// otherwise
if (isset($_POST['doThesis'])) {
$link = mysql_connect(DB_HOST, DB_USER, DB_PASS) or die("Couldn't make connection.");
// check if current user is banned
$the_query = sprintf("SELECT COUNT(*) FROM users WHERE `banned` = '0' AND `id` = '%d'",
$user_id);
$result = mysql_query($the_query, $link);
$user_check = mysql_num_rows($result);
// user is ok
if ($user_check > 0) {
// required field name goes here...
$required_fields = array('thesis_Name','abstract');
// check for empty fields
foreach ($required_fields as $field_name) {
$value = trim($_POST[$field_name]);
if (empty($value)) {
$err[] = "ERROR - The $field_name is a required field" ;
}
} // no errors
if (empty($err)) {
$id = mysql_real_escape_string($_POST['id']);
$thesis_Name = mysql_real_escape_string($_POST['thesis_Name']);
$abstract = mysql_real_escape_string($_POST['abstract']);
//replace query
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query))
echo "the query failed";
else header ("location:myaccount.php?id=' . $user_id");
}}}
$rs_settings = mysql_query("SELECT * from thesis WHERE user_id = $user_id;");
?>
<br>
<form action="thesis.php" method="post" name="regForm" id="regForm" >
class="forms">
<?php
$num_rows = mysql_num_rows($rs_settings);
if($num_rows > 0) { ?>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
Title of Proposed Thesis<span class="required">*</span>
<textarea name="thesis_Name" type="text" style="width:500px; height:150px"
id="thesis_Name" size="600"><?php echo $row_settings['thesis_Name']; ?> </textarea>
</tr>
<tr>
<td>Abstract<span class="required">*</span>
</td>
<td><textarea name="abstract" style="width:500px; height:150px"
type="text" id="abstract" size="600"><?php echo $row_settings['abstract']; ?>
</textarea></td>
</tr>
<?php }
} else { ?>
//shows fields again without echo
I've tried var_dum($query) but nothing appears
PS I know the code isn't perfect but I'm not asking about this right now
I can't see how your replace statement will ever insert the initial row, as the where clause is always going to be false (there won't be a row with that user Id).
I think of you want to use replace you need to replace into thesis (id, userid, etc) without a where clause. If id and userid have a unique constraint and a row for userid exists then it will be updated; if it doesn't exist it will be inserted.
However- if you don't know id- which you won't if you are using auto increment, then I'm not sure you can do this with replace. See http://dev.mysql.com/doc/refman/5.0/en/replace.html
Why don't you check for the existence of a row an then use update or insert?
BTW, is the idea that a user can enter multiple theses into a form, or just one? Your table suggests they can have multiple. If this is what you are trying to achieve then I think you should be storing the id of each thesis in a hidden field as part of the form data. You would then be able to use REPLACE INTO thesis (id, user_id, thesis_name, abstract) VALUES ($id, $user_id, $thesis_name, $abstract) where id is the id of the thesis obtained from each hidden field. If this is not present, i.e. the user has entered a new thesis, then use NULL for id in the insert. This will work using the REPLACE INTO as the id column is auto increment.
Perhaps you mean user_id not id:
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE user_id='{$_SESSION['user_id']}'";
Or if you do mean the id from $_POST['id']
$query = "REPLACE INTO thesis ( thesis_Name, abstract)
VALUES ('$thesis_Name','$abstract')
WHERE id='$id'";
Also instead of REPLACE you should use UPDATE. Im pretty sure its faster because REPLACE basically deletes the row then inserts it again, im pretty sure you need all the fields and values else your insert default values. From the manual:
Values for all columns are taken from the values specified in the
REPLACE statement. Any missing columns are set to their default
values, just as happens for INSERT
So you should use:
$query = "UPDATE thesis
SET thesis_Name='$thesis_Name', abstract='$abstract'
WHERE id='$id'";
You are doing everything right just one thing you are doing wrong
Your replace query variable is $query and you executing $the_query.
you wrong here:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($the_query)) // this is wrong
echo "the query failed";
replace it with:
$query = "REPLACE INTO thesis ( thesis_Name, abstract) VALUES ('$thesis_Name',
'$abstract') where id='$_SESSION[user_id]'";
if (!mysql_query($query)) // use $query
echo "the query failed";

Update/Insert into mysql query

I am trying to perform a update/insert into query for MySQL. Should insert, if not already in database.
However, it will not update. My db connection is good. I cannot figure it out.
$sql = "UPDATE jos_bl_paid SET u_id='$uid', m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND '$mid' = m_id ";
$test45 = mysql_affected_rows();
if ($test45 == 0) {
$sql = "INSERT INTO jos_bl_paid(paypal_payment,u_id,m_id,pd,t_id,p_date)VALUES('$txn','$uid','$mid','1','$cus',NOW())";
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
echo 'Yes';
}else{
echo 'No';
}
From the code you are showing you aren't even running the update query. You need to put
if (!mysql_query($sql)) {
error_log(mysql_error());
exit(0);
}
before the line
$test45 = mysql_affected_rows();
for that to even return what you want
I would make these into one statement using the ON DUPLICATE KEY UPDATE mysql command. I would guess that your problem is that the insert may be failing because of some unique key set in you schema even though the actual uid doesn't yet exist so the update also fails. Can you post exactly what error message you get?
check your last value in update query i found an error there and have fixed it from my side
try this
$sql = mysql_query("UPDATE jos_bl_paid SET u_id='$uid',m_id = '$mid', t_id = '$cus', pd = '1', paypal_payment='$txn',p_date=NOW() WHERE u_id = '$uid' AND m_id = '$mid'") or die(mysql_error());
Answer is updated try the updated one
From the code you posted, it appears that you're setting the $sql string to an update statement, but not executing it before checking for the number of affected rows.
You'll probably need to call mysql_query($sql) before checking mysql_affected_rows();
Otherwise you're not telling the database to update anything.
If the new values in update are the same as old one mysql won't update the row and you will have mysql_affected_rows be 0. If you have primary key on fields u_id, m_id you can use INSERT ON DUPLICATE UPDATE http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html
If you don't have such you may use the count query:
SELECT count(*) FROM jos_bl_paid WHERE u_id = '$uid' AND '$mid' = m_id
To decide if you should update or insert new one.

php - duplicate entry

what should do if the entry are doubled?
<?php
require_once('auth.php');
session_start();
$exam = $_SESSION['exam'];
$subject_id = $_SESSION['exam'];
$_SESSION['sub'] = $subject_id;
$subject_title = $_POST['subject_title'];
$subject_description = $_POST['subject_description'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('db_compre', $con);
$sql = "INSERT INTO examsubjectrecord_table(subject_id , subject_title ,
subject_description)
VALUES ('$subject_id','$subject_title', '$subject_description')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
else
{
header("location: addsubject.php?exam=".$exam ."");
}
?>`
Notice: A session had already been started - ignoring session_start() in C:\xampp\htdocs\compre\admin\addsubjectacc.php on line 4
**Error: Duplicate entry '1' for key 'PRIMARY'**
It depends on yout application business-logic.
You can notify a user about a duplicated entry or silently update information with INSERT ... ON DUPLICATE KEY UPDATE ... SQL statement.
In your database you have a primary key of subject_id which cant have duplicates.
If you need to have duplicates in the subject_id column then you should add a column and set it as a primary key in your database. For example add another column unique_id and set it to auto_increment and as a primary key for row identification.
Basically, you'll first want to check if the value you're trying to insert into your primary key field already exists.
So if you primary key field is subject_id, you'd need to check if that already exists by doing a select query followed by PHP's mysql_num_rows function. For example:
$subject_id = 1337;
$check = mysql_query("SELECT `subject_id` FROM `examsubjectrecord_table` WHERE `subject_id`=" . $subject_id);
// See if anything was returned
if(mysql_num_rows($check) > 0) {
// We have something with this subject_id already!
echo "Cannot insert duplicate subject!";
} else {
// All clear, run your INSERT query here
}
Which column is your primary key? I'm going to assume that's subject_id. This needs to be unique for each row in your table. The easiest way to ensure this is to use AUTO_INCREMENT and then avoid inserting the subject_id at all. It will be assigned automatically.
If you need to find out what the ID of new subjects is, you can use mysql_insert_id.

Categories