Question

Actually I'm new to this and having problem with insert into property of mysql.

I created two tables namely questions and answers. user can put up data(for both table) through html form. because of some unknown mistake, data is not inserting into the answer table, there is no such problem with question table. Strange thing is that php code of insertion for both tables is almost same excepting variable's name.

singleques_info.php code:

<?PHP

 session_start();
 $t=$_GET['p'];
 $ans= "";
 $error_message = "";
 $num_rows = 0;

 function quote_smart($value, $handle)
 {
     if (get_magic_quotes_gpc()) 
        {
         $value = stripslashes($value);
        }
     if (!is_numeric($value)) 
        {
         $value = "'" . mysql_real_escape_string($value, $handle) . "'";
        }
     return $value;
     }

 if ($_SERVER['REQUEST_METHOD'] == 'POST')
  {
         $ans = $_POST['ans'];
         $ans = htmlspecialchars($ans);
         $uLength = strlen($ans);
         if ($uLength <=100) 
          {
         $error_message = "";
          }
           else 
          {
           $error_message = $error_message . "Username must be between 10 and 20 characters" . "<BR>";
          }


    if ($error_message == "") 
      {
        $username = "root";
        $password = "";
        $database = "techinsight";
        $server = "127.0.0.1";
        $db_handle = mysql_connect($server, $username, $password);
        $db_found = mysql_select_db($database, $db_handle);

        if ($db_found) 
         {
         echo "connected";
         $ans = quote_smart($ans, $db_handle);
         $SQL = "SELECT * FROM answers WHERE answer= $ans";
         $result = mysql_query($SQL);
         $num_rows = mysql_num_rows($result);
          if ($num_rows > 0)
           {
            echo "Question already taken";
           }
            else
           }                          
            $SQL = "INSERT INTO answers (Aid, answer, date) VALUES ($t, $ans, CURDATE())";
            $result = mysql_query($SQL);
            mysql_close($db_handle);

            session_start();
            $_SESSION['login'] = "1";

            header ("Location:ques_wala_main.php");
            echo "You are done.";
           }

        }
         else 
        {
          $errorMessage = "Database Not Found";
        }

      }
      //<div class="content_mess">
  /*    else
        {
           session_start();
           $_SESSION['login'] = "";
           header ("Location: signup.php");
           echo "Please SignIn Before Asking....";
        }
  // </div> */

 }

 ?>

html form :

 <form id="ans" method="POST" name="ans" action="#">
   <div class="field extra">
    <label>your answer:</label> <br/> <br/> <br/>
    <textarea name="ans" cols="70" rows="6"></textarea>
   </div>
   <br/> <br/>
   <input type="submit" name="submit" value="submit" />
 </form>
Était-ce utile?

La solution

The issue has been solved by OP adding the following to the top of script(s):

error_reporting(E_ALL);
ini_set('display_errors', 1);

Having to find out that the mysql_* functions were no longer supported on the server and had to resort to switching to mysqli_* functions.

This having conversed with OP through multiple comments.


When now using mysqli_* functions, (with an extra option):

Add error reporting to the top of your file(s) which will help during production testing.

error_reporting(E_ALL);
ini_set('display_errors', 1);

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

MySQL (error reporting links)


Additional APIs:

Use mysqli with prepared statements, or PDO

PDO error handling:

Autres conseils

This question has already been answered in the comments but I'll expand.

You seem to be puzzled with two aspects. The first is the correct preparation of SQL statements, which you're using here. Each statement consists of two important parts. You specify:

  1. columns of the table you want to use:

    INSERT INTO answers (Aid, answer, date)

  2. and values you want to use with these columns:

    VALUES ($t, $ans, CURDATE())

The MySQL syntax allows you to leave the column names unencapsulated if there are no spaces (or some other characters) in them, so this part is okay. The values however, depending on the columns types might have to be encapsulated with single or double quotes, e.g. you have to encapsulate values for VARCHAR, DATE, DATETIME and BLOB but you shouldn't usually do so for numeric types like INT and DECIMAL or whenever you're telling the MySQL server to calculate something before it inserts the new record (like CURDATE(), 10 + 5 etc.). So assuming your columns are:

Aid    - INT
answer - VARCHAR
date   - DATE

the correct SQL statement would be (notice the single quotes around $ans and lack of quotes around CURDATE()):

INSERT INTO answers (Aid, answer, date) VALUES ($t, '$ans', CURDATE())

The other aspect that seems to confuse you is how PHP deals with strings. What you're doing is telling the PHP to prepare a line of text (string) and pass it into a MySQL server so that the server would run it and pass the result back to the PHP (e.g. mysql_insert_id() is such a result). The thing is PHP from the beginning to the end of this process has no idea what an SQL statement is and how to prepare it. All it knows is "here's a string and I need to put some variables in". So assuming the answer number 32 was a submitted answer, these two parts of your code:

$SQL = "SELECT * FROM answers WHERE answer= $ans";
[...]
$SQL = "INSERT INTO answers (Aid, answer, date) VALUES ($t, $ans, CURDATE())";

would produce the following correct strings but incorrect SQL statements:

SELECT * FROM answers WHERE answer= a submitted answer
INSERT INTO answers (Aid, answer, date) VALUES (32, a submitted answer, CURDATE())

Hopefully the solution is now obvious.

Above said, I'm responding only to pay it forward (all of us had to start somewhere). This coding style is outdated and it's value arguable (even as a means to learn). It never should see a production environment.

EDITED:

Deprecated: mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead

The above should be a notice level and probably isn't an issue. If you want to check whether functions are available run the following script:

<?php
    $a = array(
        'mysql_connect', 
        'mysql_real_escape_string',
        'mysql_query',
        'mysql_fetch_assoc',
    );

    foreach ($a as $f)
        var_dump(function_exists($f));
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top