MySQL查询插入" 0"对于所有列值

时间:2013-12-03 01:20:16

标签: php html mysql

我有一个包含5个文本框的HTML表单。单击提交按钮后,表单将提交到名为“admin.php”的页面

admin.php的

<?php
include($_SERVER['DOCUMENT_ROOT'] . '/inc/init.php');
$reference_key = $_POST['reference_key'];
$success = false;
switch ($reference_key)
{
    case 0: break;
    case 2: {
        $date = $_POST['date'];
        $time = $_POST['time'];
        $gym = $_POST['gym'];
        $home = $_POST['home'];
        $away = $_POST['away'];
        $success = "";
        try {
            newGame($db7, $date, $time, $gym, $home, $away);
            $success="index.php";
        }
        catch (Exception $e)
        {
            $success="/404";
        }
        //header("Location: " . $success);
    } break;
    default: break;
}

function newGame($db, $date, $time, $gym, $home, $away)
{
    $db->addGameToSchedule($date, $time, $gym, $home, $away);
}
?>

提交表单时,会传递引用键。引用键的值为“2”,正如您在上面的代码中看到的admin.php,当键为2时,将执行一组特定的代码。如代码中所指出的,函数newGame执行,然后调用函数addGameToSchedule

addGameToSchedule功能:

public function addGameToSchedule($date, $time, $gym, $home, $away) {
    try {
        print "Date: " . $date . "\nTime: " . $time . "\nGym: " . $gym . "\nHome: " . $home . "\nAway: " . $away;
        $sth = $this -> db -> prepare("INSERT INTO schedule (date, time, gym, home, away) VALUES (':date', ':time', ':gym', ':home', ':away')");
        $sth -> execute(array(':date' => $date, ':time' => $time, ':gym' => $gym, ':home' => $home, ':away' => $away));
    } catch (Exception $e) {
        header('Location: /404');
    }
}

函数顶部的print语句用于检查值是否正确传递。执行代码时,print语句会正确打印我输入的信息。但是,当我检查数据库中的新行值时,我只看到插入的5列的“0”。

我做错了什么?如果我需要添加更多信息,请告诉我。

1 个答案:

答案 0 :(得分:2)

不要将参数占位符放在引号内。在引号内,任何不包含数字的文字字符串都会转换为0.就像SELECT 1 + 'abc'返回1 + 0或1一样。

请改为:

$sth = $this -> db -> prepare("INSERT INTO schedule (date, time, gym, home, away)
    VALUES (:date, :time, :gym, :home, :away)");

来自@redolent的评论:

试试这个:

mysql> SELECT ':date' AS value;
+-------+
| value |
+-------+
| :date |
+-------+

引用的字符串是文字,而不是参数占位符。在该示例中,它只是一个字符串文字。

如果我们强制将其解释为数字:

mysql> SELECT 0 + ':date' AS value;
+-------+
| value |
+-------+
|     0 |
+-------+
1 row in set, 1 warning (0.04 sec)

Warning (Code 1292): Truncated incorrect DOUBLE value: ':date'

如果我们强制将其解释为日期:

mysql> SELECT DATE(':date') AS value;
+-------+
| value |
+-------+
| NULL  |
+-------+
1 row in set, 1 warning (0.35 sec)

Warning (Code 1292): Incorrect datetime value: ':date'