+ Reply to Thread
Results 1 to 8 of 8

Thread: PHP/SQL: Increment Integer Value in Database via Form

  1. #1
    shawntc is offline x10Hosting Member shawntc is an unknown quantity at this point
    Join Date
    Jan 2010
    Posts
    62

    PHP/SQL: Increment Integer Value in Database via Form

    The page in question is http://shawntc.x10hosting.com/picard-page.php

    I'm learning to use PHP/SQL. Pretty much what I'm trying to do is grab an integer value from a database, then when the user clicks a button the value is incremented and stored. The PHP on the server that deals with the SQL:

    Code:
    <?php
    
    // add-picard-starships.php
    
    $a=$_POST["a"];
    $a++;
    $con=mysql_connect("localhost","shawntc_username","wouldntyouliketoknow");
    if(!$con){
      die("Connect failed".mysql_error());
    }
    mysql_select_db("shawntc_test",$con);
    mysql_query("UPDATE StarshipTest SET StarshipsOwned='$aString' WHERE Captain='Picard'");
    $result=mysql_query("SELECT StarshipsOwned FROM StarshipTest WHERE Captain='Picard');
    $row=mysql_fetch_array($result);
    echo $row['StarshipsOwned'];
    mysql_close($con);
    ?>
    But when I press Add to Picard, this is what is returned:
    Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in /home/shawntc/public_html/add-picard-starships.php on line 15

    Grrr it makes no sense to me.
    Last edited by shawntc; 07-10-2010 at 08:09 AM.
    For God so loved the world that he gave is one and only son, that whoever believes in him shall not perish but have eternal life. - John 3:16
    MY SITE!

  2. #2
    leafypiggy's Avatar
    leafypiggy is offline Community Advocate leafypiggy is on a distinguished road
    Join Date
    Aug 2007
    Location
    Massachusetts
    Posts
    2,228
    In your mysql update query, chain $aString to just $a.
    Last edited by leafypiggy; 07-10-2010 at 08:37 AM.
    Neil Hanlon | x10Hosting Support Representative
    Neil[at]x10hosting.com
    █ I'm always happy to help. Just ask a question in Free Hosting
    Terms of Service IRC

  3. #3
    shawntc is offline x10Hosting Member shawntc is an unknown quantity at this point
    Join Date
    Jan 2010
    Posts
    62

    Re: PHP/SQL: Increment Integer Value in Database via Form

    Tried that, both with and without the single quotes around it. Error still persists.
    For God so loved the world that he gave is one and only son, that whoever believes in him shall not perish but have eternal life. - John 3:16
    MY SITE!

  4. #4
    leafypiggy's Avatar
    leafypiggy is offline Community Advocate leafypiggy is on a distinguished road
    Join Date
    Aug 2007
    Location
    Massachusetts
    Posts
    2,228
    Okay. I'll take look when I get on my laptop. iPod isn't he best place for debugging.
    Neil Hanlon | x10Hosting Support Representative
    Neil[at]x10hosting.com
    █ I'm always happy to help. Just ask a question in Free Hosting
    Terms of Service IRC

  5. #5
    lemon-tree's Avatar
    lemon-tree is offline x10 Minion lemon-tree has a spectacular aura about
    Join Date
    Nov 2007
    Posts
    1,420

    Re: PHP/SQL: Increment Integer Value in Database via Form

    Your error is on the line it states, you forgot to close the double-quotes:
    $result=mysql_query("SELECT StarshipsOwned FROM StarshipTest WHERE Captain='Picard'");

  6. #6
    misson is offline x10 Spammer misson is a jewel in the rough
    Join Date
    Mar 2008
    Location
    Libertatia
    Posts
    2,506

    Re: PHP/SQL: Increment Integer Value in Database via Form

    There are a few other issues beyond the error.

    Note: use [php] rather than [code] for PHP code, and it gets colorized. [html] does the same for HTML code.

    Quote Originally Posted by shawntc View Post
    PHP Code:
    $con=mysql_connect("localhost","shawntc_username","wouldntyouliketoknow"); 
    The old mysql driver has been obsoleted twice over, first by mysqli, then PDO. For a tutorial on the latter, read "Writing MySQL Scripts with PHP and PDO".

    Quote Originally Posted by shawntc View Post
    PHP Code:
      die("Connect failed".mysql_error()); 
    Don't use die when outputting HTML.

    Outputting mysql_error to every user reveals too much information.

    Quote Originally Posted by shawntc View Post
    PHP Code:
    mysql_query("UPDATE StarshipTest SET StarshipsOwned='$aString' WHERE Captain='Picard'"); 
    This is open to SQL injection. Normally, I'd say to use prepared statements, but here you can use a different query:
    Code:
    UPDATE StarshipTest SET StarshipsOwned=StarshipsOwned+1 WHERE Captain='Picard'
    This also fixes the problem with tho other query that if multiple users simultaneously access the page and update the table, the last update will clobber the others.
    Be sure to read all pages linked in this post; they have further information that should prove useful. When asking for help, make sure you follow Eric Raymond's and Jon Skeet's guidelines for prompt, accurate responses. Please answer any questions I ask; they're not rhetorical (probably). Any posted code is intended as illustrative example, rather than a solution to your problem to be copied without alteration. Study it to learn how to write your own solution.
    Misson, not Mission.

  7. #7
    shawntc is offline x10Hosting Member shawntc is an unknown quantity at this point
    Join Date
    Jan 2010
    Posts
    62

    Re: PHP/SQL: Increment Integer Value in Database via Form

    Wow. I need an IDE bad.
    For God so loved the world that he gave is one and only son, that whoever believes in him shall not perish but have eternal life. - John 3:16
    MY SITE!

  8. #8
    bdistler's Avatar
    bdistler is offline x10 Lieutenant bdistler is an unknown quantity at this point
    Join Date
    May 2010
    Location
    Catalina AZ USA
    Posts
    349

    Re: PHP/SQL: Increment Integer Value in Database via Form

    Here is something to start with...
    I have NOT thrown it at a database

    PHP Code:
    <?php

    // so we can use the current session ID
    session_start();

    // put ==> include "my_lib.php"; <== here after you make it

    //variables for MySQL database connection S/B in your "my_lib.php" lib file
    //used as "$dbConn = mysql_connect($serverName, $userName, $password)"
    $serverName "localhost";
    $userName "shawntc_username";
    $password "wouldntyouliketoknow";

    // used as "mysql_select_db($dbName, $dbConn)"
    $dbName "shawntc_test";

    // These functions S/B in your php lib file

    function connectToData()
      {
        
    // set in "my_lib.php"
        
    global $serverName$userName$password$dbName;

        
    // get "MySQL link identifier" in $dbConn or die
        
    $dbConn mysql_connect($serverName$userName$password) or die ("<h3>Server unreachable</h3><br />\n");

        
    //connect to MySQL database or die
        
    mysql_select_db($dbName$dbConn) or die ("<h3>Database non existent</h3><br />\n");

        
    //return chl# = "MySQL link identifier"
        
    return $dbConn;
      } 
    // end function connectToData()

    function stripslashes_nested($bugger)
      {
        if (
    is_array($bugger))
          {
            return 
    array_map('stripslashes_nested'$bugger);
          } else
            {
              return 
    stripslashes($bugger);
            }
      } 
    // end function stripslashes_nested($bugger)

    function full_mysql_escape($escapeit)
      {
        
    $escapeit trim($escapeit);
        
    $escapeit mysql_real_escape_string($escapeit);
        
    $escapeit str_replace("`","\`",$escapeit);
        return 
    $escapeit;
      } 
    //end function full_mysql_escape($escapeit)

    // ***************** end of functions *****************

    $debugPrint FALSE;
    // rem out next line to stop debug print
    $debugPrint TRUE;

    $dbTable "StarshipTest";
    $dbField "StarshipsOwned";
    $dbKey "Captain = 'Picard'";

    // NEED TO TEST FOR JUNK HERE
    // data is passed to use via $_POST
    if (get_magic_quotes_gpc())
      {
        
    // if PHP "Magic Quotes" is set on
        // undo the effects of "Magic Quotes" on $_POST
        
    $_POST stripslashes_nested($_POST);
      }

    // pevent SQL Injection Attack with data sent to MySQL database
    // test $value  ** \x00 * \n * \r * \ * ' *` * " * \x1a ** for mysql_real_escape_string($value)
    // mysql_real_escape_string($value) will NOT backslashes "`" (next to far let "1" key on USA key borads
    // so after "mysql_real_escape_string($value)" use "$value = str_replace("`","\`",$value);"

    $a $_POST["a"];
    $a full_mysql_escape($a);

    // I would pass the count as  $_SESSION['count'] also
    //
    // here you need to test the value of $a like:
    // if (($a < $min) || ($a > $max) || ($a != $_SESSION['count'])) do something about the error

    // I would pass session ID as $_SESSION['star'] also
    //
    // $theID = $_SESSION["star"];
    // will not put $theID into MySQL database no need to use ==> full_mysql_escape() <==
    //
    // test for same session
    // if ($theID !== session_id()) do something about NOT same session

    // assume good to work database
    global $dbConn;
    $dbConn connectToData();

    // assume $a is incremented BEFORE passed to us
    $query "UPDATE $dbTable SET $dbField = ' $a ' WHERE $dbKey";

    $result mysql_query($query$dbConn);

    if (!
    $result)
      {
        if (
    $debugPrint) print "Could not successfully run update query (" $query ") <br />  mySQL error: " mysql_error() . "<br />\n";
        print 
    "Finished with error<br />\n";
        exit;
      }

    if (
    mysql_affected_rows($dbConn) == 0)
      {
        if (
    $debugPrint) print "No record updated with query (" $query ") <br />\n";
      }
      elseif (
    mysql_affected_rows($dbConn) > 1)
        {
          if (
    $debugPrint) print "More then one record updated with query (" $query ") <br />\n";
          print 
    "Finished with error<br />\n";
          exit;
        }

    // assume only one $dbKey
    $query "SELECT $dbField FROM $dbTable WHERE $dbKey";

    $result=mysql_query($query$dbConn);

    if (!
    $result)
      {
        if (
    $debugPrint) print "Could not successfully run read-back query (" $query ") <br />  mySQL error: " mysql_error() . "<br />\n";
        print 
    "Finished with error<br />\n";
        exit;
      }

    if (
    mysql_num_rows($result) < 1)
      {
        if (
    $debugPrint) print "No record found at read-back";
        print 
    "Finished with error<br />\n";
        exit;
      }
      elseif (
    mysql_num_rows($result) > 1)
        {
          if (
    $debugPrint) print "More then one record found";
          print 
    "Finished with error<br />\n";
          exit;
        }

    $row mysql_fetch_assoc($result);
    print 
    "You are the owner of $row[$dbField] Starships<br />\n";

    mysql_close($con);
    ?>

+ Reply to Thread

Similar Threads

  1. Exporting a Csv File with zeros as the first integer
    By tillabong in forum Programming Help
    Replies: 14
    Last Post: 07-30-2011, 01:28 PM
  2. [PHP+MySQL] How to get the next auto-increment value
    By farscapeone in forum Tutorials
    Replies: 6
    Last Post: 02-17-2010, 10:29 AM
  3. Problem updating database through form
    By stevet70 in forum Programming Help
    Replies: 3
    Last Post: 08-25-2009, 09:24 PM
  4. row missing in an auto-increment field of DB table
    By anilson1 in forum Programming Help
    Replies: 3
    Last Post: 06-07-2008, 03:47 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
x10hosting free hosting for the masses
dedicated servers