JSP cannot Insert into MYSQL

hi, i have a jsp code which can successfully return results from MySQL database. But once i change the SQL statement from a select statement to a insert statement, it does not add in a new row in the database. It has no error while compiling but it also appear nothing on the screen when being run. Has the problem got to do with the user privilages of MySQL? thanks.
//jsp file which parameter posted from another html file. Parameter has been successfully passed.
<%@ page import="java.sql.*"%>
<body>
<%
     String file = request.getParameter("file");
     String pic = request.getParameter("pic");
     ResultSet rs = null;
     ResultSet rs2 = null;
     String timestamp = "CURRENT_TIMESTAMP()";
     String q2 = "Select * from fileReqAce";
     String q1 = "INSERT INTO fileReqAce(PIC,FileName,DateReq) VALUES('"+pic+"','"+file+"',CURRENT_Timestamp())";
try{
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wendy?user=user;password=password");
Statement state = con.createStatement();
     %><br><%
     rs = state.executeQuery(q1);
     //Statement state2 = con.createStatement();
     /**rs2 = state2.executeQuery(q2);
     %><br>
     <table border="1"><%
     while(rs2.next()){
     %>
     <tr>
     <td>Request by : <%=rs2.getString("PIC")%></td><td>File Reference : <%=rs2.getString("FileName")%></td><td>Time Requested : <%=rs2.getTimestamp("DateReq")%></td>
     </tr>
     <%
     %></table>
<%**/
     rs.close();
//     rs2.close();
     con.close();
     catch(Exception e)
     System.err.println("Unable to load driver");
     e.printStackTrace();
%>
</body>

That all might be good and well but I think the very important thing to note here is what the first reply stated.
If you are going to run an Insert sql statement you need to use the executeUpdate() method. You also use this function for Updates and Delete SQL statements.
Only Select statements that return a recordset use the executeQuery() method. The executeUpdate() method returns an interger that reflects the number of rows affected by the SQL statement.
Like when you insert 1 row the return value of the executeUpdate method will be one. You can accordingly check this returned value to see if the operation ran successfully. A return value of 0 means that now rows where inserted.
That is my 2c worth. I hope it helped some.

Similar Messages

  • Unable to insert into mysql from flash burrito

    I'm having issues inserting a record to mysql, if I use the test "test operation and use these values the it works fine, but now in the android app.
    values in my test operation
        id:0,
        type:"cool",
        navn:"vegar 16"
    the getall method works fine, and shows up on the network monitor, but the button dont work at all, nothing happends in the network monito, if I debug it I can see that the button works, any suggestions on what Im doing wrong?
    code in my view:
    <?xml version="1.0" encoding="utf-8"?>
    <s:View xmlns:fx="http://ns.adobe.com/mxml/2009"
            xmlns:s="library://ns.adobe.com/flex/spark"
            xmlns:kunderservice="services.kunderservice.*"
            title="Home">
        <fx:Script>
            <![CDATA[
                import mx.events.FlexEvent;
                import valueObjects.Kunder;
                protected function list_creationCompleteHandler(event:FlexEvent):void
                    getAllKunderResult.token = kunderService.getAllKunder();
                protected function button_clickHandler(event:MouseEvent):void
                    var item:Kunder = new Kunder();
                    item.id=0
                    item.navn="vegar"
                    item.type ="test"
                    createKunderResult2.token = kunderService.createKunder(item);
            ]]>
        </fx:Script>
        <fx:Declarations>
            <s:CallResponder id="getAllKunderResult"/>
            <kunderservice:KunderService id="kunderService"/>
            <s:CallResponder id="createKunderResult2"/>
            <!-- Place non-visual elements (e.g., services, value objects) here -->
        </fx:Declarations>
        <s:List id="list" x="35" y="45" width="409" height="193"
                creationComplete="list_creationCompleteHandler(event)" labelField="navn">
            <s:AsyncListView list="{getAllKunderResult.lastResult}"/>
        </s:List>
        <s:Button id="button" x="20" y="406" label="Button" click="button_clickHandler(event)"/>
        </s:View>

    I really appreciate your help. Yes indeed, debugging and seeing what is going on in general is most difficult with flash!
    Once I get this cracked I should be able to complete a lot of what I am trying to achieve.
    After inserting some echo's into my php as such:
    <?php
    $player = $_POST['player'];
    $tournament = $_POST['tournament'];
    $position = $_POST['position'];
    $prize = $_POST['prize'];
    mysql_connect("localhost", "root","poker");
    echo "onnected to database"
    mysql_select_db("poker");
    echo "database connected";
    mysql_query("INSERT INTO results(player,tournament,position,prize) VALUES
    ('$player','$tournamnet','$position','$prize')");
    echo "result added";
    ?>
    The returned info is a load of nonsense to me:
    response from server:  %3C%3Fphp%0A%24player%20=%20%24%5FPOST%5B%27player%27%5D%3B%0A%24tournament%20%3D%20%24%5 FPOST%5B%27tournament%27%5D%3B%0A%24position%20%3D%20%24%5FPOST%5B%27position%27%5D%3B%0A% 24prize%20%3D%20%24%5FPOST%5B%27prize%27%5D%3B%0A%0Amysql%5Fconnect%28%22localhost%22%2C%2 0%22root%22%2C%22poker%22%29%3B%0Aecho%20%22onnected%20to%20database%22%0Amysql%5Fselect%5 Fdb%28%22poker%22%29%3B%0Aecho%20%22database%20connected%22%3B%0Amysql%5Fquery%28%22INSERT %20INTO%20results%28player%2Ctournament%2Cposition%2Cprize%29%20VALUES%20%0A%28%27%24playe r%27%2C%27%24tournamnet%27%2C%27%24position%27%2C%27%24prize%27%29%22%29%3B%0Aecho%20%22re sult%20added%22%3B%0A%3F%3E

  • Noob help to format date to insert into mysql

    Sorry, if this question has been asked before, I did di a search but could not find an answer that I could understand.  I am pretty new to DW and my coding skills are not good so please go easy on me.
    I have a simple form to insert records to a mysql database.  I have created a form validarion behaviour to require the fields that are set as not-NULL in the database.  How do I modify the code to allow the date format to be entered in the dob field in the form as DD/MM/YYYY but inserted correctly in the database as YYYY/MM/DD?
    Finally, how would I then modify it further to default to todays date?
    Here's my code:
    <?php require_once('Connections/mypms.php'); ?>
    <?php
    function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "")
      $theValue = (!get_magic_quotes_gpc()) ? addslashes($theValue) : $theValue;
      switch ($theType) {
        case "text":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;   
        case "long":
        case "int":
          $theValue = ($theValue != "") ? intval($theValue) : "NULL";
          break;
        case "double":
          $theValue = ($theValue != "") ? "'" . doubleval($theValue) . "'" : "NULL";
          break;
        case "date":
          $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
          break;
        case "defined":
          $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
          break;
      return $theValue;
    $editFormAction = $_SERVER['PHP_SELF'];
    if (isset($_SERVER['QUERY_STRING'])) {
      $editFormAction .= "?" . htmlentities($_SERVER['QUERY_STRING']);
    if ((isset($_POST["MM_insert"])) && ($_POST["MM_insert"] == "form1")) {
      $insertSQL = sprintf("INSERT INTO demographics (title, firstname, surname, dob, address1, address2, town, county, postcode) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)",
                           GetSQLValueString($_POST['title'], "text"),
                           GetSQLValueString($_POST['firstname'], "text"),
                           GetSQLValueString($_POST['surname'], "text"),
                           GetSQLValueString($_POST['dob'], "date"),
                           GetSQLValueString($_POST['address1'], "text"),
                           GetSQLValueString($_POST['address2'], "text"),
                           GetSQLValueString($_POST['town'], "text"),
                           GetSQLValueString($_POST['county'], "text"),
                           GetSQLValueString($_POST['postcode'], "text"));
      mysql_select_db($database_mypms, $mypms);
      $Result1 = mysql_query($insertSQL, $mypms) or die(mysql_error());
    $recordID = mysql_insert_id();
      $insertGoTo = "detail_tab.php?recordID=$recordID";
      if (isset($_SERVER['QUERY_STRING'])) {
        $insertGoTo .= (strpos($insertGoTo, '?')) ? "&" : "?";
        $insertGoTo .= $_SERVER['QUERY_STRING'];
      header(sprintf("Location: %s", $insertGoTo));
      exit();
    $colname_insert = "1";
    if (isset($_GET['recordID'])) {
      $colname_insert = (get_magic_quotes_gpc()) ? $_GET['recordID'] : addslashes($_GET['recordID']);
    mysql_select_db($database_mypms, $mypms);
    $query_insert = sprintf("SELECT px_id, title, firstname, surname, dob, address1, address2, town, county, postcode FROM demographics WHERE px_id = %s", $colname_insert);
    $insert = mysql_query($query_insert, $mypms) or die(mysql_error());
    $row_insert = mysql_fetch_assoc($insert);
    $totalRows_insert = mysql_num_rows($insert);
    ?>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    <title>address</title>
    <script language="JavaScript" type="text/JavaScript">
    <!--
    function MM_findObj(n, d) { //v4.01
      var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
        d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
      if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
      for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=MM_findObj(n,d.layers[i].document);
      if(!x && d.getElementById) x=d.getElementById(n); return x;
    function MM_validateForm() { //v4.0
      var i,p,q,nm,test,num,min,max,errors='',args=MM_validateForm.arguments;
      for (i=0; i<(args.length-2); i+=3) { test=args[i+2]; val=MM_findObj(args[i]);
        if (val) { nm=val.name; if ((val=val.value)!="") {
          if (test.indexOf('isEmail')!=-1) { p=val.indexOf('@');
            if (p<1 || p==(val.length-1)) errors+='- '+nm+' must contain an e-mail address.\n';
          } else if (test!='R') { num = parseFloat(val);
            if (isNaN(val)) errors+='- '+nm+' must contain a number.\n';
            if (test.indexOf('inRange') != -1) { p=test.indexOf(':');
              min=test.substring(8,p); max=test.substring(p+1);
              if (num<min || max<num) errors+='- '+nm+' must contain a number between '+min+' and '+max+'.\n';
        } } } else if (test.charAt(0) == 'R') errors += '- '+nm+' is required.\n'; }
      } if (errors) alert('The following error(s) occurred:\n'+errors);
      document.MM_returnValue = (errors == '');
    //-->
    </script>
    </head>
    <body>
    <p> </p>
    <form action="<?php echo $editFormAction; ?>" method="post" name="form1" onSubmit="MM_validateForm('firstname','','R','surname','','R','dob','','R');return document.MM_returnValue">
      <table align="center">
        <tr valign="baseline">
          <td nowrap align="right">Title:</td>
          <td><input type="text" name="title" value="" size="32"></td>
          <td> </td>
        </tr>
        <tr valign="baseline">
          <td nowrap align="right">Firstname:</td>
          <td><input type="text" name="firstname" value="" size="32"></td>
          <td> </td>
        </tr>
        <tr valign="baseline">
          <td nowrap align="right">Surname:</td>
          <td><input type="text" name="surname" value="" size="32"></td>
          <td> </td>
        </tr>
        <tr valign="baseline">
          <td nowrap align="right">Dob:</td>
          <td><input type="text" name="dob" value="" size="32"></td>
          <td> </td>
        </tr>
        <tr valign="baseline">
          <td nowrap align="right">Address1:</td>
          <td><input type="text" name="address1" value="" size="32"></td>
          <td> </td>
        </tr>
        <tr valign="baseline">
          <td nowrap align="right">Address2:</td>
          <td><input type="text" name="address2" value="" size="32"></td>
          <td> </td>
        </tr>
        <tr valign="baseline">
          <td nowrap align="right">Town:</td>
          <td><input type="text" name="town" value="" size="32"></td>
          <td> </td>
        </tr>
        <tr valign="baseline">
          <td nowrap align="right">County:</td>
          <td><input type="text" name="county" value="" size="32"></td>
          <td> </td>
        </tr>
        <tr valign="baseline">
          <td nowrap align="right">Postcode:</td>
          <td><input type="text" name="postcode" value="" size="32"></td>
          <td><input name="Search" type="button" id="Search" value="Search"></td>
        </tr>
        <tr valign="baseline">
          <td nowrap align="right"> </td>
          <td><input type="submit" value="Insert record"></td>
          <td> </td>
        </tr>
      </table>
      <input type="hidden" name="MM_insert" value="form1">
    </form>
    <p> </p>
    </body>
    </html>
    <?php
    mysql_free_result($insert);
    ?>
    Thank you for your help :-)

    barrydocks wrote:
    thanks for the reply osgood;
    I was hoping for a more simple solution than a JQuery date picker, I have read this threat where the SQL queries is aletered:
    http://forums.adobe.com/thread/450108
    Which I tried but could not make work.
    I haven't tried DATE_FORMAT but the example implies that it would work when SELECTING the date from the database to output to a page in a more conventional FORMAT. However you want to INSERT the date using the correct format.
    barrydocks wrote:
    http://forums.adobe.com/thread/1097555
    but I don't know how to use this in my code that already has form validation?
    That thread is implying that you would need to convert the date inserted into the form field before it is inserted into the database in the correct format.......so you may as well use a datepicker.
    Problem with letting anyone insert a date manually is that a date can be written in many formats which are NOT acceptable by the database. A datepicker overcomes all of these issues. Getting the date back out of the database is a case of simply converting via php into a format which is applicable to your country or your usage OR using the method in the first thread you provided.
    Lets see if anyone else can offer a more simple solution for you.

  • How to insert into mysql the creation time and modification time from java?

    first how?
    Second what is better from create the date from java or do it from mysql?
    thanks in advace
    Pedro

    One way is to use the GetDate function in mysql. This will set the date as you insert data. insert into table(date) values(getdate())
    Anytime you modifiy the table just call the function again and update its fields.
    Dont know which is beter to do. In java or on the database side.

  • Cannot insert into database

    Can any body help plzzzzzzzzzzzzzzzz,
    I establish a connection using connection pooling as given in netbeans
    helps.With that ican retrieve data from database but cant insert into it.While inserting only null values ere entered into database.why?
    please somebody help

    My Jsp page userRegistration.jsp
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
    <%@taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
    <%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
    <%@ page import="java.sql.*" %>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
            </head>
        <body>
    <html:errors/>
        <table>
    <html:form action="reg.do"method="post" >
    <tr>
    <td>
    firstname<html:text  property="firstName"  />
    </td>
    </tr>
    <tr>
    <td>
    lastname<html:text property="lastName" />
    </td>
    </tr>
    <tr>
    <td>
    username<html:text property="userName" />
    </td>
    </tr>
    <tr><td>
    email<html:text property="email" />
    </td>
    </tr>
    <tr>
    <td>
    phone<html:text property="phone" />
    </td>
    </tr>
    <tr>
    <td>
    fax<html:text property="fax" />
    </td>
    </tr>
    <tr>
    <td>
    password<html:password property="password" />
    </td>
    </tr>
    <tr><td>
    passwordcheck<html:password property="passwordCheck" />
    </td>
    </tr>
    <tr>
    <td>
    <html:submit />
    </td>
    <td>
    <html:cancel />
    </td>
    </tr>
    </table>
    </html:form>
    </body>
    </html>
    my struts action
    package action;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionMapping;
    import org.apache.struts.action.ActionForward;
    import javax.servlet.http.HttpSession;
    public class reg extends Action {
         private String firstName;
        private String lastName;
        private String userName;
               private String email;
               private String phone;
               private String fax;
               private String password;
               private String passwordCheck;
        /* forward name="success" path="" */
        private final static String SUCCESS = "success";
        public ActionForward execute(ActionMapping mapping, ActionForm  form,
                HttpServletRequest request, HttpServletResponse response)
                throws Exception {
            response.sendRedirect("complete.jsp");
            return mapping.findForward(getSUCCESS());
        public String getFirstName() {
            return firstName;
        public void setFirstName(String firstName) {
            this.firstName = firstName;
        public String getLastName() {
            return lastName;
        public void setLastName(String lastName) {
            this.lastName = lastName;
        public String getUserName() {
            return userName;
        public void setUserName(String userName) {
            this.userName = userName;
        public String getEmail() {
            return email;
        public void setEmail(String email) {
            this.email = email;
        public String getPhone() {
            return phone;
        public void setPhone(String phone) {
            this.phone = phone;
        public String getFax() {
            return fax;
        public void setFax(String fax) {
            this.fax = fax;
        public String getPassword() {
            return password;
        public void setPassword(String password) {
            this.password = password;
        public String getPasswordCheck() {
            return passwordCheck;
        public void setPasswordCheck(String passwordCheck) {
            this.passwordCheck = passwordCheck;
        public static String getSUCCESS() {
            return SUCCESS;
        private javax.sql.DataSource getHima() throws javax.naming.NamingException {
            javax.naming.Context c = new javax.naming.InitialContext();
            return (javax.sql.DataSource) c.lookup("java:comp/env/jdbc/hima");
    my complete.jsp where insertion happens
    <%@page contentType="text/html"%>
    <%@page pageEncoding="UTF-8"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
    <%@taglib prefix="c"uri="http://java.sun.com/jsp/jstl/core"%>
    <%@taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
    <%@ page import="java.sql.*" %>
    String firstName=("firstName");
    String lastName = getInitParameter("lastName");
    String userName = getInitParameter("userName");
    String email= getInitParameter("email");
    String phone = getInitParameter("phone");
    String fax = getInitParameter("fax");
    String password = getInitParameter("password");
    String passwordCheck = getInitParameter("passwordCheck");
    <%
           String firstName=(String)request.getAttribute("firstName");
           request.getSession().setAttribute("firstName",firstName);
    %>  
    <sql:query var="queryresults" dataSource="jdbc/hima">
            select phone from user
            </sql:query>
    <sql:update var="resultset" dataSource="jdbc/hima">
                INSERT INTO user1 (firstName,lastName,userName,email,phone,fax,password,passwordCheck)
                VALUES(firstName,lastName,userName,email,phone,fax,password,passwordCheck)
            </sql:update>
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
       "http://www.w3.org/TR/html4/loose.dtd">
       <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            <title>JSP Page</title>
        </head>
        <body>
    <form action="comp"></form>
        <h1>JSP Page</h1>
        <table>
        <tr>
        <th>first</th>
        </tr>
        <c:forEach var="row" items="${queryresults.rows}">
            <tr>
            <td><c:out value="${row.phone}"/></td>
            </tr>
        </c:forEach>
    </table>
        </body>
    </html>

  • Help on Chinese insert into mysql (urgent)

    Dear Friends,
    we are running an coldfusion mx application on window,
    perfect, the database is mysql, utf-8 encoding.
    But when we moved to redhat linux +mysql, the chinese in the
    database displayed as ?????. when we insert into database, the
    chinese inserted like ????? as well...
    Any thing that we missed to config...please help.
    thanks,

    [This page|http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/] has a good explanation of where the issues might be.
    The thing with character encodings is that you have to get it right at every step. If you miss one of them, then the whole thing blows apart.
    From the minimal info you have here, I would take a look at the request.setCharacterEncoding() methd.
    cheers,
    evnafets

  • Drop down menu for birthday, inserting into Mysql

    I have a registration form that inserts a new record into
    mysql.
    For the birthday, I have two spryselect dropdowns (month and
    day), and one spry textfield (year).
    Once the user submits the form, how can the selected values
    (month and day) be combined with the inputted year so mysql can
    accept it: YYYY-MM-DD.
    Here is my insert code. I tried concat but I don't think I
    did it right.
    if ((isset($_POST["MM_insert"])) &&
    ($_POST["MM_insert"] == "form1")) {
    $insertSQL = sprintf("INSERT INTO members (Username,
    Password, `First`, `Last`, Birthday, Address1, Address2, City,
    `State`, Zip, Phone, Email, Newsletter) VALUES (%s, %s, %s, %s, %s,
    %s, %s, %s, %s, %s, %s, %s, %s)",
    GetSQLValueString($_POST['Username'], "text"),
    GetSQLValueString($_POST['Password'], "text"),
    GetSQLValueString($_POST['First_Name'], "text"),
    GetSQLValueString($_POST['Last_Name'], "text"),
    GetSQLValueString($_POST['Birthday'], $year.$month.$day),
    GetSQLValueString($_POST['Address1'], "text"),
    GetSQLValueString($_POST['Address2'], "text"),
    GetSQLValueString($_POST['City'], "text"),
    GetSQLValueString($_POST['State'], "text"),
    GetSQLValueString($_POST['Zip'], "int"),
    GetSQLValueString($_POST['Phone_Number'], "int"),
    GetSQLValueString($_POST['EMail_Address'], "text"),
    GetSQLValueString($_POST['Newsletter'], "text"));

    chris.cavage wrote:
    > Here is my insert code. I tried concat but I don't think
    I did it right.
    Assuming you have named the select elements and text field
    "month",
    "day", and "year", you need to add this somewhere near the
    top of the page:
    if (isset($_POST['month']) && isset($_POST['day'])
    isset($_POST['year'])) {
    $_POST['birthday'] =
    "{$_POST['year']}-{$_POST['month']}-{$_POST['day']}";
    } else {
    $_POST['birthday'] = 0;
    Then change this:
    > GetSQLValueString($_POST['Birthday'],
    > $year.$month.$day),
    to this:
    GetSQLValueString($_POST['Birthday'], "text"),
    David Powers, Adobe Community Expert
    Author, "The Essential Guide to Dreamweaver CS4",
    "PHP Solutions" & "PHP Object-Oriented Solutions"
    http://foundationphp.com/

  • FRM-40602: Cannot insert into or update data in a view

    Hi all!
    I have a form based on a view and I want to get rid off this message.
    I set the properties blocks query only but it still doesn't work.
    Does someone met with this situation?
    Many thanks!

    Hello
    I've just been messing about with a similar problem. Basically, I have a view that involves a join across two tables, I have a data block in my form that's based on the view, and I've written an INSTEAD OF trigger to insert/update/delete from the two tables.
    I was getting the error message 'Cannot insert or update data in a view', and it turned out that the error was happening because the join column between the two tables was the primary key on one of the tables, but the corresponding column on the join table had no unique key on it. This meant that Oracle couldn't establish a one-to-one relationship between rows in the view and rows in the underlying tables. The column on the join table was in fact unique on that table, and adding a unique constraint on that column in the database cured the problem.
    Hope that's of use.
    regards
    Andrew
    UK

  • Can select, but cannot insert into oracle tables using php.

    I am having trouble inserting data into a tables in oracle using PHP. I can insert into the tables using baninst1, but nothing else. I can't even insert using the tables' owner. Every time I try I get the ORA-00492 error of table or view does not exist. However, I can run a select statement just fine. So far, baninst1 is the only user that can actually do inserts. I've triple checked all the table grants and everything is fine. Also, I can copy/paste the exact insert statement into SQL*Plus and it works with the correct user. It doesn't have to be baninst1. I've tried everything I can think of. I've tried putting the table name in quotes, adding the schema name to the table, checking public synonyms, but everything appears to be ok. I would greatly appreciate any suggestions others may have.
    I'm using PHP 5.2.3 with an oracle 9i DB.

    Here is the code that doesn't work. It works only with baninst1, no other username will work and all I do is change the my_username/my_password to something different. This is one example function where I try to do an insert, but it doesn't work on any of the tables I try.
    Thanks for looking.
    class Oracle {
         private $oracleUser = "my_username";
         private $oraclePassword = "my_password";
         private $oracleDB = "MY_DB";
         private $c = null;
         function Connect() {
              if ( !($this->c = ocilogon( $this->oracleUser, $this->oraclePassword, $this->oracleDB ) ) )
                   return false;
              return true;
         function AddNewTest($testName, $course, $section, $term, $maxAttempts, $length, $startDate, $startTime, $endDate, $endTime)
              $result = "";
              if( $this->c == null )
                   $this->Connect();     
              $splitIndex = strpos($course, " ");
              $subjectCode = substr($course, 0, $splitIndex);
              $courseNumber = substr($course, $splitIndex + 1);
              $insertStatment = "insert into szbtestinfo(szbtestinfo_test_name,
                                                                szbtestinfo_course_numb,
                                                           szbtestinfo_section,
                                                                szbtestinfo_max_attempts,
                                                                szbtestinfo_length_minutes,
                                                                szbtestinfo_start,
                                                                szbtestinfo_end,
                                                                szbtestinfo_id,
                                                                szbtestinfo_subj_code,
                                                                szbtestinfo_eff_term)
                                                                values( '" . $testName .
                   "', '" . $courseNumber .
                   "', '" . $section .
                   "', " . $maxAttempts .
                   ", " . $length .
                   ", to_date('" . $startDate . " " . $startTime . "', 'MM/DD/YYYY HH24:MI')" .
                   ", to_date('" . $endDate . " " . $endTime . "', 'MM/DD/YYYY HH24:MI')" .
                   ", szsnexttest.nextval" .
                   ", '" . $subjectCode .
                   "', '" . $term . "')";
              //return $insertStatment;
              $s = OCIParse($this->c, $insertStatment);
              try
                   $result = OCIExecute($s);
              catch(exception $e)
              return $result;
         }

  • List/Menu (multiple selected)  insert into MySQL

    I have been building a feedback form and I am running into a
    issue that when I place a list/menu that allows multiple selections
    when I submit my form in my MySQL database it collected the
    information but only on the last multiple selection.
    For example, this is what my list/menu looks like.
    <select name="occasion" size="5" multiple="MULTIPLE"
    id="occasion">
    <option value="Spur of the moment,">Spur of the
    moment</option>
    <option value="Family dinner">Family
    dinner</option>
    <option value="Special occasion (i.e.
    birthday)">Special occasion (i.e. birthday)</option>
    <option value="Office get together">Office get
    together</option>
    <option value="Romantic dinner">Romantic
    dinner</option>
    <option value="Night out with friends">Night out with
    friends</option>
    <option value="Business meeting">Business
    meeting</option>
    <option value="Other">Other</option>
    </select>
    And my MySQL database I have it set up as...
    Field Type
    occasion mediumtext
    I do not know why I cannot have more than one selection
    inputed into my field, what must I do to correct this? Everything
    works perfectly expect the multi selected list/menu. I want to
    place all that is selected in the list/menu in that one database
    field called occasion.

    .oO(MikeL7)
    >>You should also test with isset() and is_array() if
    $_POST['occasion']
    >>is available at all and of the expected type. The
    code above will also
    >>throw a notice if $insert_string is not initialized
    before the loop.
    >
    > I use both isset and is_array in my code, When you say
    notice, you dont mean
    >a script stoppiong error?
    Nope. An E_NOTICE error won't terminate the script, but
    shouldn't happen
    nevertheless. While developing, the error_reporting directive
    should be
    set to E_ALL|E_STRICT and _all_ reported problems should be
    solved. It's
    not only better coding style, but also helps to prevent real
    errors. In
    this particular case it was just a guess, because it was only
    a part of
    the code. But using an uninitialized variable with a '.='
    operator for
    example would lead to a notice, which should be fixed.
    >>But of course this is a really bad DB design, as it
    already violates the
    >> first normal form (1NF). Just some ideas for queries
    that might come to
    >> mind, but would be really hard to do with such a
    comma-separated list:
    >
    > A better table design would be to have column for |
    list_ID | user_ID |
    >song_ID | and do a insert for each song selected.
    Yes, something like that.
    >Thanks for the input, i like escaping the variables from
    a string as they
    >stand out more in code view, is the single quote method
    faster? And which one
    >will be or is already deprecated?
    All are correct and won't be deprecated. IMHO it's more or
    less just
    personal preference. It also depends on the used editor and
    its syntax
    highlighting capabilities. For example I use Eclipse/PDT for
    all my PHP
    scripts, which can also highlight variables inside a string.
    But if the
    above is your preferred way, there's nothing really wrong
    with it.
    Just some additional thoughts:
    Personally I prefer as less escaping and concatenating as
    possible,
    because such a mixture of single quotes, double quotes, dots
    and
    sometimes even escaped quote signs (for example when printing
    HTML)
    _really_ confuses me. I like to keep my code clean and
    readable.
    Something like this:
    print "<img src=\"".$someVar."\" ...>\n";
    not only hurts my eye, it is also quite error-prone. It's
    easy to miss a
    quote or a backslash and get a parse error back, especially
    in editors
    with limited syntax highlighting (or none at all). So I would
    prefer
    print "<img src='$someVar' ...>\n";
    or even
    printf("<img src='%s' ...>\n", $someVar);
    When it comes to performance issues, of course there's a
    difference
    between the various methods. But for me they don't really
    matter. In
    practice you usually won't notice any difference between an
    echo, a
    print or a printf() call for example, as long as you don't
    call them
    a million times in a loop.
    So I always just use the method that leads to the most
    readable code.
    In many cases, especially when a lot of variables or
    expressions are
    involved, (s)printf() wins. Not for performance, but for
    readability.
    But as said - personal preference. YMMV.
    Micha

  • Inserting Into MYSQL Table Via Air/PHP = Not Allowed?

    I'm having trouble inserting data into my mysql database tables through my air app. All the code is pretty much exactly the same as in some examples I've seen but it simply won't do it. Is this because of some sort of security restriction because the air app is on my machine and the server with my mysql database on is elsehwhere? Or is it possible to insert data via an air app?
    Here is the example I've been following:-
    http://livedocs.adobe.com/flex/3/html/help.html?content=data_access_2.html

    jimmyoneshot wrote:
    Thanks for the answers boys. I've decided I'm going to change it into a flex app instead as then there won't be any problems. It simply means I'll have to add a logon system to it.
    While were on the subject do you guys happen to know of any examples anywhere of how someone can REMOVE data from an sql table via flex/php?
    What I'm looking for is basically when a user uses my app and enters info into some text inputs, if that specfic info exists within a table then that data will be removed from the table. The way this works is that they will choose an item within a tilelist which is populated by the data from this mysql table and this will insert the data of the selected item into the text inputs and then they click a remove button to remove that item. Can't find anything similar anywhere though.
    You will have to use a common identifier, eg:
    give each row in your database an ID.
    then pass that ID value on the button press to a PHP script, which does something like:
    $deleteID = $_POST["delID"];
    mysql_query("DELETE FROM exampleTable WHERE ID='$deleteID
    maybe check that a row with that ID exists first for verification, then pass back a value indicating if removal was a success or not.
    You can delete on other values, but remember they have to be unique for the database, else you'll run the risk of deleting multiple values.
    Or you could delete on a compound key, depends on the data you're storing in the grid.

  • Read text file and insert into MySQL

    Dears,
    I need to read text file and then insert the data in the correct column in the MySQL database
    example
    I have the following text file:
    field1=1234 field2=56789 field3=444555
    field1=1333 field2=2222 field3=333555
    and so on and so forth ,,note that all rows are identical and just the filed value is changed(there is a dilemeter between fields)
    how can I read field1,field2 and field3 from text file and insert them in the correct table and column in the database.....
    any help?????
    thanks for your cooperation
    Best Regars

    Sure.
    Which part don't you understand?
    1. Reading a text file
    2. Parsing the text file contents.
    3. Relational databases and SQL.
    4. How to create a database.
    5. How to connect to a database in Java.
    6. How to insert records into the database in Java.
    7. How to map Java objects to records in a database.
    This is a pretty nice list. Solve complex problems by breaking them into smaller ones.
    %

  • Why JApplet and JSP cannot connect to MySQL

    When i use applet connect to MySQL, it show that no suitable driver.
    My program is
    import java.applet.*;
    import java.awt.*;
    import java.awt.event.*;
    import javax.swing.*;
    import java.sql.*;
    public class fuck extends JApplet implements ActionListener
    private JButton bb = new JButton("update");
    private JTextArea aa = new JTextArea(1,7);
    private JTextArea ss = new JTextArea(1,7);
    private JPanel pp = new JPanel();
    public fuck()
    Container c=getContentPane();
    pp.add(aa);
    pp.add(ss);
    pp.add(bb);
    c.add(pp);
    bb.addActionListener(this);
    public void actionPerformed(ActionEvent ee)
    try
    Class.forName("org.gjt.mm.mysql.Driver");
    catch(ClassNotFoundException e)
    System.out.println(e.getMessage());
    try
    Connection con =
    DriverManager.getConnection("jdbc:mysql://localhost/air","root","");
    Statement st = con.createStatement();
    //PreparedStatement pst = con.prepareStatement(
    // "update aa set condition=? where temp=?");
    //pst.setInt(1,3);
    //pst.setString(2,"hg");
    //pst.executeUpdate();
    ResultSet rs=
    st.executeQuery("select * from aa");
    while (rs.next())
    aa.setText(rs.getString("temp"));
    ss.setText(rs.getString("condition"));
    st.close();
    con.close();
    catch(SQLException ex)
    System.err.println("SQLException:"+ex.getMessage());
    If I using JSP, it also have some condition

    Clearly it is in the classpath, otherwise the error would have been "Class not found". But here's a quote from the documentation for the driver, the part that explains how to make a connection:// The newInstance() call is a work around for some
    // broken Java implementations
    Class.forName("org.gjt.mm.mysql.Driver").newInstance();The "broken Java implementations" it refers to are certain JVMs that run applets in browsers...

  • Need help for "From concatenate string insert to mysql table"

    Well, most of this problem is a question about SQL syntax. In the VALUES clause you put a comma delimited list of the values to go into the new record. You insert one record at a time. How are the columns defined? Have you done any study on basic SQL?
    Mike...

    i nid to insert values from concatenate string into mysql with using LabSQL, but the result come out from conatenate string is like " 2015-07-08 00:00:00 38.933235E-3" , a logged data of "Date Time Wind Speed(m/s). i nid to put these 3 values into 3 different column in mysql which is Date Time and Wind Speed. How can i pick Date to put inside Date's column, Time into Time's column and Wind Speed into Wind Speed's column in mysql ?
    What i do is
    INSERT INTO wind_speed_data (Date, Time, Wind_Speed) The space in Wind Speed can i put a _ in between Wind Speed? without _ and just put Wind Speed it shows errors.
    VALUES( i have no idea wat to key in at this part ) <--- nid help !
    The Mysql table. Date Time Wind Speed
    The result from concatenate string. Have to insert into mysql.
    My labview program.
    The error i facing.
     

  • Problem with inserting data into mySQL database with jsp

    I have a jsp page that collects infromation about a users vehicle and puts the data into a mySQL database. Iv'e been messing around with it for ages & i can't seem to get it to work even though i cannot see anything wrong with the code, which can be seen below.
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*" errorPage="" %>
    <%@ include file="Connections/connection.jsp" %>
    <%
    // *** Restrict Access To Page: Grant or deny access to this page
    String MM_authorizedUsers="";
    String MM_authFailedURL="login_form.jsp";
    boolean MM_grantAccess=false;
    if (session.getValue("MM_Username") != null && !session.getValue("MM_Username").equals("")) {
      if (true || (session.getValue("MM_UserAuthorization")=="") ||
              (MM_authorizedUsers.indexOf((String)session.getValue("MM_UserAuthorization")) >=0)) {
        MM_grantAccess = true;
    if (!MM_grantAccess) {
      String MM_qsChar = "?";
      if (MM_authFailedURL.indexOf("?") >= 0) MM_qsChar = "&";
      String MM_referrer = request.getRequestURI();
      if (request.getQueryString() != null) MM_referrer = MM_referrer + "?" + request.getQueryString();
      MM_authFailedURL = MM_authFailedURL + MM_qsChar + "accessdenied=" + java.net.URLEncoder.encode(MM_referrer);
      response.sendRedirect(response.encodeRedirectURL(MM_authFailedURL));
      return;
    String vehicle_details__registration = null;
    if(request.getParameter("txt_registration") != null){ vehicle_details__registration = (String)request.getParameter("txt_registration");}
    String vehicle_details__make = null;
    if(request.getParameter("txt_make") != null){ vehicle_details__make = (String)request.getParameter("txt_make");}
    String vehicle_details__model = null;
    if(request.getParameter("txt_model") != null){ vehicle_details__model = (String)request.getParameter("txt_model");}
    String vehicle_details__colour = null;
    if(request.getParameter("txt_colour") != null){ vehicle_details__colour = (String)request.getParameter("txt_colour");}
    String vehicle_details__tax_class = null;
    if(request.getParameter("select_tax_class") != null){ vehicle_details__tax_class = (String)request.getParameter("select_tax_class");}
    String vehicle_details__chasis_num = null;
    if(request.getParameter("chasis_num") != null){ vehicle_details__chasis_num = (String)request.getParameter("chasis_num");}
    String vehicle_details__status = null;
    if(request.getParameter("radio_status") != null){ vehicle_details__status = (String)request.getParameter("radio_status");}
    String owner_details__MMColParam = "1";
    if (session.getValue("MM_Username") !=null) {owner_details__MMColParam = (String)session.getValue("MM_Username");}
    Driver Drivervehicle_details = (Driver)Class.forName(MM_connection_DRIVER).newInstance();
    Connection Connvehicle_details = DriverManager.getConnection(MM_connection_STRING,MM_connection_USERNAME,MM_connection_PASSWORD);
    PreparedStatement vehicle_details = Connvehicle_details.prepareStatement("INSERT INTO vehicle_man_db.vehicle_details (registartion, make, model, colour, tax_class, chasis_num) VALUES ('"+ String vehicle_details__registration + "', '"+ String vehicle_details__make + "', '"+ String vehicle_details__model + "', '"+ String vehicle_details__colour + "', '"+ String vehicle_details__tax_class + "', '"+ String vehicle_details__chasis_num + "', '"+ String vehicle_details__status + "')");
    vehicle_details.executeUpdate();
    %>
    <form name="add_vehicle_form" id="add_vehicle_form">
      <p>Registration mark:
        <input name="txt_registration" type="text" id="txt_registration">
    </p>
      <p>Make:
        <input name="txt_make" type="text" id="txt_make">
    </p>
      <p>Model:
        <input name="txt_model" type="text" id="txt_model">
    </p>
      <p>Colour:
        <input name="txt_colour" type="text" id="txt_colour">
      </p>
      <p>Tax Class:
        <select name="select_tax_class" id="select_tax_class">
          <option value="AAA">Band AAA (up to 100g/km)</option>
          <option value="AA">Band AA (101 - 120g/km)</option>
          <option value="A">Band A (121 - 150g/km)</option>
          <option value="B">Band B (151 - 165g/km)</option>
          <option value="C">Band C (166 - 185g/km)</option>
          <option value="D">Band D (Over 185g/km)</option>
        </select>
      </p>
      <p>Chasis Number:
        <input name="txt_chassis_num" type="text" id="txt_chassis_num">
    </p>
      <p>Status: active:
        <input name="radio_status" type="radio" value="1" checked>
        off-road
        <input name="radio_status" type="radio" value="0">
      </p>
      <p>
        <input type="submit" name="Submit" value="Submit">
    </p>
    </form>
    <%
    Connvehicle_details.close();
    %>This is the error I am getting from the server
    org.apache.jasper.JasperException: Unable to compile class for JSP
    An error occurred at line: 3 in the jsp file: /add_vehicle_form.jsp
    Generated servlet error:
    C:\Servers\Tomcat 5.0\work\Catalina\localhost\Assignment\org\apache\jsp\add_005fvehicle_005fform_jsp.java:113: ')' expected
    PreparedStatement vehicle_details = Connvehicle_details.prepareStatement("INSERT INTO vehicle_man_db.vehicle_details (registartion, make, model, colour, tax_class, chasis_num) VALUES ('"+ String vehicle_details__registration + "', '"+ String vehicle_details__make + "', '"+ String vehicle_details__model + "', '"+ String vehicle_details__colour + "', '"+ String vehicle_details__tax_class + "', '"+ String vehicle_details__chasis_num + "', '"+ String vehicle_details__status + "')");
    ^
    1 error
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:84)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:332)
         org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:412)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:472)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:451)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:439)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:511)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:295)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:292)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:236)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
    Any help would be much appreciated.
    Thanks

    use this ...
    PreparedStatement vehicle_details =
    Connvehicle_details.prepareStatement("INSERT INTO
    vehicle_man_db.vehicle_details (registartion, make,
    model, colour, tax_class, chasis_num) VALUES
    vehicle_details .setString(1,String
    vehicle_details__registration );
    vehicle_details setString(2,String
    vehicle_details__make );
    vehicle_details .setString(3,String
    vehicle_details__model );
    vehicle_details .setString(4,vehicle_details__colour
    vehicle_details .setString(5,String
    vehicle_details__tax_class);
    vehicle_details .setString(6,String
    vehicle_details__chasis_num );
    vehicle_details .executeQuery();Even you need a screwing up... what's the point putting that String inside. That's the bloody error.

Maybe you are looking for