2015-06-30 7 views
3

Когда я использую следующий код, я не могу вставить данные. Он показывает следующее сообщение об ошибке:PHP не может вставлять данные

Ошибка при вводе данных. Пожалуйста, попробуйте еще раз later.You есть ошибка в вашем SQL синтаксиса: проверьте руководство, которое соответствует Вашей версии сервера MySQL для правильного синтаксиса, чтобы использовать рядом с «)» в строке 10]

if($_SERVER['REQUEST_METHOD'] != 'POST') 
{ 
    $sql = "SELECT 
       cat_id, 
       cat_name, 
       cat_description 
      FROM 
       categories"; 

    $result = mysql_query($sql); 

    if(!$result) 
    { 
     echo 'Error while selecting from database. Please try again later.'; 
    } 
    else 
    { 
     if(mysql_num_rows($result) == 0) 
     { 
      //there are no categories, so a topic can't be posted 
      if($_SESSION['userlevel'] == 1) 
      { 
       echo 'You have not created categories yet.'; 
      } 
      else 
      { 
       echo 'Before you can post a topic, you must wait for an admin to create some categories.'; 
      } 
     } 
     else 
     { 

      echo '<form method="post" action=""> 
       Subject: <input type="text" name="topic_subject" /> 
       Category:'; 

      echo '<select name="topic_cat">'; 
       while($row = mysql_fetch_assoc($result)) 
       { 
        echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>'; 
       } 
      echo '</select>'; 

      echo 'Message: <textarea name="post_content" /></textarea> 
       <input type="submit" value="Create topic" /> 
      </form>'; 
     } 
    } 
} 
else 
{ 
    //start the transaction 
    $query = "BEGIN WORK;"; 
    $result = mysql_query($query); 

    if(!$result) 
    { 
     //Damn! the query failed, quit 
     echo 'An error occured while creating your topic. Please try again later.'; 
    } 
    else 
    { 

     //the form has been posted, so save it 
     //insert the topic into the topics table first, then we'll save the post into the posts table 
     $sql = "INSERT INTO 
        topics(topic_subject, 
          topic_date, 
          topic_cat, 
          topic_by) 
       VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "', 
          NOW(), 
          " . mysql_real_escape_string($_POST['topic_cat']) . ", 
          " . $_SESSION['userid'] . " 
          )"; 

     $result = mysql_query($sql); 
     if(!$result) 
     { 
      //something went wrong, display the error 
      echo 'An error occured while inserting your data. Please try again later.' . mysql_error(); 
      $sql = "ROLLBACK;"; 
      $result = mysql_query($sql); 
     } 
     else 
     { 
      //the first query worked, now start the second, posts query 
      //retrieve the id of the freshly created topic for usage in the posts query 
      $topicid = mysql_insert_id(); 

      $sql = "INSERT INTO 
         posts(post_content, 
           post_date, 
           post_topic, 
           post_by) 
        VALUES 
         ('" . mysql_real_escape_string($_POST['post_content']) . "', 
           NOW(), 
           " . $topicid . ", 
           " . $_SESSION['userid'] . " 
         )"; 
      $result = mysql_query($sql); 

      if(!$result) 
      { 
       //something went wrong, display the error 
       echo 'An error occured while inserting your post. Please try again later.' . mysql_error(); 
       $sql = "ROLLBACK;"; 
       $result = mysql_query($sql); 
      } 
      else 
      { 
       $sql = "COMMIT;"; 
       $result = mysql_query($sql); 

       //after a lot of work, the query succeeded! 
       echo 'You have successfully created <a href="topic.php?id='. $topicid . '">your new topic</a>.'; 
      } 
     } 
    } 
} 

`

+4

Можете ли вы сварить образец кода до одного примера? PHP, который вы нам предоставили, имеет 7 разных вызовов в mysql_query() - что не удается? – Kaoru

+1

то, что я хотел бы сделать здесь, кроме использования PDO или mysqli, - это распечатать ваши запросы непосредственно перед их исполнением, echo $ sql; $ result = mysql_query ($ sql); тогда будет ясно, где проблема. – ArtisticPhoenix

+0

Вы проверили, что $ _SESSION [userid] определен в вашей второй функции sql? – user4467065

ответ

0

ваш запрос здесь enclose ваши строки и значения даты разрыва с "'"

VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "', 
         NOW(), <--- enclose with ."'" 
1

Вы пропустили добавить кавычки вокруг каждой строки:

$sql = "INSERT INTO 
        topics(topic_subject, 
          topic_date, 
          topic_cat, 
          topic_by) 
       VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "', 
          NOW(), 
          '" . mysql_real_escape_string($_POST['topic_cat']) . "', 
          '" . $_SESSION['userid'] . "' 
          )"; 

Вы должны добавить одинарные кавычки вокруг своего второго mysql_real_escape_string. (А также вокруг вашего $_SESSION['userid'], если он содержит строку.)

1
<pre> 
<?php 
$con = mysql_connect('localhost', 'root',''); 
if (!$con) 
{ 
die('Could not connect: ' . mysql_error()); 
} 

mysql_select_db("stack",$con); 

$_SESSION['userlevel']= 1; 
if($_SERVER['REQUEST_METHOD'] != 'POST') 
{ 
    $sql = "SELECT 
       cat_id, 
       cat_name, 
       cat_description 
      FROM 
       categories"; 

    $result = mysql_query($sql); 

    if(!$result) 
    { 
     echo 'Error while selecting from database. Please try again later.'; 
    } 
    else 
    { 
     if(mysql_num_rows($result) == 0) 
     { 
      //there are no categories, so a topic can't be posted 
      if($_SESSION['userlevel'] == 1) 
      { 
       echo 'You have not created categories yet.'; 
      } 
      else 
      { 
       echo 'Before you can post a topic, you must wait for an admin to create some categories.'; 
      } 
     } 
     else 
     { 

      echo '<form method="post" action=""> 
       Subject: <input type="text" name="topic_subject" /> 
       Category:'; 

      echo '<select name="topic_cat">'; 
       while($row = mysql_fetch_assoc($result)) 
       { 
        echo '<option value="' . $row['cat_id'] . '">' . $row['cat_name'] . '</option>'; 
       } 
      echo '</select>'; 

      echo 'Message: <textarea name="post_content" /></textarea> 
       <input type="submit" value="Create topic" /> 
      </form>'; 
     } 
    } 
} 
else 
{ 
    //start the transaction 
    $query = "BEGIN WORK;"; 
    $result = mysql_query($query); 

    if(!$result) 
    { 
     //Damn! the query failed, quit 
     echo 'An error occured while creating your topic. Please try again later.'; 
    } 
    else 
    { 
    $user =1; 
     //the form has been posted, so save it 
     //insert the topic into the topics table first, then we'll save the post into the posts table 
     $sql = "INSERT INTO 
        topics(topic_subject, 
          topic_date, 
          topic_cat, 
          topic_by) 
       VALUES('" . mysql_real_escape_string($_POST['topic_subject']) . "', 
          NOW(), 
          " . mysql_real_escape_string($_POST['topic_cat']) . ", ". $user. " 
          )"; 

     $result = mysql_query($sql); 
     if(!$result) 
     { 
      //something went wrong, display the error 
      echo 'An error occured while inserting your data. Please try again later.' . mysql_error(); 
      $sql = "ROLLBACK;"; 
      $result = mysql_query($sql); 
     } 
     else 
     { 
      //the first query worked, now start the second, posts query 
      //retrieve the id of the freshly created topic for usage in the posts query 
      $topicid = mysql_insert_id(); 

      $sql = "INSERT INTO 
         posts(post_content, 
           post_date, 
           post_topic, 
           post_by) 
        VALUES 
         ('" . mysql_real_escape_string($_POST['post_content']) . "', 
           NOW(), 
           " . $topicid . ",1 
         )"; 
      $result = mysql_query($sql); 

      if(!$result) 
      { 
       //something went wrong, display the error 
       echo 'An error occured while inserting your post. Please try again later.' . mysql_error(); 
       $sql = "ROLLBACK;"; 
       $result = mysql_query($sql); 
      } 
      else 
      { 
       $sql = "COMMIT;"; 
       $result = mysql_query($sql); 

       //after a lot of work, the query succeeded! 
       echo 'You have successfully created <a href="topic.php?id='. $topicid . '">your new topic</a>.'; 
      } 
     } 
    } 
} 
?> 
</pre> 

я использую тот же сценарий, и он работает. проверьте свою сессию, если она создает

Смежные вопросы