dosi8657 2017-01-10 08:42
浏览 15
已采纳

使用ajax的数据库更新不起作用[关闭]

Why this does't work?

<form id='formprofile' autocomplete='off'>
    <input type='text' name='name' value='<?php echo $row['name'];?>'>
    <input type='text' name='sname' value='<?php echo $row['sname'];?>'>
    <button type='button' id='btnsave'>Save</button>
</form>

javascript

$('#btnsave').click(function(){
$.ajax({
    url: 'profilesave.php',
    type: 'post',
    data: $('#formprofile').serialize(),
    success: function(data) {
        if (data =='empty'){
            alert ('something is missing!');
        }
        else{
            alert ('profile saved');
            location.href = 'index.php';
        }
    }
  });
});

profilesave.php

extract($_POST);

if ($name == ''){
    echo ('empty');
    exit();
}

try {
   $stmt = $db->prepare('UPDATE members SET name = :name, sname = :sname WHERE user = :"' . $user . '"');
   $stmt->execute(array(
    ":name" => $name,
    ":sname" => $sname
   ));
}
catch(PDOException $e) {
   echo $e->getMessage();
}

Database is not updated.
Variable $user is tested, it exists and have a propper value.

Database is not updated.
Variable $user is tested, it exists and have a propper value.

  • 写回答

1条回答 默认 最新

  • douping3891 2017-01-10 08:54
    关注

    Assuming there is probably more content of profilesave.php ( ie: the database include and other variables such as $user ) then you should probably construct the prepared statement like this rather than embedding the value directly. You can test if the statement is created successfully before trying to execute it.

    try{
    
        $name = !empty( $_POST['name'] ) ? $_POST['name'] : false;
        $sname = !empty( $_POST['sname'] ) ? $_POST['sname'] : false;
    
        if( $name && $sname ){
            $stmt = $db->prepare( 'UPDATE members SET name = :name, sname = :sname WHERE user = :user' );
            if( $stmt ){
                $stmt->execute( array(
                        ':name'     =>  $name,
                        ':sname'    =>  $sname,
                        ':user'     =>  $user
                    )
                );
            } else {
                echo 'Prepared statement failed';
            }
        }
    } catch( PDOException $e ){
        echo $e->getMessage();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程