用于将数据存储到mysql db中的PHP语法错误

时间:2016-03-26 16:18:22

标签: php mysql

我已经解决了这个问题。以下代码现在可以完美运行。 谢谢你们。

请将dbcontroller.php文件的相关部分说明如下:

<?php
class DBController {


function runQuery2($query) {
    $result = mysql_query($query);
            return $result;
    }

 }

另外,我在我的主html / php文件中修改了我原来的MySQL语句,如下所示:

<?php
 session_start();
 require_once("dbcontroller.php");
 $db_handle = new DBController();


if(!empty($_POST["submit"])) {

  if ($db_handle->runQuery2("INSERT INTO cquestionstable 
  (postid, ccode,    nick, queries) VALUES ( 1,'cc-001', 'james', 'what    
   could be the problem?')") === TRUE) {
    echo "New record created successfully";
     } else {
    echo "Error in posting question, pls try again." . "<br>";
   }

?>

谢天谢地。

1 个答案:

答案 0 :(得分:0)

您的密码:

<?php
    session_start();
    require_once("dbcontroller.php");
    $db_handle = new DBController();

    if(!empty($_POST["submit"])) {

        $sql = "INSERT INTO cquestionstable (postid, ccode, nick, queries) VALUES ( 1,'cc-001', 'james', 'what could be the problem?')";
        if ($db_handle->runQuery($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $**sql . "<br>" . $db_handle->error;
        }
    }
?>

我已经看到了错误。

首先if (!empty($_POST["submit"])) {应为if (isset($_POST["submit"])) {

然后您使用了if ($db_handle->runQuery($sql) === TRUE) {,其实际上应该是if ($conn->query($sql) === TRUE) {

然后在你的回音中你使用了$**sql $sql

然后我不知道dbcontroller.php是什么,但最终的代码应该是

<?php
    // session_start(); You do not need this when inserting into database
    include "dbcontroller.php";

    if (isset($_POST["submit"])) {

        $sql = "INSERT INTO cquestionstable (postid, ccode, nick, queries) VALUES (1, 'cc-001', 'james', 'what could be the problem?')";
        if ($conn->query($sql) === TRUE) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . $connn->error;
        }
    }
?>

dbcontroller.php

<?php

$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
} 

?>

如果您仍然不明白为什么它不起作用,请查看w3Schools

希望这是我们正在寻找的答案。