[RESOLVED] PHP Beginner Help
Results 1 to 6 of 6

Thread: [RESOLVED] PHP Beginner Help

  1. #1
    Junior Member
    Join Date
    Apr 2012
    Posts
    5

    resolved [RESOLVED] PHP Beginner Help

    Hello All,

    Firstly I would like to let you know that I'm new to this forum and PHP/MySQL. I've been passing PHP/MySQL work to freelancers for years and finally thought to learn it myself. I am familiar with HTML and PHP concepts but am a total beginner.

    Anyway, I am making my first programme in PHP. User simply uses a form to add some text (a comment) into the MySQL database. I have set-up the database on my localhost using Wampserver. I managed to create a setup.php file:

    PHP Code:
    <?php
    include("dbinfo.inc.php");
    mysql_connect(localhost,$username,$password);
    @
    mysql_select_db($database) or die( "Unable to select database");
    $query="CREATE TABLE comments (id int(6) NOT NULL auto_increment,date varchar(10) NOT NULL,comment varchar(200) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))";
    mysql_query($query);
    mysql_close(); 
    echo 
    "Database created";
    ?>
    The above code worked and I now have a table in my database. And I also managed to create an input data form:

    HTML Code:
    <form action="insert.php" method="post">
    Todays Date: <input type="text" name="date"><br>
    Your Comment: <input type="text" name="comment"><br>
    <input type="Submit">
    </form>
    Which should work with this insert.php file:

    PHP Code:
    <?php
    include("dbinfo.inc.php");
    mysql_connect(localhost,$username,$password);
    @
    mysql_select_db($database) or die( "Unable to select database"); 

    $query "INSERT INTO comments VALUES ('','$date','$comment')";
    mysql_query($query);
    mysql_close();
    ?>


    The problem occurs when I try to submit the form. The browser just shows me the source for insert.php, and adds nothing into the database.

    My question is, what am I doing wrong. Thank You in advance for all your help!

    Hab.786
    Last edited by bradgrafelman; 04-16-2012 at 10:25 AM. Reason: bbcode tags added

  2. #2
    Pna lbh ernq guvf¿
    Join Date
    Jul 2004
    Location
    Kansas City area
    Posts
    19,410
    Welcome to PHPBuilder! When posting PHP or HTML code, please use the board's [php]..[/php] or [html]..[/html] bbcode tags (respectively) as they make your code much easier to read and analyze.

    Quote Originally Posted by hab.786 View Post
    I managed to create a setup.php file:

    PHP Code:
    <?php
    include("dbinfo.inc.php");
    mysql_connect(localhost,$username,$password);
    @
    mysql_select_db($database) or die( "Unable to select database");
    $query="CREATE TABLE comments (id int(6) NOT NULL auto_increment,date varchar(10) NOT NULL,comment varchar(200) NOT NULL,PRIMARY KEY (id),UNIQUE id (id),KEY id_2 (id))";
    mysql_query($query);
    mysql_close(); 
    echo 
    "Database created";
    ?>
    Few comments:
    1. You should ensure that display_errors is set to On and error_reporting is set to E_ALL, because this:
      PHP Code:
      mysql_connect(localhost,$username,$password); 
      should be generating an error message (an 'undefined constant' one) since localhost is first being treated as if it were a constant rather than a string; the latter must be delimited in some way (such as with single or double quotes).
    2. Don't use the '@' error suppressor. Ever. (It doesn't do anything helpful; what it does do is simply prevent you from knowing about potential problems with your code.)
    3. The entire mysql extension (e.g. any functions that start with 'mysql_') has been outdated for some time and is deprecated in favor of MySQLi (or even PDO). See mysqlinfo.api.choosing for more info.
    4. You should always check the return value of mysql_query() to see if it returned boolean FALSE (indicating an error has occurred) and, if so, either output or log the MySQL error message (and perhaps the SQL query as well to aid in debugging).
    5. Any reason why you chose to create the table via PHP rather than the MySQL CLI or some GUI front end such as phpMyAdmin?
    6. Couple comments about your table schema:
      1. If you've got a both KEY and UNIQUE are a subset of the PRIMARY KEY type of index, so specifying all three is redundantly redundant, repetitive, and redundant. ()
      2. Why is the `date` column a VARCHAR column and not a... well, a DATE column? (Unless by `date`you're referring to the tasty fruit rather than something you'd find on a calendar.)


    Quote Originally Posted by hab.786 View Post
    Which should work with this insert.php file:

    PHP Code:
    <?php
    include("dbinfo.inc.php");
    mysql_connect(localhost,$username,$password);
    @
    mysql_select_db($database) or die( "Unable to select database"); 

    $query "INSERT INTO comments VALUES ('','$date','$comment')";
    mysql_query($query);
    mysql_close();
    ?>
    Few comments:
    1. Same comments as #1-4 above.
    2. If I showed you this INSERT query:
      Code:
      INSERT INTO myTable VALUES (123, 'foo bar', NULL)
      could you tell me about the columns in this table? Or perhaps just explain which column 'foo bar' is being INSERT'ed in?

      The answer is you can't, because I omitted the column list and instead just threw a bunch of values in a SQL query. Furthermore, if the table structure ever changes, that query could even become broken and/or not behave properly.

      Same problem with your code. IMHO you should always list the columns in an INSERT INTO query, e.g.:
      Code:
      INSERT INTO myTable (id, name, favorite_color) VALUES (123, 'foo bar', NULL)
    3. Assuming you take my above advice, note that AUTO_INCREMENT columns should be omitted altogether from INSERT queries - just leave it out of your column list and VALUES section and MySQL will take care of it on its own. Otherwise, note you should be using NULL - not an empty string (the two are not the same).
    4. Where do you define the variables $date and $comment? Perhaps you meant $_POST['date'] and $_POST['comment'] instead? See the manual page variables.external to learn more about how to access data from external sources (e.g. that which is POST'ed from a form or appears in the query string of the URL).
    5. Note that user-supplied data should never be placed directly into a SQL query string, else your code will be vulnerable to SQL injection attacks and/or just plain SQL errors. Instead, you must first sanitize the data such as with a function like mysql_real_escape_string() (for string data) or by using prepared statements. See security.database.sql-injection for an introduction to the topic of SQL injections if you haven't heard of it before.


    Quote Originally Posted by hab.786 View Post
    The browser just shows me the source for insert.php
    This suggests a much bigger problem; either you aren't accessing the pages via your webserver, or else your webserver isn't passing the requests along to the PHP interpreter and is instead treating the PHP script as if it were any other plain text document (such as HTML) to be sent directly to the user.

    So... how are you accessing the HTML form in your browser?

  3. #3
    Junior Member
    Join Date
    Apr 2012
    Posts
    5
    Wow... so much wrong... :-)

    *Thank you soooooo much for your help!

    Ok, so I was following this manual: http://www.freewebmasterhelp.com/tutorials/phpmysql/3 which was most likely the problem. So I switched to this:

    <?php

    // CONNECTION TO THE MYSQL DATABASE
    $hostname = "localhost"; // change to your hostname
    $db_user = "root"; // change to your database username
    $db_password = ""; // change to your database password
    $database = "internet1"; // provide your database name
    $db_table = "comments"; // leave this as is



    // THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE
    $db = mysql_connect($hostname, $db_user, $db_password);
    mysql_select_db($database,$db);
    ?>


    <html>
    <head>
    <title>ADD COMMENTS</title>
    </head>
    <body>


    <?php
    if (isset($_REQUEST['Submit'])) {
    // THIS CODE TELL MYSQL TO INSERT THE DATA FROM THE FORM INTO YOUR MYSQL TABLE
    $sql = "INSERT INTO $db_table(date,comment) values ('".mysql_real_escape_string(stripslashes($_REQUEST['date']))."','".mysql_real_escape_string(stripslashes($_REQUEST['comment']))."')";
    if($result = mysql_query($sql ,$db)) {
    echo 'Thank you. Your comment has been added.';
    } else {
    echo "ERROR: ".mysql_error();
    }
    } else {
    ?>
    <h1>Add a comment here:</h1>
    <form method="post" action="">
    Date (MM.DD.YY):<br>
    <input type="text" name="date">
    <br>
    Comment: <br>
    <input type="text" name="comment">
    <br><br>
    <input type="submit" name="Submit" value="Submit">
    </form>
    <?php
    }
    ?>
    </body>
    </html>

    And now its working like a charm. Now the issue is, how to export the data saved onto a table in HTML. So for that, I have used this manual: http://www.phpbuilder.com/board/arch...-10207538.html

    But the following code is not working:

    <?php

    $hostname = "localhost"; // change to your hostname
    $db_user = "root"; // change to your database username
    $db_password = ""; // change to your database password
    $database = "internet1"; // provide your database name
    $db_table = "comments"; // leave this as is

    mysql_connect($hostname, $db_user, $db_password)
    mysql_select_db($database);

    print "<TABLE BORDER=0 CELLPADDING=2>\n";
    $fields = mysql_list_fields($database, $db_table);
    $columns = mysql_num_fields($fields);
    print "<TR>";
    for ($x = 0; $x < $columns;$x++) {
    print "<TH>" . mysql_field_name($fields,$x) . "</TH>\n";
    }
    print "</TR>\n";

    $sql = "SELECT * from YOURSQLTABLENAME";
    $result = mysql_query($sql);
    while ($obj = mysql_fetch_object($result,MYSQL_ASSOC)) {
    print "<TR>";
    foreach($obj as $val) {
    print "<TD>" . $val . "</TD>";
    }
    print "</TR>\n";
    }
    echo "</TABLE>\n";

    ?>

    Any help would be appreciated. Thanks again for your above comment.

  4. #4
    Junior Member
    Join Date
    Apr 2012
    Posts
    5
    Ok, I get an error on Line 22:

    <?php

    $hostname = "localhost"; // change to your hostname
    $db_user = "root"; // change to your database username
    $db_password = ""; // change to your database password
    $database = "internet1"; // provide your database name
    $db_table = "comments"; // leave this as is

    mysql_connect($hostname, $db_user, $db_password);

    print "<TABLE BORDER=0 CELLPADDING=2>\n";
    $fields = mysql_list_fields($database, $db_table);
    $columns = mysql_num_fields($fields);
    print "<TR>";
    for ($x = 0; $x < $columns;$x++) {
    print "<TH>" . mysql_field_name($fields,$x) . "</TH>\n";
    }
    print "</TR>\n";

    $sql = "SELECT * from $db_table";
    $result = mysql_query($sql);
    while ($obj = mysql_fetch_object($result,MYSQL_ASSOC)) {
    print "<TR>";
    foreach($obj as $val) {
    print "<TD>" . $val . "</TD>";
    }
    print "</TR>\n";
    }
    echo "</TABLE>\n";

    ?>

  5. #5
    Junior Member
    Join Date
    Apr 2012
    Posts
    5
    All resolved... Solution:

    <?php

    // CONNECTION TO THE MYSQL DATABASE
    $hostname = "localhost"; // change to your hostname
    $db_user = "root"; // change to your database username
    $db_password = ""; // change to your database password
    $database = "internet1"; // provide your database name
    $db_table = "comments"; // leave this as is



    // THIS CODE IS USED TO CONNECT TO THE MYSQL DATABASE
    $db = mysql_connect($hostname, $db_user, $db_password);
    mysql_select_db($database,$db);
    ?>


    <html>
    <head>
    <title>ADD COMMENTS</title>
    </head>
    <body>


    <?php
    if (isset($_REQUEST['Submit'])) {
    // THIS CODE TELL MYSQL TO INSERT THE DATA FROM THE FORM INTO YOUR MYSQL TABLE
    $sql = "INSERT INTO $db_table(date,comment) values ('".mysql_real_escape_string(stripslashes($_REQUEST['date']))."','".mysql_real_escape_string(stripslashes($_REQUEST['comment']))."')";
    if($result = mysql_query($sql ,$db)) {
    echo 'Thank you. Your comment has been added.';
    } else {
    echo "ERROR: ".mysql_error();
    }
    } else {
    ?>
    <h1>Add a comment here:</h1>
    <form method="post" action="">
    Date (MM.DD.YY):<br>
    <input type="text" name="date">
    <br>
    Comment: <br>
    <input type="text" name="comment">
    <br><br>
    <input type="submit" name="Submit" value="Submit">
    </form>
    <?php
    }
    ?>
    </body>
    </html>

  6. #6
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,854
    When posting PHP or HTML code, please use the board's [php]..[/php] or [html]..[/html] bbcode tags (respectively) as they make your code much easier to read and analyze.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •