I have been unable to figure out how to insert data into My database. I am just learning PHP so please ignore comments

<?php  


if (isset($_POST['submit']))
{
   if (isset($_POST['question']))
   {   
  $DBhost = "localhost";
  $DBuser = "root";
  $DBpass = "";
  $DBName = "exit_poll";
  $table = "exit_reason";
mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database");
    
//@mysql_select_db("$DBName") or die("Unable to select database $DBName");
         $conn = mysql_connect($DBhost,$DBuser,$DBpass) or die('Unable to connect to database'. mysql_error());
//         echo 'Please select only 3 or less'          
//             $Qcount = count(question);

        
            echo 'Please select only 3 or less';
           foreach ($_POST['question'] as $value)
      {    
  
        $sql="INSERT INTO exit_reason (date,$value) VALUES (now(),1)";
        mysql_query($conn, $sql);           

//          $query=mysql_query ("INSERT INTO ($table) SET date = NOW(), (question) VALUE('1')");   SET date = NOW(),
         echo $sql . '<br>'; 

      }
   }
   else
   {
      echo 'Your Vote is Very Important to us.Please select at least 1 reason';
   }
}
          mysql_close($conn);    
?>

any help is greatly appreciated

Recommended Answers

All 8 Replies

I forgot to say my $conn value returns link = 2

I was going to be all descriptive, but the words didn't come to me.
So I just wrote you an example:

<?php
// Isset actually takes an unlimited amount of parameters.
if(isset($_POST['submit'], $_POST['question']))
{
    // Make sure there aren't to many questions selected.
    if(count($_POST['question']) > 3)
    {
        echo "You can only select 3 choices or less. Please LEARN TO READ!";
    }
    else
    {
        // Connect to MySQL
        $dbLink = mysql_connect("host", "user", "pwd") or die(mysql_error());
        mysql_select_db("dbName", $dbLink) or die(mysql_error());

        // Go through the questions and insert them
        $errors = array(); // Used to record errors, if there are any
        foreach($_POST['question'] as $question)
        {
            // Sanitize the question. (Do NOT skip this, or you will be vulnerable to SQL Injection.)
            $question = mysql_real_escape_string($question, $dbLink);

            // Create and execute the query
            $sql = "INSERT INTO tbl(date, {$question}) VALUES(NOW(), 1)";
            if(!mysql_query($sql, $dbLink)) {
                // The query return false... record the error.
                $errors[] = mysql_error($dbLink);
            }
        }

        // Display the results of this all
        $errorCount = count($errors);
        if($errorCount > 0) 
        {
            // Errors were recorderd. Display a error message.
            $totalCount = count($_POST['question']);
            echo "Warning: {$errorCount} of your {$totalCount} items failed to be inserted. <br />";

            // Loop through the recorded error messages and print them.
            for($i = 0; $i < $errorCount; ++$i)
            {
                echo " #{$i} = {$errors[$i]}<br />";
            }
        }
        else 
        {
            // Success!
            echo "Your questions have been inserted!";
        }

        // Close the connection to MySQL
        mysql_close($dbLink);
    }
    
}
else
{
    // Can anybody guess what TV show I'm watching right now? :P
    echo "Please stay on the line. You are the next caller. You'r call is very important to us.";
}
?>

Please let me know if something is unclear.
I'll probably be my descriptive self after a couple of cups of coffee :)

P.S.
Does your IDE display the code that messed up? It's barely readable :S

P.P.S.
Your INSERT query worries me. It's rarely a good thing when you have to dynamically insert field names into queries. Suggests a poor table structure.

If you post the table structure, perhaps I could point out the error, if any.

Thanks I am going to go through it step by step so I can learn, so It may take awhile

... Your INSERT query worries me. It's rarely a good thing when you have to dynamically insert field names into queries. Suggests a poor table structure. ...

There are several reasons I use the '... SET col=name ...' syntax:

  • When written with good spacing, the source code is much more readable and grokable.
  • I don't have to keep printouts of the schemas nearby to see which columns are receiving which data.
  • I don't have to ensure that the data in the VALUES clause are in the correct order.
  • I don't have to change a lot of source code when I later change the database schema.
  • Associative arrays minimize the need to maintain data in schema order.

Unless a very strong argument can be made for performance/efficiency reasons, the order of columns in a schema really don't matter too much. I would sooner go for clarity of source code than for strict source/schema alignment.

There are several reasons I use the '... SET col=name ...' syntax:

Ok. Not exactly sure what this has to do with what I said, but I'll bite.

If you prefer that syntax, I'm fine with that.
I doubt there is a notable performance difference, so the difference is only preferential.

The obvious drawback to this, tho (unless I am missing something), is that you can't do multiple row inserts using this method, like you can with the VALUES clause.

INSERT INTO tbl(field2, field1) VALUES 
('value2', 'value1'), ('value4', 'value3'), ('value6', 'value5');

[*]When written with good spacing, the source code is much more readable and grokable.

Agreed. But this can also bee achieved using the VALUES clause, although column>value matching will obviously not be as easy for readers.
For example:

INSERT INTO tbl(
    `Field1`,
    `Field2`,
    `Field3`
) VALUES (
    'Value1',
    'Value2',
    'Value3'
)

Takes more space, but is more easily readable.

I don't have to change a lot of source code when I later change the database schema.

Neither do those who properly use the VALUES clause.
Meaning, those who actually specify the columns, rather than leaving it empty and having to specify all the columns in an order that MySQL decides on.
For example:

/* Assuming a table with a auto_increment PK 
 * and two varchar fields */

/** A non-column specific INSERT */
/* Here I have to specify a NULL for the PK 
 * and this would break if any alterations were to be made to the table. */
INSERT INTO tbl VALUES (NULL, 'value1', 'value2');

/** The proper way to do that */
/* The PK just gets inserted with the Default value
 * as would any other field added to the table in the future. */
INSERT INTO tbl(field1, field2) VALUES ('value1', 'value2');

/** Note how I re-arrange the fields and values here */
INSERT INTO tbl(field2, field1) VALUES ('value2', 'value1');

Associative arrays minimize the need to maintain data in schema order.

There is no need to "maintain data in schema order" with either method. You can specify the order in the query either way.

<?php
$fieldList = array(
    'Field2' => 'Value2',
    'Field1' => 'Value1'
);

$fields = "`". implode("`, `", array_keys($fieldList)). "`";
$values = "'". implode("', '", $fieldList). "'";

$SQL = "INSERT INTO tbl($fields) VALUES($values)";
// Result:
//  INSERT INTO tbl(`Field2`, `Field1`) VALUES('Value2', 'Value1')
?>

I think I was misunderstood. I could see the code was very good, I could tell that much. I have only been working at this language for two days. I used to do some VB and some very basic c++ back in collage more then 10 years ago. The way I learn is to jump in and learn to swim, but you don't do that without someone to rescue you.

OK you all have been great I am on a fast learning curve. Next I what to secure my database login in another file I did something like this but it did not work

<?php
  $DBhost = "localhost";
  $DBuser = "root";
  $DBpass = "";
  $DBName = "exit_poll";
  $table = "exit_reason";
$dbLink=mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database (mysql_error()");

//@mysql_select_db("$DBName") or die("Unable to select database $DBName");
?>

I then use

include("connect.php")

but it does not seem to pass

$$dbLink=mysql_connect($DBhost,$DBuser,$DBpass) or die("Unable to connect to database (mysql_error()");

I probably using the wrong syntax, as I have always had a problem with language that way. Thank The programming god for spell checkers!

Are you getting an error when you include that?

Your code looks OK, except that you commented out the line where you select a database. If the database info is correct, that should connect and put the resource handle into $dbLink Your code, reformatted:

<?php
/**
 * File: connect.php
 */
$DBhost = "localhost";
$DBuser = "user";
$DBpass = "pwd";
$DBName = "dbName";
$DBTable = "tblName";

$dbLink = @mysql_connect($DBhost,$DBuser,$DBpass)
    or die("Unable to connect to database (". mysql_error() .")");

@mysql_select_db($DBName, $dbLink)
    or die("Unable to select database '{$DBName}'");
?>

And an example of how you would use it:

<?php
/**
 * test.php
 */
include("connect.php");

// Execute a query
$sql = "SELECT * FROM {$DBTable}";
$result = mysql_query($sql, $dbLink)
    or die("Query failed: ". mysql_error($dbLink));

// Display the results
$rowNo = 0;
while($row = mysql_fetch_assoc($result)){
    echo "#", (++$rowNo), "<br />";
    foreach($row as $_key => $_col) {
        echo " - {$_key} = {$_col}<br />";
    }
}
?>

P.S.
Are you using the root account for this?
A very dangerous thing, using the root user in a web application.
You should consider creating another user to use for your PHP code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.