Search Results

Search found 1334 results on 54 pages for 'constraint satisfaction'.

Page 4/54 | < Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >

  • Primary Key Identity Value Increments On Unique Key Constraint Violation

    - by Jed
    I have a SqlServer 2008 table which has a Primary Key (IsIdentity=Yes) and three other fields that make up a Unique Key constraint. In addition I have a store procedure that inserts a record into the table and I call the sproc via C# using a SqlConnection object. The C# sproc call works fine, however I have noticed interesting results when the C# sproc call violates the Unique Key constraint.... When the sproc call violates the Unique Key constraint, a SqlException is thrown - which is no surprise and cool. However, I notice that the next record that is successfully added to the table has a PK value that is not exactly one more than the previous record - For example: Say the table has five records where the PK values are 1,2,3,4, and 5. The sproc attempts to insert a sixth record, but the Unique Key constraint is violated and, so, the sixth record is not inserted. Then the sproc attempts to insert another record and this time it is successful. - This new record is given a PK value of 7 instead of 6. Is this normal behavior? If so, can you give me a reason why this is so? (If a record fails to insert, why is the PK index incremented?) If this is not normal behavior, can you give me any hints as to why I am seeing these symptoms?

    Read the article

  • One check constraint or multiple check constraints?

    - by RenderIn
    Any suggestions on whether fewer check constraints are better, or more? How should they be grouped if at all? Suppose I have 3 columns which are VARCHAR2(1 BYTE), each of which is a 'T'/'F' flag. I want to add a check constraint to each column specifying that only characters IN ('T', 'F') are allowed. Should I have 3 separate check constraints, one for each column: COL_1 IN ('T', 'F') COL_2 IN ('T', 'F') COL_3 IN ('T', 'F') Or a single check constraint: COL_1 IN ('T', 'F') AND COL_2 IN ('T', 'F') AND COL_3 IN ('T', 'F') My thoughts are it is best to keep these three separate, as the columns are logically unrelated to each other. The only case I would have a check constraint that examines more than one column is if there was some relationship between the value in one and the value in another, e.g.: (PARENT_CNT > 0 AND PRIMARY_PARENT IS NOT NULL) OR (PARENT_CNT = 0 AND PRIMARY_PARENT IS NULL)

    Read the article

  • Constrain generic extension method to base types and string

    - by hitch
    I want to have an extension method for XElement/XAttribute that allows me to apply a "ValueOrDefault" logic - perhaps with various slightly different implementations: ValueOrNull, ValueOrDefault, NumericValueOrDefault (which validates if the value is numeric), but I want to constrain these methods so that they can only work with ValueTypes or String (i.e. it does not really make sense to use any other reference types. Is it possible to do this with one implementation of each method, or will I have to have one where the constraint is "Structure" and one where the constraint is "String" - if I combine Structure and String in the generic constraint, I get the error : 'Structure' constraint and a specific class type constraint cannot be combined. An example of the current method implementation is as follows: <Extension()> _ Public Function ValueOrDefault(Of T As {Structure})(ByVal xe As XElement, ByVal defaultValue As T) As T If xe Is Nothing or xe.Value = "" Then Return defaultValue End If Return CType(Convert.ChangeType(xe.Value, GetType(T)), T) End Function

    Read the article

  • PHP Postgres constraint violation - can I get the constraint name somehow?

    - by RnR
    We have a web application talking to a Postgres SQL database at work - I've set up many constraints on the server to keep data consistent but we have problems with reporting nicely what it is that prevents the user from entering his (invalid) data at a given moment. The only thing we can get is "Constraint violation" but that isn't very descriptive, from perl or directly from PGAdmin we get nice info as to which constraint caused the failure (the constraint's name) - is there a way to do the same in PHP? We're able to upgrade PHP or use a different db access module if it would help so I'm interested in knowing if it's possible to do using any way that you could safely recommend.

    Read the article

  • SQL SERVER – GUID vs INT – Your Opinion

    - by pinaldave
    I think the title is clear what I am going to write in your post. This is age old problem and I want to compile the list stating advantages and disadvantages of using GUID and INT as a Primary Key or Clustered Index or Both (the usual case). Let me start a list by suggesting one advantage and one disadvantage in each case. INT Advantage: Numeric values (and specifically integers) are better for performance when used in joins, indexes and conditions. Numeric values are easier to understand for application users if they are displayed. Disadvantage: If your table is large, it is quite possible it will run out of it and after some numeric value there will be no additional identity to use. GUID Advantage: Unique across the server. Disadvantage: String values are not as optimal as integer values for performance when used in joins, indexes and conditions. More storage space is required than INT. Please note that I am looking to create list of all the generic comparisons. There can be special cases where the stated information is incorrect, feel free to comment on the same. Please leave your opinion and advice in comment section. I will combine a final list and update this blog after a week. By listing your name in post, I will also give due credit. Reference: Pinal Dave (http://blog.SQLAuthority.com) Filed under: Pinal Dave, SQL, SQL Authority, SQL Constraint and Keys, SQL Data Storage, SQL Performance, SQL Query, SQL Server, SQL Tips and Tricks, SQLServer, T SQL, Technology

    Read the article

  • Sqlite table constraint - unique on multiple columns

    - by Rich
    I can find syntax "charts" on this on the sqlite website, but no examples and my code is crashing. I have other tables with unique constraints on a single column, but I want to add a constraint to the table on two columns. This is what I have that is causing a SQLiteException with the message "syntax error". CREATE TABLE name (column defs) UNIQUE (col_name1, col_name2) ON CONFLICT REPLACE I'm doing this based on the following: table-constraint

    Read the article

  • Unique Constraint At Data Level in GAE

    - by Ngu Soon Hui
    It seems that the unique constraint is not natively supported in GAE, although one can enforce unique check before putting an object to store. But that was in January 2009, what about now? Can I specify unique constraint on a column during schema creation? i.e. class Account(db.Model): name = db.StringProperty() email = db.StringProperty() as unique # something like this @classmethod def create(cls, name, email): a = Account(name=name, email=email) a.put() return a

    Read the article

  • Check constraint over two columns

    - by Rippo
    I want to add a Check Constraint to a table for server 2005 but cannot work it out. MemberId ClubId MeetingId 1 100 10 2 100 10 3 100 10 7 101 10 <-This would throw a check constraint 1 100 11 2 100 11 I do not want to have more than one ClubId for a single MeetingId Basically a ClubId can only belong to a single MeetingId but can have more than one member assigned. How do I achieve this?

    Read the article

  • Adding user role constraint redirects Browser to jsf.js script?

    - by simgineer
    My JSF form login was working with Constraint 1 however when I added Constraint 2 to my web.xml doing a submit on the form now takes me to a jsf javascript page. Can someone tell me what I am doing wrong? I would like only administrators to be able to access the /admin/* pages and only registered users to access the entire site included admin files. BTW after I see the java script page I can still navigate to the intended page in the browser, I just don't want the user to see the intermediate js page or need to know the target page URL. Constraint 1 <security-constraint> <display-name>Admin</display-name> <web-resource-collection> <url-pattern>/admin/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>ADMIN</role-name> </auth-constraint> </security-constraint> Constraint 2 <security-constraint> <display-name>Users</display-name> <web-resource-collection> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>USER</role-name> </auth-constraint> </security-constraint> Here is the undesired url I am being redirected to: javax.faces.resource/jsf.js.xhtml?ln=javax.faces&stage=Development Here is the start of the jsf.js.xhtml... /** @project JSF JavaScript Library @version 2.0 @description This is the standard implementation of the JSF JavaScript Library. */ /** * Register with OpenAjax */ if (typeof OpenAjax !== "undefined" && typeof OpenAjax.hub.registerLibrary !== "undefined") { OpenAjax.hub.registerLibrary("jsf", "www.sun.com", "2.0", null); } // Detect if this is already loaded, and if loaded, if it's a higher version if (!((jsf && jsf.specversion && jsf.specversion >= 20000 ) && (jsf.implversion && jsf.implversion >= 3))) { ... Notes I'm using Firefox 10.0.4, Glassfish 3.1 w JSF2.0 lib, j_security_check, and my login realm setup is similar to this

    Read the article

  • mysql delete and foreign key constraint

    - by user121196
    I'm deleting selected rows from both table in MYSQL, the two tables have foreign keys. delete d,b from A as b inner join B as d on b.bid=d.bid where b.name like '%xxxx%'; MYSQL complains about foreign keys even though I'm trying to delete from both tables: Error: Cannot delete or update a parent row: a foreign key constraint fails (yyy/d, CONSTRAINT fk_d_bid FOREIGN KEY (bid) REFERENCES b (bid) ON DELETE NO ACTION ON UPDATE NO ACTION) what's the best solution here to delete from both table?

    Read the article

  • Cannot add or update a child row: a foreign key constraint fails

    - by Tom
    table 1 +----------+-------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+----------------+ | UserID | int(11) | NO | PRI | NULL | auto_increment | | Password | varchar(20) | NO | | | | | Username | varchar(25) | NO | | | | | Email | varchar(60) | NO | | | | +----------+-------------+------+-----+---------+----------------+ table2 +------------------+--------------+------+-----+---------+----------------+ | Field | Type | Null | Key | Default | Extra | +------------------+--------------+------+-----+---------+----------------+ | UserID | int(11) | NO | MUL | | | | PostID | int(11) | NO | PRI | NULL | auto_increment | | Title | varchar(50) | NO | | | | | Summary | varchar(500) | NO | | | | +------------------+--------------+------+-----+---------+----------------+ com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (myapp/table2, CONSTRAINT table2_ibfk_1 FOREIGN KEY (UserID) REFERENCES table1 (UserID)) What have I done wrong? I read this: http://www.w3schools.com/Sql/sql_foreignkey.asp and i don't see whats wrong. :S

    Read the article

  • Grails automatic constraint update

    - by Prakash
    Does grails have an automatic constraint update. If we change the field in domain class to be nullable by adding constraint, it is not getting reflected in database without schema export. Is it possible to do get grails do this update automatically.

    Read the article

  • ASP.NET JavaScript Routing for ASP.NET MVC–Constraints

    - by zowens
    If you haven’t had a look at my previous post about ASP.NET routing, go ahead and check it out before you read this post: http://weblogs.asp.net/zowens/archive/2010/12/20/asp-net-mvc-javascript-routing.aspx And the code is here: https://github.com/zowens/ASP.NET-MVC-JavaScript-Routing   Anyways, this post is about routing constraints. A routing constraint is essentially a way for the routing engine to filter out route patterns based on the day from the URL. For example, if I have a route where all the parameters are required, I could use a constraint on the required parameters to say that the parameter is non-empty. Here’s what the constraint would look like: Notice that this is a class that inherits from IRouteConstraint, which is an interface provided by System.Web.Routing. The match method returns true if the value is a match (and can be further processed by the routing rules) or false if it does not match (and the route will be matched further along the route collection). Because routing constraints are so essential to the route matching process, it was important that they be part of my JavaScript routing engine. But the problem is that we need to somehow represent the constraint in JavaScript. I made a design decision early on that you MUST put this constraint into JavaScript to match a route. I didn’t want to have server interaction for the URL generation, like I’ve seen in so many applications. While this is easy to maintain, it causes maintenance issues in my opinion. So the way constraints work in JavaScript is that the constraint as an object type definition is set on the route manager. When a route is created, a new instance of the constraint is created with the specific parameter. In its current form the constraint function MUST return a function that takes the route data and will return true or false. You will see the NotEmpty constraint in a bit. Another piece to the puzzle is that you can have the JavaScript exist as a string in your application that is pulled in when the routing JavaScript code is generated. There is a simple interface, IJavaScriptAddition, that I have added that will be used to output custom JavaScript. Let’s put it all together. Here is the NotEmpty constraint. There’s a few things at work here. The constraint is called “notEmpty” in JavaScript. When you add the constraint to a parameter in your C# code, the route manager generator will look for the JsConstraint attribute to look for the name of the constraint type name and fallback to the class name. For example, if I didn’t apply the “JsConstraint” attribute, the constraint would be called “NotEmpty”. The JavaScript code essentially adds a function to the “constraintTypeDefs” object on the “notEmpty” property (this is how constraints are added to routes). The function returns another function that will be invoked with routing data. Here’s how you would use the NotEmpty constraint in C# and it will work with the JavaScript routing generator. The only catch to using route constraints currently is that the following is not supported: The constraint will work in C# but is not supported by my JavaScript routing engine. (I take pull requests so if you’d like this… go ahead and implement it).   I just wanted to take this post to explain a little bit about the background on constraints. I am looking at expanding the current functionality, but for now this is a good start. Thanks for all the support with the JavaScript router. Keep the feedback coming!

    Read the article

  • Hibernate : Foreign key constraint violation problem

    - by Vinze
    I have a com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException in my code (using Hibernate and Spring) and I can't figure why. My entities are Corpus and Semspace and there's a many-to-one relation from Semspace to Corpus as defined in my hibernate mapping configuration : <class name="xxx.entities.Semspace" table="Semspace" lazy="false" batch-size="30"> <id name="id" column="idSemspace" type="java.lang.Integer" unsaved-value="null"> <generator class="identity"/> </id> <property name="name" column="name" type="java.lang.String" not-null="true" unique="true" /> <many-to-one name="corpus" class="xxx.entities.Corpus" column="idCorpus" insert="false" update="false" /> [...] </class> <class name="xxx.entities.Corpus" table="Corpus" lazy="false" batch-size="30"> <id name="id" column="idCorpus" type="java.lang.Integer" unsaved-value="null"> <generator class="identity"/> </id> <property name="name" column="name" type="java.lang.String" not-null="true" unique="true" /> </class> And the Java code generating the exception is : Corpus corpus = Spring.getCorpusDAO().getCorpusById(corpusId); Semspace semspace = new Semspace(); semspace.setCorpus(corpus); semspace.setName(name); Spring.getSemspaceDAO().save(semspace); I checked and the corpus variable is not null (so it is in database as retrieved with the DAO) The full exception is : com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`xxx/Semspace`, CONSTRAINT `FK4D6019AB6556109` FOREIGN KEY (`idCorpus`) REFERENCES `Corpus` (`idCorpus`)) at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:931) at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2941) at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1623) at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1715) at com.mysql.jdbc.Connection.execSQL(Connection.java:3249) at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1268) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1541) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1455) at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1440) at org.apache.commons.dbcp.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:102) at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:73) at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:33) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2158) at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2638) at org.hibernate.action.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:48) at org.hibernate.engine.ActionQueue.execute(ActionQueue.java:250) at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:298) at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:181) at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:107) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:187) at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:33) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:172) at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:27) at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70) at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:535) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:523) at org.hibernate.impl.SessionImpl.save(SessionImpl.java:519) at org.springframework.orm.hibernate3.HibernateTemplate$12.doInHibernate(HibernateTemplate.java:642) at org.springframework.orm.hibernate3.HibernateTemplate.execute(HibernateTemplate.java:373) at org.springframework.orm.hibernate3.HibernateTemplate.save(HibernateTemplate.java:639) at xxx.dao.impl.AbstractDAO.save(AbstractDAO.java:26) at org.apache.jsp.functions.semspaceManagement_jsp._jspService(semspaceManagement_jsp.java:218) [...] The foreign key constraint has been created (and added to database) by hibernate and I don't see where the constraint can be violated. The table are innodb and I tried to drop all tables and recreate it the problem remains... EDIT : Well I think I have a start of answer... I change the log level of hibernate to DEBUG and before it crash I have the following log insert into Semspace (name, [...]) values (?, [...]) So it looks like it does not try to insert the idCorpus and as it is not null it uses the default value "0" which does not refers to an existing entry in Corpus table...

    Read the article

  • MySQL unique clustered constraint not constraining as expected

    - by igor
    I'm creating a table with: CREATE TABLE movies ( id INT AUTO_INCREMENT PRIMARY KEY, name CHAR(255) NOT NULL, year INT NOT NULL, inyear CHAR(10), CONSTRAINT UNIQUE CLUSTERED (name, year, inyear) ); (this is jdbc SQL) Which creates a MySQL table with a clustered index, "index kind" is "unique", and spans the three clustered columns: full size However, once I dump my data (without exceptions thrown), I see that the uniqueness constraint has failed: SELECT * FROM movies WHERE name = 'Flawless' AND year = 2007 AND inyear IS NULL; gives: id, name, year, inyear 162169, 'Flawless', 2007, NULL 162170, 'Flawless', 2007, NULL Does anyone know what I'm doing wrong here?

    Read the article

  • How do I create a check constraint?

    - by Zack Peterson
    Please imagine this small database... Diagram Tables Volunteer Event Shift EventVolunteer ========= ===== ===== ============== Id Id Id EventId Name Name EventId VolunteerId Email Location VolunteerId Phone Day Description Comment Description Start End Associations Volunteers may sign up for multiple events. Events may be staffed by multiple volunteers. An event may have multiple shifts. A shift belongs to only a single event. A shift may be staffed by only a single volunteer. A volunteer may staff multiple shifts. Check Constraints Can I create a check constraint to enforce that no shift is staffed by a volunteer that's not signed up for that shift's event? Can I create a check constraint to enforce that two overlapping shifts are never staffed by the same volunteer?

    Read the article

  • SQL CHECK constraint issues

    - by blahblah
    I'm using SQL Server 2008 and I have a table with three columns: Length, StartTime and EndTime. I want to make a CHECK constraint on this table which says that: if Length == NULL then StartTime <> NULL and EndTime <> NULL else StartTime == NULL and EndTime == NULL I've begun to try things like this: Length == NULL AND StartTime <> NULL AND EndTime <> NULL Obviously this is not enough, but even this simple expression will not validate. I get the error: "Error validating 'CK_Test_Length_Or_Time'. Do you want to edit the constraint?" Any ideas on how to go about doing this?

    Read the article

  • MYSQL: Error: Cannot add or update a child row: a foreign key constraint fails

    - by DalivDali
    Hi all, Using MySQL on Windows OS, and am getting an error upon attempting to create a foreign key between two tables: CREATE TABLE tf_traffic_stats ( domain_name char(100) NOT NULL, session_count int(11) NULL, search_count int(11) NULL, click_count int(11) NULL, revenue float NULL, rpm float NULL, cpc float NULL, traffic_date date NOT NULL DEFAULT '0000-00-00', PRIMARY KEY(domain_name,traffic_date)) and CREATE TABLE td_domain_name ( domain_id int(10) UNSIGNED AUTO_INCREMENT NOT NULL, domain_name char(100) NOT NULL, update_date date NOT NULL, PRIMARY KEY(domain_id)) The following statement gives me the error present in the subject line (cannot add or update a child row: a foreign key constraint fails): ALTER TABLE td_domain_name ADD CONSTRAINT FK_domain_name FOREIGN KEY(domain_name) REFERENCES tf_traffic_stats(domain_name) ON DELETE RESTRICT ON UPDATE RESTRICT Can someone point me in the right direction of what may be causing the error. I also have a foreign key referencing td_domain_name.domain_id, but I don't think this should be interfering... Appreciate it!

    Read the article

  • Identifying which value of a multi-row inserts fails foreign key constraint

    - by Jonathan
    I have a multi-row insert that looks something like: insert into table VALUES (1, 2, 3), (4, 5, 6), (7, 8, 9); Assume the first attribute (1, 4, 7) is a foreign key to another table and assume that this referenced table does not have the value '4'. A MySQLExeption is thrown with error code 1452. EXCEPTION: Cannot add or update a child row: a foreign key constraint fails (dbName/tableName, CONSTRAINT id FOREIGN KEY (customer_id) REFERENCES referencedTable (customer_id)) Is there a way to identify which value caused the error? I would love to give my user an error message that said something like: Error: '4' does not exist in the referenced table. I am using the .NET mysql connector to execute the insert. Thanks- Jonathan

    Read the article

  • After Trigger execute before constraint check in oracle

    - by satakare
    Hi, I have After Insert/Update trigger on Table T1 which get the referential data for Col1 from T2 and does some work and insert it into another table. The col1 is FK to Table T2. When user insert the incorrect or non existing value into the Col1 and if trigger is disabled I am getting constraint error that is fine. But when trigger is enabled and user insert the wrong value in Col1 trigger is getting fired and shows the 'no data found' error message. Actually I am expecting the table to throw constraint error, but trigger is throwing it. Please let me know your comments about this trigger behaviour.

    Read the article

  • unique constraint (w/o Trigger) on "one-to-many" relation

    - by elgcom
    To illustrate the problem, I make an example: A tag_bundle consists of one or more than one tags. A unique tag combination can map to a unique tag_bundle, vice versa. tag_bundle tag tag_bundle_relation +---------------+ +--------+ +---------------+--------+ | tag_bundle_id | | tag_id | | tag_bundle_id | tag_id | +---------------+ +--------+ +---------------+--------+ | 1 | | 100 | | 1 | 100 | +---------------+ +--------+ +---------------+--------+ | 101 | | 1 | 101 | +--------+ +---------------+--------+ There can't be another tag_bundle having the combination from tag 100 and tag 101. How can I ensure such unique constraint when executing SQL "concurrently"!! that is, to prevent concurrently adding two bundles with the same tag combination Adding a simple unique constraint on any table does not work, Is there any solution other than Trigger or explicit lock. I come to only this simple way: make tag combination into string, and let it be unique. tag_bundle (unique on tags) tag tag_bundle_relation +---------------+--------+ +--------+ +---------------+--------+ | tag_bundle_id | tags | | tag_id | | tag_bundle_id | tag_id | +---------------+--------+ +--------+ +---------------+--------+ | 1 | 100,101| | 100 | | 1 | 100 | +---------------+--------+ +--------+ +---------------+--------+ | 101 | | 1 | 101 | +--------+ +---------------+--------+ but it seems not a good way :(

    Read the article

  • Cannot add or update a child row: a foreign key constraint fails

    - by myaccount
    // Getting the id of the restaurant to which we are uploading the pictures $restaurant_id = intval($_GET['restaurant-id']); if(isset($_POST['submit'])) { $tmp_files = $_FILES['rest_pics']['tmp_name']; $target_files = $_FILES['rest_pics']['name']; $tmp_target = array_combine($tmp_files, $target_files); $upload_dir = $rest_pics_path; foreach($tmp_target as $tmp_file => $target_file) { if(move_uploaded_file($tmp_file, $upload_dir."/".$target_file)) { $sql = sprintf(" INSERT INTO rest_pics (branch_id, pic_name) VALUES ('%s', '%s')" , mysql_real_escape_string($restaurant_id) , mysql_real_escape_string(basename($target_file))); $result = mysql_query($sql) or die(mysql_error()); } I get the next error: Cannot add or update a child row: a foreign key constraint fails (rest_v2.rest_pics, CONSTRAINT rest_pics_ibfk_1 FOREIGN KEY (branch_id) REFERENCES rest_branches (branch_id) ON DELETE CASCADE ON UPDATE CASCADE However, this error totally disappears and everything goes well when I put directly the restaurant id (14 for example) instead of $restaurant_id variable in the sql query. The URL am getting the id from is: http://localhost/rest_v2/public_html/admin/add-delete-pics.php?restaurant-id=2 Any help please?

    Read the article

  • Error 1005 when adding a foreign key constraint on mysql table

    - by luc
    Hello, I have a problem when upgrading a django and mysql app with south. I've tried to make a sql-based upgrade with the code generated by the django sqlall command and I have a similar problem. Here is the sql code: CREATE TABLE `programmations_basissupport` ( `id` integer AUTO_INCREMENT NOT NULL PRIMARY KEY, `value` numeric(6, 0) NOT NULL ) ALTER TABLE `programmations_concert` ADD `basis_support_id` integer AFTER program_status_id; ALTER TABLE `programmations_concert` ADD CONSTRAINT `basis_support_id_refs_id_1e4ed8d7` FOREIGN KEY (`basis_support_id`) REFERENCES `programmations_basissupport` (`id`); An error is raised when adding the FK constraint: ERROR 1005 (HY000): Can't create table 'apidev_mnl.#sql-106e_632b00a' (errno: 150) Does anybody have an idea? Update: DEFAULT values where missing but even if I add the default='' in the django model, the creation of foreign keys fails. Thanks for your help

    Read the article

< Previous Page | 1 2 3 4 5 6 7 8 9 10 11 12  | Next Page >