I have a HTML table having values from Mysql. My HTML table looks like this
------- ------ ------ ------
type name b_id Edit
------- ------ ------ ------
Laptop mac E1:23 edit
Desktop dell D2:45 edit
I am inserting values from input textboxes for type and name. And a select dropdown for b_id.
I can edit each row values by clicking editand i have a dropdown displaying all my b_id's.
I need to update b_id values so that, if it already exists replace with new delete the old.
For suppose i'l hit edit on Desktop dell row. And i'l select E1:23(which is already mapped for laptop mac). On saving this, E1:23 should map to desktop dell and previous mapping (laptop mac) should be deleted. I mean it should be empty
My Query
$id = $_REQUEST['id']; // Auto Increment
$b_id = $_REQUEST['b_id']; //b_id from select dropdown on edit
$sql = "SELECT * FROM table_name WHERE b_id='$b_id'";
$rs=parent::_executeQuery($sql);
$rs=parent::getAll($rs);
if($rs) // if b_id already exists
{
//First empty old b_id which has mapped already
$sql2 = "UPDATE table_name SET b_id='$b_id' WHERE id='$id'";
$rs=parent::_executeQuery($sql);
}
So how to empty previous mapped b_id. Not the type and name
If you want to empty the data in b_id, your query should be something like this:
if($rs) // if b_id already exists
{
//First empty old b_id which has mapped already
$sql2 = "UPDATE table_name SET b_id='' WHERE b_id='$b_id'";
$rs=parent::_executeQuery($sql2);
}
Related
Let us assume there is a form which has a text field and a submit button.
Every time I type a text and submit it should be stored in the database and displayed in a table.
Additionally, when I again submit the form the old text in SQL column value should be overwritten with this new value and both values should be displayed in table rows.
So every time I do this I want old data and new data to be appended to table rows.
How to achieve this??
Instead of overwriting the data, why not create a new entry and mark it as active, such that to get the latest data using sql, you order by primary key desc limit 1. If you need the old data you ust get the previous entry.
We have very few information, but here is some idea to achieve it :
1/ Add an last field in your table and update it each time you add a new data, then when you display it just get all data and check the last field to see which one is the last :
So imagine this table :
Table data
===============================
id_data | id_user | data | last
When you display it for your user :
select * from data where id_user = :id_user order by last desc;
This way you will get the last one with last = 1 (true) first then the other.
And when you submit a new data :
// you update all old data as "old"
update data set last = 0 where id_user = :id_user;
// you create a new data
insert into data (id_user, data, last) values (:id_user, :data, 1);
2/ Add a field date so you know wich one are older than other
Table data
==================================
id_data | id_user | data | created
When you display it for your user :
select * from data where id_user = :id_user order by created desc;
This way you will get the data order by the created date with the last one first.
And when you submit a new data :
// you create a new data with the current date
insert into data (id_user, data, created) values (:id_user, :data, NOW());
This solution is better I think so you can have some "historic" of each data.
Is it what you are looking for?
why not just append it with a pipe character like so... "|entry_data" then just explode it when you need it.
var data_array = explode("|",data);
print_r(data_array);
If you want to show all changes only for some users then better to save you last value in main table and create new history table for changes.
table_history
id | id_row | field | before | after
In this case you can without additional query show last value for some users and all data for others.
In this structure you also can save multiple fields data if you need.
And believe me, saving previous value in your table will make you life is easy in future.
In given below code i update field with new one insert data and also append your new data with old I hope this help you
Form from which you insert and update data
if(isset($_POST['submit']) && $_POST['submit']){
$text_field = $_POST['text_field'];
$query ="SELECT * FROM `table_name`"; //replace with your table name
$run=mysqli_query($conn,$query);
$result = mysqli_fetch_row($run);
$data = $result[1];
if(count($result)){
$last_string = $data.','.$text_field;
$update= "UPDATE `table_name` SET `text`='".$last_string."'";
mysqli_query($conn,$update);
}else{
$query = "INSERT INTO `table_name`(`text`) VALUES ('".$text_field."')";
mysqli_query($conn,$query);
}
}
?>
<form action="" method="POST">
<input type="text" name="text_field">
<input type="submit" name="submit">
</form>
view of data which is inserted
<?php
$query ="SELECT * FROM `table_name`";
$run=mysqli_query($conn,$query);
$result = mysqli_fetch_row($run);
if(isset($result) && count($result)){
echo "<p>$result[1]</p>";
}
I have a table which looks f.ex. like this:
id (primaryKey, auto_increment) | fruit | color
I would like to insert values for fruit and color, if the fruit value does not exist, else I would like to update just the color and get back the id of the inserted or updated row.
F.ex. if I have a row with:
1234 | apple | red
and want to update the color of the apple to green, without knowing that there is already a row containing an apple. I use this code:
$sqli = get_db();
$q1 = "INSERT INTO table (fruit, color) VALUES ('apple', 'green') ON DUPLICATE KEY UPDATE color='green', id=LAST_INSERT_ID(id)";
$r1 = $sqli->query($q1);
$insertedOrUpdatedID = $sqli->insert_id();
I want to update the existing row to:
1234 | apple | green
and get back the id (1234) in $insertedOrUpdatedID.
I think I need to tag the fruit column in any way. When I'm executing this code, it always creates a new row (1235|apple|green) without updating the existing one or returning the edited id.
SOLUTION:
Changing the type of 'fruit' from text to varchar(100) and setting its KEY to UNIQUE solves the problem. Moreover change the last line of the code to:
$insertedOrUpdatedID = mysqli_insert_id( $sqli );
in order to get the right ID.
Happy coding!
If you want to update by fruit name so create fruite as UNIQUE KEY
Try this query
REPLACE INTO table_name (fruit,color) VALUES ('apple','green');
OR
INSERT INTO table_name (fruit,color) VALUES ('apple','green') ON DUPLICATE KEY UPDATE color = 'green;
I have a table with the following fields: gallery(picID, picTimeStamp, location).
What I want is that when someone is uploading a new picture to the gallery, the location will get the same value that picID gets (and picID gets its value by auto increment).
I have tried:
"INSERT INTO gallery(picID, picTimeStamp, location) VALUES (null,'.time().',picID)"
but it is not working. I do not get any errors, the location just always has a zero in it.
Thanks!
You should probably be using trigger like this
CREATE TRIGGER trigger_name BEFORE INSERT ON gallery FOR EACH ROW
BEGIN
DECLARE next_id INT;
SET next_id = (SELECT AUTO_INCREMENT FROM gallery WHERE TABLE_NAME='gallery');
SET NEW.location=next_id;
END
edit: Should be after insert trigger instead of before because auto_increment number only gets set after the record is inserted. Sorry bout that!
Your table should be like this:
id | int | primary key/autoincrement
order | int | index
picTimeStamp | timestamp
and then if you want to create a new entry below pass the order number by GET:
function createBelow(){
if(isset($_GET["orders"])){
$orders = $_GET["orders"];
$query = "UPDATE links SET orders=orders+1 WHERE orders>$orders ORDER BY orders DESC";
mysql_query($query);
$query = "INSERT INTO `mydb`.`mytable` (`orders`) VALUES ($orders+1);";
mysql_query($query);
}
}
The default value takes care of id and timestamp, you don't enter these.
I am using Php to insert values into MySQL table.
What i am trying to do is:
There are three columns that i have to check. 'namel1', 'namel2' and 'namel3'.
Conditions:
If '$name' does't exist in any of the three column then put value in 'namel1'.
If '$name' exist in 'namel1' then put value in 'namel2' and if 'namel2' contains the value then put it in 'namel3'.
My current MySQL query to insert name and image path is this i want to modify it to meet above conditions:
$chk_img_db = mysql_query("select * from cvapptable where img_path='$cvh_myimg_url'");
if(mysql_num_rows($chk_img_db)<1) {
mysql_query("insert into cvapptable(namel1,img_path) values ('$name','$cvh_myimg_url')");
}
I unable to get any solution from web.
Please help. Thank you.
It's not easy to find on the net because it's a situation you shouldn't get yourself into.
You should consider normalizing the table.
Instead of having a table with the columns:
cvapp: id | img_path | namel1 | namel2 | namel3
Consider changing it to two tables:
cvapp: id | img_path
names: id | cvapp_id | name
To then select every name, you just do a query like so:
SELECT name
FROM cvapp INNER JOIN names on cvapp.id = names.cvapp_id
WHERE <condition>
That way, you can have as many names as you want, and it's much easier to insert a new one:
INSERT INTO names (cvapp_id, name) VALUES (56, "Name 1");
INSERT INTO names (cvapp_id, name) VALUES (56, "Name 2");
INSERT INTO names (cvapp_id, name) VALUES (56, "Name 3");
you can try self join and search column of you tables
I have some insurance information in a website, and I'd like to only edit certain fields the user wants to change like for example:
user, id, phone, address, city
and the user wants to change his city and phone...do i have to make a query for each specific case or is there a code that can help me retrieve the key(phone) and value (9397171602)??
to then send it in a query
Basic update would take the form of:
UPDATE table_name SET column_1 = value_1, column_2 = value_2 WHERE column_3 = value_3
Where col1, col2 would be your city and phone, and col3 would be the user id. Check out the MySQL website http://dev.mysql.com/doc/refman/5.0/en/update.html for more info
There are number of ways to update a record safely. Conside the following pseudo code + php program.
class Example
{
function UpdateRecord($editedRecord)
{
//Fetch existing record from the database
$originalRecord=DB::fetchExample($editedRecord->getId())
//validate each edited field and it is valid then assign its value
//to the originalRecord's field
if(IsValid($editedRecord->getName())
{
$originalRecord->setName($editedRecord->getName());
}
.....
//update the record.
$originalRecord->Update();
}
}
Just add some sql to it:
$sql = "UPDATE example SET col_1 = val_1, col_9 = val_9 WHERE col_7 = val_7";
mysql_query($sql);
Then replace the columns and values with you stuff. For further info: PHP MySql Update