dshfjsh_5455 2013-08-23 02:56
浏览 118
已采纳

MySQL查询错误处理日期字段

I've got a PHP/MySQL script that is yielding strange results on a date field. All along the process, my dates are fine until the very end. The final result has every entry in the date field as '0000-00-00'. I'm totally stuck and don't know what else to do. I can tell that this is an issue with PHP not interpreting this as a date, but I don't know how to fix it. Here is my code:

$sql = "CREATE TABLE temp_workouts (my_date date, sg_id int(11), loc_id int(11))";
$result = mysql_query($sql);
if (!$result) {
    $tag_success = "failure";
    $tag_message = mysql_error();
    echo encodeJSON($tag_success, $tag_message);
    die();
}

$sql = "SELECT * FROM my_table";
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    $my_date = $row['my_date'];
    echo $my_date . " ";   //<--this output looks perfect
    $sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
    $result2 = mysql_query($sql);
}
die();  

When I flip over to MyPHPAdmin and look at the table, the entire column my_date contains '0000-00-00'. How can I get PHP to recognize this as a 'Y-m-d' formatted date? Thanks. I appreciate any help.

  • 写回答

3条回答 默认 最新

  • douhuanbai6729 2013-08-23 03:05
    关注

    Your immediate problem is that you don't use quotes around date values in your insert statement.

    Change

    $sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
    

    to

    $sql = "INSERT INTO temp_table (my_date) VALUES ('$my_date')";
                                                     ^        ^
    

    Now, you can just use INSERT ... SELECT syntax to achieve your goal in one go

    INSERT INTO temp_table (my_date)
    SELECT my_date
      FROM my_table
    

    Therefore this part of your code

    $sql = "SELECT * FROM my_table";
    $result = mysql_query($sql);
    
    while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
        $my_date = $row['my_date'];
        echo $my_date . " ";   //<--this output looks perfect
        $sql = "INSERT INTO temp_table (my_date) VALUES ($my_date)";
        $result2 = mysql_query($sql);
    }
    

    can be changed to

    $sql = "INSERT INTO temp_table (my_date)
            SELECT my_date FROM my_table";
    $result2 = mysql_query($sql);
    

    On a side note: Consider switching to either PDO or MySQLi and use prepared statements.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?