want insert a duplicate entry into mysql with a suffix. here is an example:
+-------+--------------+-------+
| ID | Title | url |
+-------+--------------+-------+
+-------+--------------+-------+
| 1 | test | test1 |
+-------+--------------+-------+
| 2 | test | test2 |
+-------+--------------+-------+
| 3 | test | test3 |
+-------+--------------+-------+
means, i want to add auto number as suffix to end of each url that have duplicate title. titles are duplicated but url are kinda unique.
Here is query:
$i = 0;
$i++;
$sql = "INSERT INTO `content` (title, text, cat, url, tag)
VALUES ('".$_POST["title"]."', '".$_POST["text"]."', '".$_POST["category"]."', '".$_POST["url"]."', '".$_POST["tag"]."') ON DUPLICATE KEY UPDATE url=".$_POST["url"]."+". $i ."";
note: url made dynamically based on title entry.
this query not working, what is wrong with my code?
UPDATE: here is error after run query:
error: INSERT INTO content (title, text, cat, url, tag) VALUES
('test', '', '16', 'test', '') ON DUPLICATE KEY UPDATE url=test+1
Unknown column 'test' in 'field list'
Your code has some strange things. $i = 0; followed by $i++; is just equivalent than doing $i = 1; But then again, what's the purpose on setting a variable that you only use once?
What you really need to do is:
INSERT query forgetting about the "url" field and removing the ON DUPLICATE...
Get the ID of the last insert. Have a look at the following link to see how to get that value: http://www.w3schools.com/php/php_mysql_insert_lastid.asp
UPDATE query to set the value of "url"
$_POST["url"].$id_of_last_query
Related
I have searched that there is already a way in inserting avoiding the duplicate error
ref: MySQL: Insert record if not exists in table
INSERT INTO table_listnames (name, address, tele)
SELECT * FROM (SELECT 'Unknown' AS name, 'Unknown' AS address, '022' AS tele) AS tmp
WHERE NOT EXISTS (
SELECT name FROM table_listnames WHERE name = 'Unknown'
) LIMIT 1;
Query OK, 1 row affected (0.00 sec)
Records: 1 Duplicates: 0 Warnings: 0
SELECT * FROM `table_listnames`;
+----+---------+-----------+------+
| id | name | address | tele |
+----+---------+-----------+------+
| 1 | Rupert | Somewhere | 022 |
| 2 | John | Doe | 022 |
| 3 | Unknown | Unknown | 022 |
+----+---------+-----------+------+
is there a way for this to do in batch?
or how is the format in adding data as a batch
ref: insert multiple rows via a php array into mysql
Planning to integrate this one
$sql = array();
foreach( $data as $row ) {
$sql[] = '("'.mysql_real_escape_string($row['text']).'", '.$row['category_id'].')';
}
mysql_query('INSERT INTO table (text, category) VALUES '.implode(',', $sql));
is there a way?
I would suggest using the ON DUPLICATE KEY syntax for this. This will simplify the query, and allow the use of the VALUES() statement, which is handy to pass parameters from your application.
For this to work, you need a unique (or primary key) constraint on colum name. Create it if it does not exist:
create unique index idx_table_listnames on table_listnames(name);
Then, you can do:
insert into table_listnames(name, address, tele)
values('Unknown', 'Unknown', '022')
on duplicate key update name = values(name)
The conflict clause traps violations on the unique index, and performs a no-op update.
Side note: use parameterized queries to pass data from your application to the query; escaping input is not enough to make your query safe.
Table_A
+--------+-----------+---------+
| id | name | views |
+--------+-----------++--------+
| num | text | int |
+--------+-----------+---------+
| 1 | Video 1 | 10 |
| NULL | NULL | 0 |
| NULL | NULL | 0 |
| NULL | NULL | 0 |
| NULL | NULL | 0 |
+--------+-----------+---------+
<a href="video.php?id=video1&idtitle=Hello%20Video1">
<a href="video.php?id=video2&idtitle=Hello%20Video2">
<a href="video.php?id=video3&idtitle=Hello%20Video3">
I'm trying to make the script do something like this.
1.User click on link
2.User is on video.php?id=video1
3.Mysql then add a +1 to my id column #1
4.then take the video title from $videoName
5.Mysql take the title inside of $videoname and store it on name column #2
6.Mysql then add +1 to Views everytime ID 1 is view
7.Mysql is now finish with Row 1
8.Now Mysql will repeat that same step if video.php?id=video2 and so on,
How can i make this happen?
$id = $_GET['id'];
$videoName = $_GET['idtitle'];
$pdo = new PDO('mysql:localhost;dbname=videocount', 'root', '');
$userip = $_SERVER["REMOTE_ADDR"];
if($userip){
$pdo->query("UPDATE Table_A SET (`id`, `name`, `views`)
VALUES (NULL,$videoName, views+1)");
}
I also try the code below but still no luck.
if($userip){
$pdo->query("INSERT INTO `videocount`.`Table_A` (`id`, `name`, `views`)
VALUES (NULL, '$videoname', 'views'+1)");
}
UPDATE instead of UPDATED, VALUES instead of VALUE. In addition you have to add a WHERE condition to your query to select record to update.
This is another correct syntax:
$pdo->query( "UPDATE `Table_A` SET `views`=`views`+1 WHERE `id`='$id'" );
Edit:
To update also the video name you can perform this query:
$pdo->query( "UPDATE `Table_A` SET `name`='{$videoName}', `views`=`views`+1 WHERE `id`='$id'" );
On the border, you should bind the variable values to avoid errors with titles special characters.
See more about binding and MySQL UPDATE syntax
I think there is a little confusion about data view logic.
First of all, you need to save all data into database, then list them for user.
When the use click the link to view this video, the column of views need to be updated.
I've created a table like this,
id | option_name | value | user_id
----------------------------------------------
1 | name | Joe | 1
----------------------------------------------
2 | age | 30 | 1
----------------------------------------------
3 | sex | male | 1
----------------------------------------------
4 | name | Jane | 2
----------------------------------------------
5 | age | 28 | 2
----------------------------------------------
6 | sex | female | 2
----------------------------------------------
I want to update all rows corresponding of user_id and option_name.
If user_id == 3, when i submit form with option_name (name,sex,age) as fields, if there is no rows with user_id == 3 then insert rows but if rows exist i want to update those row with new values for value field.
Please check my code: http://pastebin.com/THQdYpix
I want to reduce query steps in my code, any idea?
First check if it updates or note if the mysql_query() returns false then you can use insert query and execute the query.
Use INSERT ... ON DUPLICATE KEY UPDATE.If you want to do this in a single statement, I would recommend using the INSERT ... ON DUPLICATE KEY UPDATE syntax, as follows:
INSERT INTO table (id, someothervalue) VALUES (1, 'hi mom') ON DUPLICATE KEY UPDATE someothervalue = 'hi mom';
The initial INSERT statement will execute if there is no existing record with the specified key value (either primary key or unique). If a record already exists, the following UPDATE statement (someothervalue = 3) is executed.
Below query will work.
REPLACE INTO `table1`
( `name`,`sex`,`age` )
VALUES
( 'Mark', '29', 'male' )
ON DUPLICATE KEY UPDATE user_id=3;
I want a column in my database to have a default value which is the same for every row, however the last characters should be the primary key of the row.
Is this possible to implement using PHP/MySQL?
e.g(I want the Link column to have the default value)
+----+----------------------------+
| ID | Link |
+----+----------------------------+
| 1 | edit_item.php?id=1 |
| 2 | edit_item.php?id=2 |
| 3 | edit_item.php?id=3 |
+----+----------------------------+
Thanks very much for any help!
At the time of insert you need to insert and update your record.
Firstly insert your record and then get last inserted id and then update record eg:
<?php
$sql = "INSERT INTO TableName(Link) VALUES ('edit_item.php')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
} else {
$id = mysql_insert_id();
mysqli_query($con,"UPDATE TableName SET Link='edit_item.php?id=".$id."' WHERE id=$id);
}
You can't dynamically set the default, but you can definitely use some sort of replacement with printf(), such as the following:
Schema:
CREATE TABLE links (
id INT PRIMARY KEY AUTO_INCREMENT,
link TEXT DEFAULT "edit_item.php?id=%d"
);
And then in PHP, replace the %d with the ID using printf(),
<?php
// Let's assume it's an array with this format:
// ['id' => 1, 'link' => 'edit_item.php?id=%d']
$row = yourSelectCommandThatReturnsAnObject();
// In this case, $row['id'] will replace the %d.
$link = printf($row['link'], $row['id']);
You can check out the PHP docs for printf() for some more info.
How in php/mySQL can i make a column equal another column?
id is auto increment, xid should be unique. Can i make xid = id in SQL? (the reason for this is to log changes but i'll explain more if needed)
To make xid unique the best way is to copy the auto increment of id
+----+-----+----------+----------------+------+---------+
| id | xid | title | body | page | visible |
+----+-----+----------+----------------+------+---------+
| 1 | 1 | my title | my body | NULL | 1 |
| 2 | 2 | my title | my body edited | 1 | 0 |
+----+-----+----------+----------------+------+---------+
$queryX = "INSERT INTO table (xid, title, body, page, visible)
VALUES (, 'Plays', 'it's playing', 'book page', 1)";
I don't understand why you want to do this, but my approach would be using two queries and LAST_INSERT_ID():
INSERT INTO table (title, body, page, visible)
VALUES ('Plays', 'it''s playing', 'book page', 1);
UPDATE table SET xid = id WHERE id = LAST_INSERT_ID();
You may want to do this using a TRIGGER, so you don't have to do it manually.
In one query:
INSERT INTO table (xid, title, body, page, visible) VALUES
( SELECT MAX(xid) + 1, .... )
it will put unique xid, can be done with id also, I not quite sure I undestand the need...