Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
 
  HOME    TRACKER    MYSQL




Check Before Insert Query


if (!empty($determin))
{
//do something when its not empty

$query = "SELECT * FROM `JS` WHERE `wrdnprc` LIKE '$mkrs' LIMIT 1";
$good_query=mysql_query($query) or die(mysql_error());

if (mysql_num_rows($good_query) == 1 )

{
echo "record found #2<br>";
}
else
{
$query = "INSERT INTO `JS` ( `id` , `wrdprc` , `wrdnprc` , `pgld` ) VALUES ('', '$mkrs', '2', '0') ";
$query=mysql_query($query) or die(mysql_error());

echo "adding record #2<br>"; }
}
else
{
//its empty... lets whine about it
echo "no <br>";
}

most of the work is being done, which is good thing BUT the query will INSERT regardless of the if good_query statement.




View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread
INSERT Check For Duplication First. Is DISTINCT?
I have the need to create a record that only has a grouping of distinct values. For instance:

summary1id = paper1id + supplier1id + liner1id
summary 2 cannot have the same combination.

How would I do that through sql (mysql)

MySQL/PHP: Check Data Length Before INSERT?
I've heard of buffer overflows being used/abused by hackers and believe one
method to reduce this from happening is to check the length of my form data
before writing it to my MySQL database.

Is my understanding correct?

At the moment, I pass all my data through htmlentities() before writing to
my database. Is this enough? Should I check each individual columns length
first, or perhaps the overall content length to fit within the maximum
record length?

I found a function called mysql_escape_string() and have thought of using
it - but other than strip_slashes(), I don't know the reverse (unless
strip_slashes() is the recommended opposite of mysql_escape_string()).

Check Query Please
This is giving me an mysql error. Why?

DELETE FROM subscribers,list_subscribers WHERE subscribers.id = list_subscribers.ls_sub_id AND list_subscribers.ls_list_id = 1

How To Check For Date/time Ranges Within Record (check For Schedule Conflicts)
You want to check scheduling conflicts and you have a record like:

appointments(table):
apptID
beginningDate
endingDate
beginningTime
endingTime

It's easy enough to check if a time is within that record. Say you want to
check if 8:00am to 10:00am is available, you would use this:

SELECT apptID
FROM appointments
WHERE (beginningDate = '2006-01-19' OR endingDate = '2006-01-19')
AND ('08:00:00' BETWEEN beginningTime AND endingTime
OR '10:00:00' BETWEEN beginningTime AND endingTime)

BUT, what if you have an all-day appointment (8:00am to 5:00pm) and there
exists an appointment already scheduled from 10:00am to 11:00am. The above
query would not find it.

Another question is what if the appointment is more than two days. Say, it's
from Monday - Wednesday from 8am to 5pm. The above query would not
successfully catch it if you wanted to schedule an appointment on Tuesday.

(I might be able to generate a date range using PHP, don't know if that's
the best way)

Is There A Query To Check Directly If A Datarecord Exists?
Is there a query to check directly if a datarecord exists?

What Query To Check If Any Rows Exist Satisfying WHERE Clause?
I'm looking for a query that will check if any rows exists in a table according to a WHERE condition. I know I can use COUNT(*) but then mysql will do unnecessary task of counting all the rows whereas I just need true or false. So far I did this:

SELECT COUNT(*) AS exists FROM mytable WHERE ...
Sometimes I just select the first row and check later in php how many rows have been returned:

SELECT some_col FROM mytable WHERE ... LIMIT 1
But I cannot do this check (or can I?) in sql alone and I have problems when I want to use this in a subquery, for example:

SELECT id,
name,
(SELECT COUNT(*) FROM mytable WHERE ...) AS exists
FROM othertable
WHERE surname='xxx'
Can I do the same without using COUNT(*)? I would like a query that returns 0 or NULL if no rows were found, or 1 (or some other value) if 1 or more rows were found.

How To Insert Multiple Rows With 1 Insert Query
I am having a form on the front end which has for example 3 rows each with 3 columns. The user enters data in all the 3 rows. When he hits the add button these should get in the database. What insert query would I write to add all of them together to the database? Do I need to use some procedure?

Can I Check The Value Of An Alias(i Think Its Called An Alias) In A Query.
I was wondering can I check the value of an alias(i think its called an alias) in a query.

At the moment I have this but its not working:

MySQL Code:

SELECT  * , ( DAYOFYEAR( ToDate )  - DAYOFYEAR( FromDate )  ) AS NumDays
FROM  `tbl_courses`
WHERE NumDays < 3 AND NumDays > 2 AND FromDate >=  &#55614;&#57159;-10-17'
ORDER  BY FromDate

Insert Query
I have the following query that gives me an error when executed:

insert into new_respolis (prov_poll_num, prov_elect_dist_id)
values
select (poll_number, eid) from temp


INSERT Query
I've checked on a few forums and haven't had any success, so I decided to post. I'm writing a .net application that uses MySQL.Data objects to access MySQL. After a few attempts at making an INSERT statement work, I ported the SQL over to MySQL Query Browser, hoping that would give me some more insight. Anyway, here's the query I'm having trouble with.

insert into FileMover (SessionID, FromDir, ToDir, StartDateTime) values (39643, 'D:Downloads', 'D:\_Work oolsFileMover est', '2006-04-28 11:04:43')

The only error message I ever get is that generic one that says there's something wrong with my syntax.

Insert Query
I forgot how to do this in MySQL.I need to insert a record in a table where it does not exist.
I think you do something like:
Code:

Insert into table1 (f1, f2, f3) values ('1','2','3') where not exists
(select * from table1 where f1='1' and f2='2' and f3='3')

Is this correct

Insert Into 2 Tables In 1 Query
how do i insert into 2 tables in 1 query?

SELECT (INSERT...) Query
Is there any way I can do an insert and select the auto_incremented id in one SQL command?

Need To Use Same Table In Subquery As In Insert Query
I have this table called "testtab":

ID | value
----------
1 | 8
2 | 15
3 | 5

Field ID is INT autoincrement as usual for ID field, field value is common INT. I need to insert new record to it. The inserted value should be equal to the highest value +1. I tried to do something like this:

INSERT INTO testtab SET value=(select max(value) from testtab)+1
Mysql threw this error:

You can't specify target table for update in FROM clause
I searched internet and found that I cannot use the same table in a subqery of insert/delete/update query. So my question is: Is here some workaround for this? I know I could use two queries - one to find the maximum value and second to insert the value+1 into DB, but I would like to do it in a single query.

INSERT Query With Random Date
I have about 2,000 entries to add to my database and I want each one to have a random date of between, for instance, 2007-01-01 and 2007-03-28 [today].

Any ideas on what's the best way of doing this?

I did try and come up with a script that grabs a line, updates it and then moves on to the next line, but I keep getting "This page will repeat forever" errors coming up.

Trigger Insert Query After Just Inserted Row
I'm having a little problem getting my head around this trigger event. Basically I have 3 tables:

Quote:




Table.Description
ID
Title
Description

Table.Colours
ID
Colour
Img
Description_ID

Table.Sizes
ID
Sizes
Colour_ID




The above is a cut down version of the actual tables, but basically I loop through an array when a customer inserts a product which can come in many colours, and each colour in many sizes.

When I insert each size I would like to fire off a trigger which will create a unique product in a seperate table, using the Related ID's above for example:


Quote:




Table.Unique
ID
Desc_ID
Col_ID
Size_ID




I have attempted to create a trigger, but have had no joy as of yet as I I'm getting errors on retrieving the last insert ID for sizes. This is what I have got so far:


Quote:




DELIMITER //
CREATE TRIGGER ai_unique_product
AFTER INSERT ON Product_Sizes
FOR EACH ROW
BEGIN
INSERT INTO Product.Unique
Size_ID = Product_Sizes.last_insert_id(),
Colour_ID = Product_Sizes.Colour_ID,
Desc_ID = Product_Colours.Descript_ID WHERE Product_Colours.ID = Product_Sizes.Colour_ID;
END;
//



PLEASE HELP*SIMPLE - Mysql INSERT QUERY
And YES its connected to mysql DB i need help (a fix) ASAP thanks

<?

$sql = "UPDATE `games` SET `sponsor` ='$WebsiteURL' WHERE `gameid` =$GameID LIMIT 1";

$result = mysql_query($sql);

echo "$result";

?>

About Using DELAYED Keyword In The INSERT Query
I have a table in my database that needs very fast inserts as hundreds of concurrent users might be inserting rows at a given time. Basically, every time a visitor accesses a web page the time needs to be logged in the table. Since there could be hundreds of insert operation in the queue waiting for their turn, a visitor needs to wait before his entry is inserted. So to speed up things a bit I was thinking of using DELAYED keywords in the INSERT statement. The visitor will issue an INSERT query and then proceed. The entry would be inserted when the table is free to accept new insert query.

Convert UPDATE Query To INSERT
I have an SQL dump file of a sql database that was generated with the UPDATE export type. The file contains code for generating the various tables inside the database along with the UPDATE lines for the table data.

Is there a way to process the dump file such that all of the UPDATE instructions are converted to INSERT instructions? I have to restore the database from scratch so there are no existing table rows to update.

Use Query-results As Delayed Insert?
Can I use the results of one query like:
-> SELECT user_id FROM tbl_customers

And use the results to fill the VALUES-statement in another table like:
-> INSERT INTO tbl_postal ('user-id') VALUES (<previous query results>)

If so, could someone complete my second SQL-statement, since I'm staring
at my CRT for over 2 evenings and I cannot get it to work.

Insert And Update In The Same Query (mySQL-3.23.58)
I am using mySQL-3.23.58 at my school. Since triggers are not available is there a way to do an insert and an update in one query?

Error 1604 With INSERT Query
I've a problem with an INSERT query i want to launch in Mysql 5 RC. In previous versions this worked correct however it stopped working correctly from Mysql RC5 on.

The error message is the following:

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 'Release,Description,JWRName,DueDate,JWalk,UI) VALUES ('35','TEST','TEST','5.50',' at line 1

This is the query:

Create A Query To Insert Data
I have a form that includes a bunch of fields to fill out. I have the query working for most of them, but right now am stuck on getting one area to work.

I have 7 fields where you can input a parts number (name=number[]) and then another 7 fields where you input the description of the part (name=description[]).

I want to put them into a database that has one column for the number, one column for the description and then a primary key and foreign key to eventually join them to the main workorder table.

I am not sure how to make a query that will INSERT them into the DB columns, one row for each number/description combination, and check to make sure there is data in the rows. There may not always be 7 part number/descriptions in the form fields and I don't want a bunch of empty rows in the DB table.

Insert A Record Using MySQL Query Browser
I know I can probably type in the actual query, but I was wondering if there was a means of inserting a record without typing "insert into table_name (blah, blah2) values (blah, blah)". I'm looking for a method as easy as typing into an Excel spreadsheet or Access DB. (I know I'm gonna get bashed for mentioning Microsoft products.)

Insert Data Into 2 Tables With 1 Query Fails
I found 2 old threads on how to insert data into 2 tables with 1 query. Both of them said that i should seperate the inserts with a ;. But i must be doing something wrong, because it comes up with an error like this ".....right syntax to use near ' INSERT INTO eiland_details"

What am i doing wrong? It's possible, right? To insert data into multiple tables with 1 query?

$query = "
INSERT
INTO sub_pages
(mainpage_id, intro_text)
VALUES
('$main_data->mainpage_id','$sub_intro');
INSERT
INTO eiland_details
(inwoners, oppervlakte)
VALUES
('$detail_inwoners',$detail_oppervlakte')";

INSERT Query Ignoring Escape Characters
I have extensively searched the web, and none of the solutions I've found seem to work (mysql_real_escape_string, addslashes, str_replace). Php will display the reformatted strings properly, but when I attempt to add a reformatted string to an INSERT or UPDATE query, the escape characters seem to be ignored.

On INSERT, fields that contain the " ' " single quote (like Joe's) are losing all data after the single quote. The query DOES insert the record, and the rest of the record is inserted properly, but the field containing the single quote is truncated. "Joe's Crabshack" gets stored as "Joe" ....

INSERT Query Runs In Mysql Client, But Not In PHP.
I'm learning the ropes with PHP and MySQL at the moment, and I've
run into a puzzle. I'm using PHP to process a form and insert some
simple information into a table. The code doesn't have any glaring
errors, and the mysql_query() doesn't error out, but the info never
gets inserted. And if I run the same query inside the mysql client the
data goes in fine. The query looks like this in PHP:

How About The Speed Compare Connection/query/insert And Other Between C,c++,php ?
How about the speed compare connection/query/insert and other between c, c++, php?

Query To Insert 2 Foreign Key Values In Table
I want to insert 2 foreign key values along with some other value into table ....

Formatting Html Tags For Mysql Insert Query...
I would like some guidance on how to format a SQL string in asp to insert a
HTML string to a text field. MySql keeps adding white space to the tags..

ie <P> ends up in the dbase as < P >

I have read multiple posts about 'escape' characters, etc... but still not
sure how to tackle this.

Query (select/insert/update)Slows When Table Grows
I have a mysql database where tables are very simple. An example table will look like this:

create table myTable(
token varchar(255) not null primary key,
token_count int default 1,
frequency int
) type=INNODB;

A java program populates this table. The program reads from files (in batch mode) and inserts into myTable with following logic:

(1) See if the String to be inserted is present in myTable.(Uses SELECT)
(2) If not present the insert into myTable (uses INSERT)
(3) If yes update the table after adding the current frequency (USES UPDATE)

After processing each file issue COMMIT.

This goes on well for some time - but after the Table grows over 100,000 rows the process slows down considerably. The Strings I 'm handling is very large and I'm not sure how well Mysql behaves with very large String as primary Key.

My select and update statements are all based upon primary key(token in this case) - so question of setting index doesn't arise. Even then I have set index on token field - but it has degraded the performance. Also I have set the query_cache_size to 1MB even then it is not enhancing the performance.

A sample file has almost 30,00 to 50,000 lines. Each line having a string + blank + frequency.

After processing first few files - the Java program takes large time to process a single file - and subsequently the processing time increases exponentially.(as the tabel grows in size it slows down).

1 Simply Query Problem. Please Help With Insert Into 1 Table From Another Table
I have Table A that has some records already in and then I have Table B that does a few things and gets updated regularly.

With Table A, I want to get it updated every 8 hours or so with new data that has been inserted into Table B.

I will do this using the Cron.

But what would be the best insert query to use so that it does the process really quick.

The query that I have so far is:

Quote:

mysql_query("INSERT INTO table a (id, title, descrip) SELECT id, title, descrip FROM table b where app=1");

With the above query the id's match in both tables. But I only want the new records to be inserted into Table A where app=1 in Table B and the row is not already in Table A.

How can I add to the query so that it does this.

&quot;update If Not Exit Insert&quot; Query?
is it possible to do query "update record. if not exist, do insert" in mysql?

Check 366 Day Expiration
Needing to filter on a datetime col Mplan.Start having runtimes of 366 days:

roughly:
SELECT *
FROM Plan
WHERE (CURRENT_DATE () <= Plan.Start + 366 days)

should dates be formatted 1st?

...WHERE DATE_FORMAT(Plan.Start ,'%Y%m%d') >= DATE_FORMAT(CURRENT_DATE(),'%Y%m%d' + ?)

problem with the following is that all future dates are included, as mysql manual states (which can't be included in this application):

...WHERE CURDATE() <=DATE_ADD(Start,INTERVAL 366 DAY)

2 + 7 = 11. Let's Check It... Iterating
<html>
<font color=

#eaf1f7>ethnic closeup architects peered beseech</font><br>
<font color=

#f1fefc>harvester grouse facade apparently loadings</font><br>
<table border=0 width=430 cellpadding=5>
<tr>
<td height=1 bgcolor=

"#F7941C" align=center>
<font face=arial><b>What are Soft Tabs that everyone is talking about?</b></font>
</td>
</tr>
<tr><td bgcolor=

"#5C4E7F" valign=top>
<font size=-1 color=

white face=arial>
<b>
A Soft Tab is an oral lozenge, mint in flavor, containing pure<br>
Tadalafil Citrate that is placed under your tongue and dissolved.<br><br>

Easy and imperceptible to take.<br>
Take just a candy and become ready for 36 hours of love.<br><br>

• This is most modern and safe way not to cover with shame<br>
• Only 15 minutes to wait<br>
• FDA Approved<br>
<br>
<br>

<center><font color=

"#F5EB96">Interested?</font></center>
</b>
</font>
<br>
<br>
<div align=right><a hrefenchanthref=http://knighted.com href=

"http://stamens.mymedsnet.info/tabs/"><font face=arial color=

white><b><u>Get more information</u></b></font></a></div>
</td></tr>
</table>
<font color=

#fdf8fa>foresight mahogany feathered shared temperate</font><br>
<font color=

#e9f4f9>tolerably leans returnable cartoon mediums</font><br>
<font color=

#f0ecfc>narratives manhood acquaint advocate bluff</font><br>
</html>

Numeric Check
I am looking for some function that tests if a value is numeric. I could not
find a function for this.

At the moment I am using "WHERE CONV(myfield,10,10)!=0" but I suppose there
must be a better way.

Check Constraint
does mySQL provide Check Constraint?

I try this :
alter table city add check(id>0);

It runs without error but when i tried to insert a city name with id = 0 the query runs ok. the check constraint fail to work.

oh ya, what is the syntax to see all the check constraint on a table?

CHECK Command
Could I use the check command to see if a certain identifier will never exceed a default value when data is put into the table.

capacity INTEGER NOT NULL DEFAULT 10,
CHECK(capacity<=10)

SQL To Check For A File?
I have a field in my DB that was pre-populated with a filename for each record. This filename is a picture that then shows up on the website. Problem is not all the pictuers are up yet so they wonderful red X shows instead for ones with no pictures.

We do have it setup so that if there is no picture file specified, it just shows a default "No Image" wording.

So, since all the records already have a filename in them, is there any way with SQL to have it go through the records, check what's in the image field, then see if that file exists or not? THen if it does, great, if it doesn't it would delete the value from the field?

Check For Existing Row ?
How do I determine if a row already exists ?

// see if a row has id=100

$id=100;
$query="SELECT * FROM mytable WHERE id=$id";
$result=mysql_query($query);

...what do I check now ?

User Check
I have been playing about with a website of mine. I was wondering when using mysql, how do i check if a username & email address is already being used.

CHECK Syntax
I have a table as follows:

CREATE TABLE country
(
codeCHAR(2)NOT NULL,
...
...

CHECK (CHAR_LENGTH(code) == 2)
);

The entry for 'code' MUST be two characters long. Although CHECK is not
yet implemented by mySQL, is the above syntax correct?

Secondly, the entry for 'code' MUST not contain any numbers. What is
the syntax to check for that?

Currently I am doing the checking before inserting the data but would
like to implement it in the database too.

Duplicate Check
I have a table with two columns, T1(id,info). I'd like to add some data from another table which also has two tables T2(id,info).

I have to add data from T2 into T1, but i have to check if the data already exists. Until now i did like this : select info from T1 where info in (select info from T2) but it fails if i have more that 5.000 records. Is there another way to do this ?

Performing A Check
I have a table called customer with a field called dateAtAddress. I want to perfrom a check so that when a new record is created the dateAtAddress must be in the past. I have tried the following code when creating the table

dateAtAddress date,
CHECK
dateAtAddress <= DATE_SUB(CURRENT_DATE, INTERVAL 0 DAY);

But it still seems to be letting datesin the future be entered in as valid data in the field.

User Check
I want to add a new user but I don’t know whether a user already exists
How can I check whether a user already exists?
This don’t work
CREATE USER IF NOT EXISTS admin

Mysql: Check
Is there any possibility to check existing of autoextend option
for InnoDB ?
I mean by any sql command and not by searching in my.ini file ?

Syntax Check
Code:

SELECT (((b.close - a.close) / a.close) * 100) FROM `AAH` a, `AAH` b WHERE b.date = '2007-01-03' AND a.date = '2007-01-02'



and said error:

Quote: 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 'b.close - a.close) / a.close) * 100) FROM `AAH` a, `AAH` b WHERE b.date = '2007-' at line 1
it is supposed to retrieve and calculate the percent change for the closing prices of a symbol on a particular stock market. Not sure what the exact error is.

Insert Multiple Rows With One Insert Stmt And Nested Select
I'm trying to insert several rows into a table using only one insert statement:

insert into component_feature values (select 3,1,sf.software_feature_id,1 from software_feature sf where sf.software_id = 1)

When I run the select statement alone, I get the result I want:

+---+---+---------------------+---+
| 3 | 1 | software_feature_id | 1 |
+---+---+---------------------+---+
| 3 | 1 | 0 | 1 |
| 3 | 1 | 1 | 1 |
| 3 | 1 | 2 | 1 |
+---+---+---------------------+---+

But when I run the complete statement I get:

ERROR 1064 (42000): 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 'select 3,1,sf.software_feature_id,1 from software_feature sf where sf.software_i' at line 1

This query is part of a PHP application I'm building. I'd rather not have to write a PHP loop to do multiple inserts.

Date Check Constraint
I'm trying to tack on a check constraint to make sure that when a check-out date is added, to make sure the check-in date is <= the check-out date. A simple inequality throws an error. What would be the correct way to handle this?

Create table maintenance(
mid char(5) primary key not null,
cid char(5) not null references cars(cid),
pid char(5) not null references people(pid),
check_in_date date not null,
check_out_date CHECK (check_in_date<= check_out_date),
milage int not null CHECK(milage>=0),
service_description varchar (255),
UNIQUE(mid)
);

#1064 - 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 'CHECK (check_in_date<= check_out_date), milage int not null CHECK(milage>=0), ' at line 6


Copyright © 2005-08 www.BigResource.com, All rights reserved