I have used Stored procedure to check whether a name exist in a table or not by using the following code snippet..
BEGIN
IF ids = 0 THEN
SELECT * FROM table_name WHERE `table_id` = alb_id AND name LIKE CONCAT('%',var_name,'%');
END IF;
END
I got the solution if the name doesn't contain any special characters or brackets, like XXXX.
If the name contains any brackets means result not came, like XX(YY)GG.
Suggest me for the best solution
Edited:
In this if a name exist already i should not insert it again, for this condition i used this procedure. If it returns mysql_num_rows > 0 means i wont insert, else i will insert the name into my table..
My sample names are,..
Turning Tables (Live Acoustic)
Hiding My Heart
Someone Like You (Live Acoustic)
Right Now (Na Na Na)
Keep You Much Longer
Someone Like You
In the list of name "Someone Like You" and "Someone Like You (Live Acoustic)" are two different names, i want to identify the name "Someone Like You (Live Acoustic)" is already exist or not..
How do i do?
CREATE TABLE `stack_test` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`text` varchar(100) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB CHARSET=utf8;
INSERT INTO `blur_new`.`stack_test` (`id`, `text`) VALUES ('1', 'run (rabbit) run');
INSERT INTO `blur_new`.`stack_test` (`id`, `text`) VALUES ('2', 'test');
set #a = 'n (rabbit)';
select * from stack_test where text like concat('%',#a,'%');
results in:
1 |run (rabbit) run
So, it works.
check the rest of the conditions in where clause
check how are you passing the value
you might gonna have to check you data types. I have a feeling something is not right there
Related
I have been trying to get the following SQL to work however it seems to skip the insert function. Essentially updating should take priority as most of the time it should fire.
UPDATE `teams-tasks`
SET status=(:s), name=(:n), description=(:d), importance=(:i), applies=(:a)
WHERE teamId =(:t) AND date=(:da) AND playerId =(:p) AND creatorId =(:c);
IF (SELECT ROW_COUNT() = 0);
INSERT INTO `teams-tasks`
( status, date, creatorId, teamId, playerId, name, description, importance, applies )
VALUES
( (:s), (:da), (:c), (:t), (:p), (:n), (:d), (:i), (:a) ))
what am i doing wrong?
i am using php pdo for my database connection if it matters
thanks
User replace into query which makes sure if the row exists it will update the data, if row does not exists it will insert the date.
to check the duplicate entry it compares the primary key internally
e.g.
REPLACE INTO table_name(column_name1,column_name2,…)
VALUES(value1,value2,…)
e.g.
REPLACE INTO offices(officecode,city)
VALUES(8,'San Jose')
Thanks
Amit
You should use INSERT ... ON DUPLICATE KEY UPDATE
For example
INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE
Timestamp=VALUES(Timestamp)
I'm using a sequence and trigger to essentially auto increment a column in a table, however I'm getting an error - ORA-24344: success with compilation error.
I was using this post: How to create id with AUTO_INCREMENT on Oracle? and it worked successfully for two other tables w/ auto increment I made, but there must be something in here I'm not familiar with causing an error.
More edits: Thanks to Polppan we've established that this likely isn't an Oracle issue, rather an OCI with PHP issue. I'm using:
oci_execute($sql);
And as mentioned here (again, thanks Polppan for that link), there's a bit of an issue between EOL characters and oci_execute. It was 11 years ago, so I don't know if that's been patched or not, and I did try his solution but it didn't help. Does anyone know if there are other issues with oci_execute and creating triggers?
Creating the table: (works)
CREATE TABLE RT_documents (
documentID INT NOT NULL,
reviewID varchar2(20) NOT NULL,
file_location CLOB NOT NULL,
version NUMBER(*,3) NOT NULL,
CONSTRAINT RT_documents_pk PRIMARY KEY (documentID)
)
Creating the sequence: (works)
CREATE SEQUENCE rt_documents_seq
Creating/replacing trigger: (doesn't work)
CREATE OR REPLACE TRIGGER rt_documents_bir
BEFORE INSERT ON RT_documents
FOR EACH ROW
BEGIN
SELECT RT_documents_seq.NEXTVAL
INTO :new.documentID
FROM dual;
END;
EDIT: Exact error message as requested - (Note, I'm executing these query-by-query using OCI/Oracle in PHP. PHP tag added just in case, but pretty sure this is an oracle syntax error or something).
Error:
Notice: oci_execute(): OCI_SUCCESS_WITH_INFO: ORA-24344: success with
compilation error in (...)
-I can successfully execute the first two queries, and double checked and the table is there so it worked properly.
Trigger doesn't understand new.id as id doesn't exist in RT_documents table.
Your trigger should be
CREATE OR REPLACE TRIGGER rt_documents_bir
BEFORE INSERT
ON RT_documents
FOR EACH ROW
BEGIN
SELECT RT_documents_seq.NEXTVAL INTO :new.documentID FROM DUAL;
END;
Update
SELECT * FROM v$version;
Oracle Database 10g Enterprise Edition
CREATE TABLE RT_documents
(
documentID INT NOT NULL,
reviewID VARCHAR2 (20) NOT NULL,
file_location CLOB NOT NULL,
version NUMBER (*, 3) NOT NULL,
CONSTRAINT RT_documents_pk PRIMARY KEY (documentID)
);
Table created.
CREATE SEQUENCE rt_documents_seq;
Sequence created.
CREATE OR REPLACE TRIGGER rt_documents_bir
BEFORE INSERT
ON RT_documents
FOR EACH ROW
BEGIN
SELECT RT_documents_seq.NEXTVAL INTO :new.documentID FROM DUAL;
END;
/
Trigger created.
INSERT INTO RT_documents (reviewID, file_location, version)
VALUES ('test', 'test', 1);
1 row created.
SELECT * FROM RT_documents;
DOCUMENTID REVIEWID FILE_LOCATION
VERSION
---------- -------------------- -------------------------------------------
-------------------------------- ----------
1 test test
1
Thanks to Polppan.
The solution was removing the EOL characters. (I did try this but had, without realising, removed the semi-colons, which caused the same error code)
This was a PHP error after all. Using oci_execute, you must remove EOL characters in triggers:
$sql = "CREATE OR REPLACE TRIGGER ......."; //shortened for easy reading
$sql = str_replace(chr(13),'',$sql);
$sql = str_replace(chr(10),'',$sql);
oci_execute($sql);
I am using a licensed software for my website, and of course the engine is encrypted. i have no access and modify to any php code...
It has a feature that i want to change, and i can't modify the php code, since the vendor doesn't allow me to do it...
The only option is to build a separate custom script and run it separately to update fields in database (which is not suitable for my project)
OR to change the values manual in mysql database (again it's not suitable)
There is a third option, and i don't know if it's really possible....
here's the scenario:
The script ads a new row in database whenever the user click on a particular link. That row has 10 fields. last 4 fields are NULL by default and they should stay NULL.
The script insert values in that last 4 fields, and it's unusual, and of course the script is not working properly anymore.
So my question is: Is there any way for me to prevent the insertion of the values for that 4 fields in database ? Can it be locked to NULL ? Can "SET / UPDATE" function be ignored for that fields?
Options:
During insert do not use those columns to insert into.
Write before insert trigger to reset to null those new column values.
Writer before update trigger to reset to null those new column values, based on a where condition.
Update:
If you do not have access to your php code to modify the insert statement, you can only achieve this by defining triggers in database. For this to happen, you should at the least have various privileges like remote connect, create, execute triggers, etc. Unless which you can't do this.
If you have such privileges, you can try on your data table something similar to the following:
before insert trigger as below:
delimiter $$
drop trigger if exists bfimt_omit_colum_data $$
create trigger bfimt_omit_colum_data before insert on my_table
for each row begin
set NEW.col_name_4_to_set_null = NULL,
NEW.col_name_5_to_set_null = NULL,
NEW.col_name_6_to_set_null = NULL;
end;
$$
delimiter ;
Similarly the before update trigger as below:
delimiter $$
drop trigger if exists bfumt_omit_colum_data $$
create trigger bfumt_omit_colum_data before update on my_table
for each row begin
set NEW.col_name_4_to_set_null = NULL,
NEW.col_name_5_to_set_null = NULL,
NEW.col_name_6_to_set_null = NULL;
end;
$$
delimiter ;
You could define a trigger like this:
delimiter //
CREATE TRIGGER set_to_null_bi BEFORE INSERT ON tablename
FOR EACH ROW
BEGIN
SET new.col4 = NULL;
SET new.col5 = NULL;
SET new.col6 = NULL;
END//
delimiter ;
and you could also create a BEFORE UPDATE trigger.
Thanks all for your help, i can't say you codes are not correct, but hey didn't work for me. I manage to solve this by myself, here's the code:
DROP TRIGGER IF EXISTS `trigger_null`;
CREATE DEFINER=`root`#`localhost` TRIGGER `trigger_null` BEFORE INSERT ON `mytable` FOR EACH ROW
SET new.create_action = NULL,
new.col4 = NULL,
new.col5 = NULL,
new.col6 = NULL,
new.col6 = NULL,
new.col7 = NULL,
new.col8 = NULL;
That's all...
Thanks for your reply's !!!
I want to make a table in a database, by giving the name of that table as an input from a text box.
<?php
$tablename = $_POST['tablename'];
// Create a MySQL table in the selected database
mysql_query("CREATE TABLE $tablename(
id INT NOT NULL AUTO_INCREMENT,
PRIMARY KEY(id),
firstpublish VARCHAR(255),
descriptions VARCHAR(255))") or die(mysql_error());
?>
it makes the table and the field, but i can't insert any data in it. When i run the code below
<?php
$firstpublish = $_POST['firstpublish'];
$descriptions = $_POST['descriptions'];
if(isset($_POST['firstpublish']) || ($_POST['descriptions']))
{
$order="INSERT INTO $tablename (id,firstpublish,descriptions) VALUES ('','$firstpublish','$descriptions')";
$result = mysql_query($order) or die (mysql_error());
}
?>
it showing an error message
"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), firstpublish VARCHA' at line 1"
how can i fixed this problem.
-thankyou.
My best guess would be that your first query is somehow being rerun with a blank value for $tablename
If this is a publicly accessible page, i'd be very careful about creating tables from user input. You also probably want to (at the very least) run $tablenale through mysql_real_escape_string() and change CREATE TABLE to CREATE TABLE IF NOT EXISTS
The error is here:
mysql_query("CREATE TABLE $tablename(
Since you are mixing a variable in a quoted string, you insert whitespace after its name, because "$tablename(" is illegal name and will most likely be replaced will null, so the SQL-statement will actually be seen for MySQL as
CREATE TABLE id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), firstpublish VARCHAR(255), descriptions VARCHAR (255))
which, in turn, is a syntax error.
Solution: Add a space between $tablename and "(".
i am trying to insert data to database but it removing braces'{}' while inserting i am using this code.
<pre><code>
require_once './includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_DATABASE);
$aa['alt']="happy alt";
$aa['title']="happy title";
$sldata=serialize($aa);
$sql="Insert into test(pval) values('".$sldata."')";
echo $sql;
db_query($sql);
</pre></code>
my db structure is as
<pre><code>
CREATE TABLE IF NOT EXISTS `test` (
`sl` int(11) NOT NULL AUTO_INCREMENT,
`pval` text NOT NULL,
PRIMARY KEY (`sl`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
</pre></code>
suggest me what is wrong here..
Drupal uses {} arround the tables names, to be able to do some manipulations on those names -- like prefix them, if you have configured it to do so.
So, you must not use {} in your query -- except arround tables names, of course.
Instead of brutaly injecting your serialized-string into the SQL query, you must use place-holders in it -- and pass the corresponding values to db_query(), which will take care of escaping what has to be :
$sldata = serialize($aa);
$sql = "insert into {test} (pval) values('%s')";
db_query($sql, $sldata);
Here :
As the pval field is a string in database, I used a %s place-holder
And the first value passed to db_query() (after the SQL query itself, of course) will be injected by drupal, to replace that first (and only, here) placeholder.
And, for more informations, you might want to take a look at Database abstraction layer.
instead of just serialize, you could base64_encode to bypass curlies being a problem.
http://php.net/manual/en/function.base64-encode.php
base64_encode(serialize($aa));
Then on the retrieving side of the data
unserialize(base64_decode($db_data));