Updating row on mysql php -
i want update row on table , not updating. html , php code :
<?php if ($_get) { if (isset($_get['id'])) { $id = preg_replace('#[^0-9]#', '', $_get['id']); echo $id; $query = "select * posts id='{$id}'"; $result = mysqli_query($connect, $query); $rows = mysqli_fetch_assoc($result); } elseif (empty($_get['id'])) { header("location: manage_posts.php"); } } ?> <form action="modify_post.php?id=<?php echo $id; ?>" method="post"> <h3>post title <?php //echo $id; ?></h3> <input name="title" value="<?php echo $rows['title'];?>" type="text" placeholder="title here ..." id="title" required> <h3>post content</h3> <textarea name="content" required placeholder="title here ..." style="resize: none"><?php echo $rows['content'];?></textarea> <br/> <input type="submit" value="update" id="submit"/> </form> <?php if ($_server['request_method'] === 'post') { if ($_post['title'] != "" || $_post['content'] != "") { $id = preg_replace('#[^0-9]#', '', $_get['id']); $sql = "update posts set title='{$_post['title']}', content='{$_post['content']}' id='{$id}'"; $update_result = mysqli_query($connect, $sql); if (isset($result)) { echo "<h2>update successfully, redirecting ...</h2>"; } else { echo "record hasn't been updated" . mysqli_errno($result); } header("location: manage_posts.php"); } else { echo "<h3>please fill fields</h3>"; } } ?>
this came !
i don't know problem coming ?
a) avoid sql injections e.g. prepared statements + parameters
b) add more error handling , parameter checking.
<?php if ($_server['request_method'] !== 'post') { echo 'wrong method'; } else if ( !isset($_post['title'], $_post['content']) ) { echo 'missing post parameters'; } else if ( !isset($_get['id']) ) { echo 'missing parameter'; } else if ($_post['title'] == "" || $_post['content'] == "") { echo '<h3>please fill fields</h3>'; } else { $stmt = $connect->prepare('update posts set title=?, content=? id=?'); if ( !$stmt ) { trigger_error('prepare failed', e_user_error); } else if ( !$stmt->bind_param('sss', $_post['title'], $_post['content'], $_get['id']) ) { trigger_error('bind_param failed', e_user_error); } else if ( !$stmt->execute() ) { trigger_error('execute failed', e_user_error); } else { echo '# of updated rows: ', $stmt->affected_rows(); } }
see
Comments
Post a Comment