我的代码没有将数据插入数据库

时间:2012-06-14 19:55:18

标签: php mysql mysqli

我有一个旧的mysql代码,它成功地将值插入数据库。但是因为人们现在声称mysqli更好用(不能使用PDO,因为我的php版本低于5.3),我试图改变我的代码,以便它使用mysqli而不是mysql。

问题是,自从进行此更改后,它现在不会将值插入到数据库中。我是一个mysqli新手所以如果有人可以帮我改变下面的代码,我会非常感激,以便mysqli可以用来将数据插入到数据库中。我究竟做错了什么?错误报告中没有错误。

以下是我目前对此的尝试:

    $username="xxx";
    $password="xxx";
    $database="mobile_app";

      $mysqli = new mysqli("localhost", $username, $password, $database);

      /* check connection */
      if (mysqli_connect_errno()) {
        printf("Connect failed: %s\n", mysqli_connect_error());
        die();
      }

    $sql = "SELECT TeacherId FROM Teacher WHERE (TeacherUsername = ?)";

    $stmt=$mysqli->prepare($sql);
    $stmt->bind_param("s",$_SESSION['teacherusername']);
    $stmt->execute();
    $record = $stmt->fetch();
    $teacherid = $record['TeacherId'];




    if($_SERVER['REQUEST_METHOD'] == 'POST')

    {

    $time = str_replace(array(' Hrs ', ' Mins ', ' Secs'), array(':', ':', ''), $_SESSION['durationChosen']);

    $insertsql = "INSERT INTO Session (SessionId, SessionTime, SessionDate, SessionWeight, SessionDuration, TotalMarks, ModuleId, TeacherId, Room) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
    $insert = $mysqli->prepare($insertsql);


for ($i = 1, $n = $_SESSION['sessionNum']; $i <= $n; ++$i) {
    $sessid = $_SESSION['id'] . ($n == 1 ? '' : $i);
    $sessdate = date("Y-m-d", strtotime($_SESSION['dateChosen']));

    $insert->bind_param("sssssssss", $sessid, $_SESSION['timeChosen'], $sessdate,
                     $_SESSION['textWeight'], $time, $_SESSION['textMarks'],
                     $_SESSION['module'], $teacherid, $_SESSION['rooms']);

    $insert->execute();
}


    }

1 个答案:

答案 0 :(得分:1)

看起来你错过了这一行的结尾引用:

$insertsql = "INSERT INTO Session (
    SessionId, SessionTime, SessionDate, SessionWeight,
    SessionDuration, TotalMarks, ModuleId, TeacherId, Room) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);

成功

$insertsql = "INSERT INTO Session (
    SessionId, SessionTime, SessionDate, SessionWeight,
    SessionDuration, TotalMarks, ModuleId, TeacherId, Room) 
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";

看起来你需要在绑定params之前放置for循环,因为你在绑定中使用了for循环的结果。