1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

Php Form To Db

Discussion in 'PHP' started by trenttdogg, Feb 12, 2013.

  1. #1
    I can't get my form to insert data into mysql. Here's the code for the form:
    <form action="insert.php" method="post">
    subject: <input type="text" name="subject">
    category: <input type="text" name="category">
    <input type="submit">
    </form>
    Code (markup):
    and here's my insert.php file
    <?php
    $server = 'localhost';
    $user = 'user_tf';
    $pass = '******';
    $db = '--------';
    $mysqli = new mysqli($server, $user, $pass, $db);
    $mysql_select_db($db);
    $mysql="INSERT INTO worksheets (subject, category)
    VALUES
    ('$_POST[subject]','$_POST[category]')";
    if (!mysql_query($sql))
      {
      die('Error: ' . mysql_error());
      }
    echo "1 record added";
     
    mysql_close();
    ?>
    Code (markup):
    I keep getting this error:
    Fatal error: Function name must be a string in /home/sshirk/public_html/housedogg/test/insert.php on line 7

    Any suggestions would be greatly appreciated.
     
    Solved! View solution.
    trenttdogg, Feb 12, 2013 IP
  2. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #2
    Try storing your connect file in a separate folder and calling it:
    
    include('connect_folder/sqlconnect.php'); 
    //convert vars for cleaner SQL
    $subject   = $_POST['subject'];
    $category = $_POST['category'];
     
    //  insert info into Database 
    mysql_query("INSERT INTO worksheets(subject, category) VALUES('$subject', '$category')"); 
    
    PHP:
    Create your connect file and set it up like this (never have your important info hanging out in the open on a script like that. Its easily aquired and then your database (when its live and not localhost will be up for grabs by anyone) Always put it in top root above the site folder.

    
     
     <?php # mysql_connect.php
     
    // This file contains the database access information.
    // This file also establishes a connection to MySQL and selects the database.
     
    // Set the database access information on constants.
    DEFINE ('DB_USER', 'YourName');
    DEFINE ('DB_PASSWORD', 'YourPassword');
    DEFINE ('DB_HOST', 'localhost');
    DEFINE ('DB_NAME', 'NameofDatabase_NOT_the_table');
     
    // Make the connection.
    $dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die 
      ('Could not connect to MySQL: ' . mysql_error() );
     
    // Select the database.
    @mysql_select_db (DB_NAME) OR die 
      ('Could not select the database: ' . mysql_error() ); 
    ?>
     
    
    PHP:
     
    ezprint2008, Feb 12, 2013 IP
  3. Rukbat

    Rukbat Well-Known Member

    Messages:
    2,908
    Likes Received:
    37
    Best Answers:
    51
    Trophy Points:
    125
    #3
    mysql_select_db($db);
    not
    $mysql_select_db($db);
     
    Rukbat, Feb 12, 2013 IP
  4. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #4
    even if you get it working you should still get your DB connect code off the same page
     
    ezprint2008, Feb 12, 2013 IP
  5. gapz101

    gapz101 Well-Known Member

    Messages:
    524
    Likes Received:
    8
    Best Answers:
    2
    Trophy Points:
    150
    #5
    this :)

    <?php
    $server = 'localhost';
    $user = 'user_tf';
    $pass = '******';
    $db = '--------';
    $mysqli = mysql_connect($server, $user, $pass);
    mysql_select_db($db);
    $sql="INSERT INTO worksheets (subject, category)
    VALUES
    ('{$_POST[subject]}','{$_POST[category]}')";
    if (!mysql_query($sql))
      {
      die('Error: ' . mysql_error());
      }
    echo "1 record added";
     
    mysql_close();
    ?>
    PHP:
     
    gapz101, Feb 12, 2013 IP
  6. trenttdogg

    trenttdogg Greenhorn

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    8
    #6
    I'm still getting an error. Here's my codes. I must be missing something.
    upload.php(form)
    <form action="insert.php" method="post">
    subject: <input type="text" name="subject">
    category: <input type="text" name="category">
    <input type="submit">
    </form>
    Code (markup):
    insert.php
    <?php
    include('http://housedogg.com/test/connect_folder/sql_connect.php');
    //convert vars for cleaner SQL
    $subject  = $_POST['subject'];
    $category = $_POST['category'];
    //  insert info into Database
    mysql_query("INSERT INTO worksheets(subject, category) VALUES('$subject', '$category')");
    ?>
    Code (markup):
    and finally the sql_connect.php
    <?php # mysql_connect.php

    // This file contains the database access information.
    // This file also establishes a connection to MySQL and selects the database.

    // Set the database access information on constants.
    DEFINE ('DB_USER', '*****');
    DEFINE ('DB_PASSWORD', '*****');
    DEFINE ('DB_HOST', '*****');
    DEFINE ('DB_NAME', '*****');

    // Make the connection.
    $dbc = @mysql_connect (DB_HOST, DB_USER, DB_PASSWORD) OR die
    ('Could not connect to MySQL: ' . mysql_error() );

    // Select the database.
    @mysql_select_db (DB_NAME) OR die
    ('Could not select the database: ' . mysql_error() );
    ?>

    I get these errors:
    Warning: mysql_query() [function.mysql-query]: Access denied for user 'sshirk'@'localhost' (using password: NO) in /home/sshirk/public_html/housedogg/test/insert.php on line 7

    Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /home/sshirk/public_html/housedogg/test/insert.php on line 7


    Any suggestions?
     
    trenttdogg, Feb 12, 2013 IP
  7. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #7
    Since you're using mysqli, you probably shouldn't be slapping $_POST directly into the query string since that's insecure/dangerous. You're wide open to code injections. (and shame on everyone for not pointing that out yet :D )

    You also are passing the DB at connect, so you don't need to select_db it...

    ... and you're using the wrong closing statement since mysql_close closes mysql_ functions, NOT mysqli -- big difference one letter makes.

    ... and ease up on the double quotes, they just make life harder.

    <?php
    
    $server = 'localhost';
    $user = 'user_tf';
    $pass = '******';
    $dbName = '--------';
    
    try {
    
    	$db = new mysqli($server, $user, $pass, $dbName);
    
    	$statement = $db->prepare('
    		INSERT INTO worksheets (
    			subject, category
    		) VALUES (
    			?, ?
    		)
    	');
    
    	$statement->bindParam(
    		'ss',
    		$_POST['subject'],
    		$_POST['category']
    	);
    
    	$statement->execute();
    
    	if ($statement->affectedRows == 0) {
    		die('Failed to add Row');
    	} else echo '1 record added<br />';
    	
    catch (mysqli_sql_exception $e) {
    	die('mysqli Error: ',$e->getMessage());
    }
    
    $db->close();
    
    ?>
    Code (markup):
    In theory that die shouldn't ever fire... but it's good to be thorough.

    NOT that I'd be using mysqli -- I prefer PDO since it opens the door to using more than just mySQL, and has a bit cleaner a implementation (IMHO).

    <?php
    
    $host = 'localhost';
    $user = 'user_tf';
    $pass = '******';
    $dbName = '--------';
    
    try {
    
    	$db = new pdo(
    		'mysql:dbname='.$dbName.';host='.$host,
    		$user,
    		$pass
    	);
    
    	$statement = $db->prepare('
    		INSERT INTO worksheets (
    			subject, category
    		) VALUES (
    			:subject, :category
    		)
    	');
    	
    	if ($statement->execute(array(
    		':subject' => $_POST['subject'],
    		':category' => $_POST['category']
    	))) echo '1 record added<br />';
    	
    catch (PDOException $e) {
    	die('PDO Error: ',$e->getMessage());
    }
    
    // pdo closes when released or unset, usually not neccessary
    
    ?>
    Code (markup):
    Either way prepared queries are the way to go -- since they're immune to script injections. It's part of why you shouldn't be using mysql_ functions anymore and should be using mysqli or PDO instead.
     
    deathshadow, Feb 12, 2013 IP
  8. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #8
    Oh lord, your new code is even WORSE -- terrifyingly so... while the re-re's at Wordpress might think it's ok to put your usernames and passwords in DEFINE, where ANY CODE ANYWHERE THAT CALLS IT HAS ACCESS TO YOUR LOGIN INFO, if you care about keeping that stuff secure put that in a function and keep them local in scope.

    But again that's the trap of blind includes.

    Never, EVER put your passwords into DEFINE... I don't know who's been telling people to do that, but they need a good swift kick in the junk.
     
    deathshadow, Feb 12, 2013 IP
  9. trenttdogg

    trenttdogg Greenhorn

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    8
    #9
    Probably a dumb question, but what's pdo and how to i connect it to my db?
     
    trenttdogg, Feb 12, 2013 IP
  10. trenttdogg

    trenttdogg Greenhorn

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    8
    #10
    Nevermind, i see your PDO code. I'll try it. Thanks
     
    trenttdogg, Feb 12, 2013 IP
  11. trenttdogg

    trenttdogg Greenhorn

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    8
    #11
    I tried the PDO technique (i made that my insert.php file, correct?)
    Anyway, this is what i got back:
    Parse error: syntax error, unexpected T_CATCH in /home/sshirk/public_html/housedogg/new_test/insert.php on line 29
     
    trenttdogg, Feb 12, 2013 IP
  12. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #12
    oops, I forgot a } -- put it before the 'catch' line thus:

    } catch (PDOException $e) {
    Code (markup):
    My bad, typo.
     
    deathshadow, Feb 12, 2013 IP
  13. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #13
    Ok, here's some fixed/tested code... that also separates out the database connection -- MIND YOU this code is designed to allow you to connect to the database once and only once. IDEALLY your actual connection and handling should be in a function so $db isn't put into the global space... or make it private to a singleton.

    dbConnect.php
    <?php
    
    function dbConnect() {
    	if (defined('DBCONNECTED')) die ('<p>Hacking Attempt Detected!</p>');
    	define(DBCONNECTED,1);
    	try {
    		return new pdo (
    			'mysql:dbname=______;host=localhost',
    			'user_tf',   // username
    			'******'    // password
    		);
    	} catch (PDOException $e) {
    		die('PDO Error: ',$e->getMessage());
    	}
    }
    
    ?>
    Code (markup):
    insert.php
    <?php
    
    require_once('dbConnect.php');
    $db = dbConnect();
    
    try {
    
    	$statement = $db->prepare('
    		INSERT INTO worksheets (
    			subject, category
    		) VALUES (
    			:subject, :category
    		)
    	');
    	
    	if ($statement->execute(array(
    		':subject' => $_POST['subject'],
    		':category' => $_POST['category']
    	))) echo '1 record added<br />';
    	
    } catch (PDOException $e) {
    	die('PDO Error: ',$e->getMessage());
    }
    
    // pdo closes when released or unset, usually not neccessary
    
    ?>
    Code (markup):
    That should do the job.
     
    deathshadow, Feb 12, 2013 IP
  14. trenttdogg

    trenttdogg Greenhorn

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    8
    #14
    It still gave me the following error on line 22:
    Parse error: syntax error, unexpected ',' in /***/***/public_html/housedogg/new_test/insert.php
     
    trenttdogg, Feb 12, 2013 IP
  15. trenttdogg

    trenttdogg Greenhorn

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    8
    #15
    Yes, this upload form is going to be used by me and only me and I may even put it an htaccess directory if that's possible.
     
    trenttdogg, Feb 12, 2013 IP
  16. trenttdogg

    trenttdogg Greenhorn

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    8
    #16
    I am still getting this error:
    Parse error: syntax error, unexpected ',' in /home/sshirk/public_html/housedogg/connect_PDO/dbConnect.php on line 13

        <?php
       
        function dbConnect() {
            if (defined('DBCONNECTED')) die ('<p>Hacking Attempt Detected!</p>');
            define(DBCONNECTED,1);
            try {
                return new pdo (
                    'mysql:dbname=***;host=localhost',
                    '*****',  // username
                    '*****'    // password
                );
            } catch (PDOException $e) {
                die('PDO Error: ',$e->getMessage());
            }
        }
       
        ?>
    PHP:
    Any help is appreciated.
    Thanks,
     
    trenttdogg, Feb 12, 2013 IP
  17. #17
    Damn, I've got to stop posting from the laptop.

    die('PDO Error: ',$e->getMessage());

    Should be a period, not a comma.

    die('PDO Error: '.$e->getMessage());
     
    deathshadow, Feb 12, 2013 IP
  18. trenttdogg

    trenttdogg Greenhorn

    Messages:
    62
    Likes Received:
    1
    Best Answers:
    0
    Trophy Points:
    8
    #18
    LOL. It worked. I just added a record. YAY!! Thanks for all your help. Now I just need to add some more fields to the form to get it how I want. Then, of course I'll need to retrieve the data from the db and get it to display on my page. Perhaps that for another day;)
     
    trenttdogg, Feb 12, 2013 IP
  19. ezprint2008

    ezprint2008 Well-Known Member

    Messages:
    611
    Likes Received:
    15
    Best Answers:
    2
    Trophy Points:
    140
    Digital Goods:
    1
    #19
    Your form has no action=" " and no method="post" or "get"

    your input boxes have no maxlength (easy to inject 10,000 lines of code or more into your text boxes that easily makes it was to your SQL database and accesses it that way. It's not just your PHP code its your form field. No SQL injection protection. No Maxlengths. You're inserting directly from $_POST['vars'] with no HTML char or other stripping for sanitization. Your database is a sitting duck for a newbie hack that wants to cause you troubles on form injection.

    Forms should have minimum of :
    1. Proper PHP Code
    2. Sanitized process for FORM elements like Maxlength.
    3. a Javascript Validator script to force all fields required be completed.
    4. Sanitized vars from the $_POST into vars that are cleaned, stripped of any characters used in coding/HTML etc.
     
    ezprint2008, Feb 14, 2013 IP
  20. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,998
    Best Answers:
    253
    Trophy Points:
    515
    #20
    Who's that in response to -- OP has that...

    Which is why I suggested using prepared queries, since that sanitizes FOR YOU... at least in terms of SQL injections. Doing things like tag stripping or specialchars escaping would depend on the data and where this form is being used -- if it's admin access, leave it be, you might want markup -- public access, gut the puppy with strip_tags.

    Often a waste of code -- depends on how big the form is, how well you label the inputs, how big the page is -- it's often easier to just label things properly, maybe color code them, than it is to waste scripting on validation.

    Oh, and maxlength is an illusions since you can slap it aside in a heartbeat -- better to limit the size server-side instead than rely on an attribute -- though having that attribute is useful to the user so they can't enter it, just don't rely on it server-side.
     
    deathshadow, Feb 14, 2013 IP