This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
“INSERT IGNORE” vs “INSERT … ON DUPLICATE KEY UPDATE”
Hello peoples
$sql1="SELECT * FROM `table` WHERE `user` = '$user'";
$res1=mysql_query($sql1);
if(!$res1||mysql_num_rows($res1)<1){
$sql2="INSERT INTO `table` (`user`) VALUES ('$user')";
$res2=mysql_query($sql2);
if(!$res2){echo 'Yes';}else{echo 'No';}
}
else{echo 'user already exists!';}
Can to combine the two queries into one?
If you set your column user to UNIQUE, there'll be a maximum of ONE entry of each user. To ALTER TABLE and make the column UNIQUE:
ALTER TABLE `table`
ADD UNIQUE INDEX `user` (`user`);
And then, a single query like this would be good:
$res = mysql_query("INSERT IGNORE INTO `table`(`user`) VALUES( '".mysql_real_escape_string($user) . "')";
echo ( mysql_affected_rows() == 0 ) ? "No" : "Yes";
mysql_affected_rows().
Use this query .
INSERT INTO USER SELECT * FROM TABLE WHERE user='$user'
the number of column in table table and user table must be same ,their type also.
you can also use
INSERT into user
SELECT * from table
WHERE user='$user'
AND
NOT EXISTS (SELECT * FROM USER
WHERE USER = '$user')
Related
I'm new on php and mysql. I found several things that I can use - such as implode- on internet but I couldn't make it. I will try to be clear as much as I can.
First table name: mylist
column name: id (The values on this column are unique.) (incremental)
I put all ids inside an array called myIds. The array contains only unique integer values and it's length is 800.
I need to get answers for each ids from another table for the current date. This table also contain id column but for an id, there can be more than one answer.
For example: today, there are 3 answers for id 1 and 5 answers for id 4, etc.
Second table name: answerlist
This is the query works for a specified id:
$sql = "SELECT `answer` FROM `answerlist` WHERE `type`= 'Help' AND `id` = 1 AND DATE(`added`) = DATE (NOW())";
I would like to create a dynamic query which gets id values from the above array. How can I do this?
A Solution would be to use The mysql IN operations for your ids
SELECT `answer`, `id` FROM `answerlist` WHERE `type`= 'Help' AND `id` IN (1,2,3,4,5) AND DATE(`added`) = DATE (NOW())
you can implode them like this :
$sql = "SELECT `answer`, `id` FROM `answerlist` WHERE `type`= 'Help' AND `id` IN (" . implode(',', $myIds) . ") AND DATE(`added`) = DATE (NOW())";
I am trying to run an query using php into a database, I need to check if the customers address is already exists then do not insert, but if not exists then insert into table, I have based it around the following:
$query = "INSERT INTO address(id,address_type)
SELECT('1111','bill')FROM DUAL
WHERE NOT EXISTS
(SELECT * FROM address
WHERE id='1111' AND address_type='bill')";
$n = mysql_query($query, $connect ) or die(mysql_error());
This allows me to insert just the id but not the address_type.
I will have the same id for both bill & ship addresses making a unique field not possible.
I have about 8 fields to insert, what am I doing wrong?
$query = "INSERT INTO address(id,address_type)
SELECT('1111','bill')FROM DUAL
WHERE NOT EXISTS
(SELECT * FROM address
WHERE id='1111' )";
remove address_type='bill' and check
Im creating a website for booking activities. I have 3 centres. The customer is cant book the same activity twice neither in a different centre. Im using a table in mysql which i store the infos provided by the costumers. Is there any way to filter or to check in my php code if a customer has already booked the same activity more than one time and echo an error msg?
my table(and the info im asking) contains these columns:
ID(Primary)
FirstName
LastName
Email
ContactNumber
ClassName
Week
Intensity
CentreName
$values = $_POST;
foreach ($values as &$value) {
$value = mysql_real_escape_string($value);
}
$sql1="INSERT INTO loan (loan_id)
VALUES ('$values[loan_id]')";
$result = mysql_query($sql1);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
When you create the table add the unique attribute to the fields you want to prevent, something like this
CREATE TABLE Persons
(
P_Id INT NOT NULL AUTO_INCREMENT,
LastName VARCHAR(255) NOT NULL,
FirstName VARCHAR(255),
Address VARCHAR(255),
City VARCHAR(255),
UNIQUE (P_Id)
)
If you already have created the table just edit it like this
ALTER TABLE Persons
ADD UNIQUE (P_Id)
Hope this helps you; If you do not have a unique id i believe this will suit you best on what you need; Note that this is not the full code; You need to add some to other information to fit in your question;
// Checks if the value already exist on the database
$query = SELECT EXISTS(SELECT column_name FROM table_name WHERE
condition LIMIT 1)
// If condition is not met it will proceed with save
if (mysql_num_rows(!$query) > 0) {
echo "Activity Booked";
} else { // If condition is met it will echo an error message
echo "Unable to booked activity"; }
You need to create a unique (composite) index on the column(s) that you wish to be unique. You can disregard your PK when making your unique index. In your case your sql would look something like:
Alter table yourtablename
add unique index idx_unq(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`);
Then do an INSERT IGNORE INTO instead of an INSERT INTO.
This post may also help you.
"INSERT INTO .. ON DUPLICATE KEY UPDATE" Only inserts new entries rather than replace?
In order to see if record already exist in table you must first "test" to see if that exact record exist in your table. This is to be done before the 'Insert IGNORE Into' in your logic. Using the variables your code would look something like this:
$testcount = "Select count(`LastName`, `FirstName`, `Email`, `ContactNumber` `ClassName`, `Week`, `Intensity`, `CentreName`)
from yourtablename
where
(LastName = '$LastName' AND FirstName= '$FirstName' AND Email= '$EMAIL' AND ContactNumber= '$ContactNumber' AND ClassName= '$ClassName' AND Week= '$Week' Intensity = '$Intensity' AND CentreName = '$CentreName' )";
This query will give you back (assuming there are no duplicates already in the table) a 0 or a 1 and store it in your $testcount variable. This can then be used to either determine based on the value to insert the record into the table or print a message to end user informing them that it already exist.
I am not sure how you want to structure the php code but the psuedocode would look something like:
If $testcount = 1 then do your insert.
else if $testcount = 0 then echo your message.
This question already has answers here:
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
(12 answers)
Closed 8 years ago.
I have a query that will update a row in the database, which works fine providing there is a row there to begin with.
How could I say; update if exists insert if doesn't?
require_once('../scripts/includePDO.php');
$who = $_SESSION['who'];
$formText = $_POST['protext'];
$sql = "UPDATE tbl_profiles SET proText = :formText WHERE user_id = :who";
$q = $conn->prepare($sql);
$q->bindValue(':who',$who,PDO::PARAM_INT);
$q->bindValue(':formText',$formText,PDO::PARAM_STR);
$q->execute();
header("Location: ../settings/?status=Done");
Assuming user_id is a unique key in the db:
$sql = "INSERT INTO tbl_profiles (user_id, proText) VALUES (:who, :formText) ON DUPLICATE KEY UPDATE proText = :formText";
Your SQL query should be:
INSERT INTO tbl_profiles (user_id,proText) VALUES (:who,:formText)
ON DUPLICATE KEY UPDATE proText=:formText
This is assuming that user_ID is a unique id
1- simple way is use ORM such as Dotrine
2- How ORM handle this :
usually tables has primary key(id) that should not be null .if you have update then you had select that load this data . in you select load id field in you data structure (array or object or something else) . in save method only check current row you want save that it has id (if this record has id then it exist and need to update else you should save).
I have a php script that uploads csv files into a mysql database.
The database has several columns. Among these columns is an 'email' field. I wrote some mysql that would remove rows that contained duplicate values in the email column. Below is the mysql:
$sql = "CREATE TABLE new_table as SELECT * FROM auto WHERE 1 GROUP BY email";
mysql_query($sql, $conn);
$query = mysql_query("SELECT COUNT(*) FROM new_table");
list($number) = mysql_fetch_row($query);
$query = mysql_query("SELECT COUNT(*) FROM auto");
list($number2) = mysql_fetch_row($query);
$result = $number2 - $number;
mysql_query("DROP TABLE auto");
mysql_query("RENAME TABLE new_table TO auto");
The code works, it removes duplicate values.
Problem:
It removes rows that contain no values. So it assumes that two or more emails values that are empty are duplicates and removes they're rows.
Question:
How do I tell mysql to ignore empty values.
Thanks for the help.
Edit
The where is my database table. One table.
The when is when I execute the code. I plan on putting in a php file to be executed on demand.
The result I expect is a mysql table without duplicate emails.
Something like this would work for a one-time alteration, by allowing NULL in email, and adding a UNIQUE constraint:
-- set empties to NULL
UPDATE tablename SET email = NULL WHERE LENGTH(email)=0;
-- drop all rows violating the UNIQUE constraint on email:
ALTER IGNORE TABLE tablename ADD UNIQUE (email);